editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use parking_lot::RwLock;
  131use project::{
  132    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub(crate) enum InlayId {
  262    Suggestion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::Suggestion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub suggestions_style: HighlightStyle,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            suggestions_style: HighlightStyle::default(),
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = language_settings::language_settings(None, None, cx)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445enum InlineCompletion {
  446    Edit(Vec<(Range<Anchor>, String)>),
  447    Move(Anchor),
  448}
  449
  450struct InlineCompletionState {
  451    inlay_ids: Vec<InlayId>,
  452    completion: InlineCompletion,
  453    invalidation_range: Range<Anchor>,
  454}
  455
  456enum InlineCompletionHighlight {}
  457
  458#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  459struct EditorActionId(usize);
  460
  461impl EditorActionId {
  462    pub fn post_inc(&mut self) -> Self {
  463        let answer = self.0;
  464
  465        *self = Self(answer + 1);
  466
  467        Self(answer)
  468    }
  469}
  470
  471// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  472// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  473
  474type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  475type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  476
  477#[derive(Default)]
  478struct ScrollbarMarkerState {
  479    scrollbar_size: Size<Pixels>,
  480    dirty: bool,
  481    markers: Arc<[PaintQuad]>,
  482    pending_refresh: Option<Task<Result<()>>>,
  483}
  484
  485impl ScrollbarMarkerState {
  486    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  487        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  488    }
  489}
  490
  491#[derive(Clone, Debug)]
  492struct RunnableTasks {
  493    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  494    offset: MultiBufferOffset,
  495    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  496    column: u32,
  497    // Values of all named captures, including those starting with '_'
  498    extra_variables: HashMap<String, String>,
  499    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  500    context_range: Range<BufferOffset>,
  501}
  502
  503impl RunnableTasks {
  504    fn resolve<'a>(
  505        &'a self,
  506        cx: &'a task::TaskContext,
  507    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  508        self.templates.iter().filter_map(|(kind, template)| {
  509            template
  510                .resolve_task(&kind.to_id_base(), cx)
  511                .map(|task| (kind.clone(), task))
  512        })
  513    }
  514}
  515
  516#[derive(Clone)]
  517struct ResolvedTasks {
  518    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  519    position: Anchor,
  520}
  521#[derive(Copy, Clone, Debug)]
  522struct MultiBufferOffset(usize);
  523#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  524struct BufferOffset(usize);
  525
  526// Addons allow storing per-editor state in other crates (e.g. Vim)
  527pub trait Addon: 'static {
  528    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  529
  530    fn to_any(&self) -> &dyn std::any::Any;
  531}
  532
  533#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  534pub enum IsVimMode {
  535    Yes,
  536    No,
  537}
  538
  539/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  540///
  541/// See the [module level documentation](self) for more information.
  542pub struct Editor {
  543    focus_handle: FocusHandle,
  544    last_focused_descendant: Option<WeakFocusHandle>,
  545    /// The text buffer being edited
  546    buffer: Model<MultiBuffer>,
  547    /// Map of how text in the buffer should be displayed.
  548    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  549    pub display_map: Model<DisplayMap>,
  550    pub selections: SelectionsCollection,
  551    pub scroll_manager: ScrollManager,
  552    /// When inline assist editors are linked, they all render cursors because
  553    /// typing enters text into each of them, even the ones that aren't focused.
  554    pub(crate) show_cursor_when_unfocused: bool,
  555    columnar_selection_tail: Option<Anchor>,
  556    add_selections_state: Option<AddSelectionsState>,
  557    select_next_state: Option<SelectNextState>,
  558    select_prev_state: Option<SelectNextState>,
  559    selection_history: SelectionHistory,
  560    autoclose_regions: Vec<AutocloseRegion>,
  561    snippet_stack: InvalidationStack<SnippetState>,
  562    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  563    ime_transaction: Option<TransactionId>,
  564    active_diagnostics: Option<ActiveDiagnosticGroup>,
  565    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  566
  567    project: Option<Model<Project>>,
  568    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  569    completion_provider: Option<Box<dyn CompletionProvider>>,
  570    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  571    blink_manager: Model<BlinkManager>,
  572    show_cursor_names: bool,
  573    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  574    pub show_local_selections: bool,
  575    mode: EditorMode,
  576    show_breadcrumbs: bool,
  577    show_gutter: bool,
  578    show_line_numbers: Option<bool>,
  579    use_relative_line_numbers: Option<bool>,
  580    show_git_diff_gutter: Option<bool>,
  581    show_code_actions: Option<bool>,
  582    show_runnables: Option<bool>,
  583    show_wrap_guides: Option<bool>,
  584    show_indent_guides: Option<bool>,
  585    placeholder_text: Option<Arc<str>>,
  586    highlight_order: usize,
  587    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  588    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  589    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  590    scrollbar_marker_state: ScrollbarMarkerState,
  591    active_indent_guides_state: ActiveIndentGuidesState,
  592    nav_history: Option<ItemNavHistory>,
  593    context_menu: RwLock<Option<CodeContextMenu>>,
  594    mouse_context_menu: Option<MouseContextMenu>,
  595    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  596    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  597    signature_help_state: SignatureHelpState,
  598    auto_signature_help: Option<bool>,
  599    find_all_references_task_sources: Vec<Anchor>,
  600    next_completion_id: CompletionId,
  601    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  602    code_actions_task: Option<Task<Result<()>>>,
  603    document_highlights_task: Option<Task<()>>,
  604    linked_editing_range_task: Option<Task<Option<()>>>,
  605    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  606    pending_rename: Option<RenameState>,
  607    searchable: bool,
  608    cursor_shape: CursorShape,
  609    current_line_highlight: Option<CurrentLineHighlight>,
  610    collapse_matches: bool,
  611    autoindent_mode: Option<AutoindentMode>,
  612    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  613    input_enabled: bool,
  614    use_modal_editing: bool,
  615    read_only: bool,
  616    leader_peer_id: Option<PeerId>,
  617    remote_id: Option<ViewId>,
  618    hover_state: HoverState,
  619    gutter_hovered: bool,
  620    hovered_link_state: Option<HoveredLinkState>,
  621    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  622    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  623    active_inline_completion: Option<InlineCompletionState>,
  624    // enable_inline_completions is a switch that Vim can use to disable
  625    // inline completions based on its mode.
  626    enable_inline_completions: bool,
  627    show_inline_completions_override: Option<bool>,
  628    inlay_hint_cache: InlayHintCache,
  629    diff_map: DiffMap,
  630    next_inlay_id: usize,
  631    _subscriptions: Vec<Subscription>,
  632    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  633    gutter_dimensions: GutterDimensions,
  634    style: Option<EditorStyle>,
  635    text_style_refinement: Option<TextStyleRefinement>,
  636    next_editor_action_id: EditorActionId,
  637    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  638    use_autoclose: bool,
  639    use_auto_surround: bool,
  640    auto_replace_emoji_shortcode: bool,
  641    show_git_blame_gutter: bool,
  642    show_git_blame_inline: bool,
  643    show_git_blame_inline_delay_task: Option<Task<()>>,
  644    git_blame_inline_enabled: bool,
  645    serialize_dirty_buffers: bool,
  646    show_selection_menu: Option<bool>,
  647    blame: Option<Model<GitBlame>>,
  648    blame_subscription: Option<Subscription>,
  649    custom_context_menu: Option<
  650        Box<
  651            dyn 'static
  652                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  653        >,
  654    >,
  655    last_bounds: Option<Bounds<Pixels>>,
  656    expect_bounds_change: Option<Bounds<Pixels>>,
  657    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  658    tasks_update_task: Option<Task<()>>,
  659    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  660    breadcrumb_header: Option<String>,
  661    focused_block: Option<FocusedBlock>,
  662    next_scroll_position: NextScrollCursorCenterTopBottom,
  663    addons: HashMap<TypeId, Box<dyn Addon>>,
  664    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  665    _scroll_cursor_center_top_bottom_task: Task<()>,
  666}
  667
  668#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  669enum NextScrollCursorCenterTopBottom {
  670    #[default]
  671    Center,
  672    Top,
  673    Bottom,
  674}
  675
  676impl NextScrollCursorCenterTopBottom {
  677    fn next(&self) -> Self {
  678        match self {
  679            Self::Center => Self::Top,
  680            Self::Top => Self::Bottom,
  681            Self::Bottom => Self::Center,
  682        }
  683    }
  684}
  685
  686#[derive(Clone)]
  687pub struct EditorSnapshot {
  688    pub mode: EditorMode,
  689    show_gutter: bool,
  690    show_line_numbers: Option<bool>,
  691    show_git_diff_gutter: Option<bool>,
  692    show_code_actions: Option<bool>,
  693    show_runnables: Option<bool>,
  694    git_blame_gutter_max_author_length: Option<usize>,
  695    pub display_snapshot: DisplaySnapshot,
  696    pub placeholder_text: Option<Arc<str>>,
  697    diff_map: DiffMapSnapshot,
  698    is_focused: bool,
  699    scroll_anchor: ScrollAnchor,
  700    ongoing_scroll: OngoingScroll,
  701    current_line_highlight: CurrentLineHighlight,
  702    gutter_hovered: bool,
  703}
  704
  705const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  706
  707#[derive(Default, Debug, Clone, Copy)]
  708pub struct GutterDimensions {
  709    pub left_padding: Pixels,
  710    pub right_padding: Pixels,
  711    pub width: Pixels,
  712    pub margin: Pixels,
  713    pub git_blame_entries_width: Option<Pixels>,
  714}
  715
  716impl GutterDimensions {
  717    /// The full width of the space taken up by the gutter.
  718    pub fn full_width(&self) -> Pixels {
  719        self.margin + self.width
  720    }
  721
  722    /// The width of the space reserved for the fold indicators,
  723    /// use alongside 'justify_end' and `gutter_width` to
  724    /// right align content with the line numbers
  725    pub fn fold_area_width(&self) -> Pixels {
  726        self.margin + self.right_padding
  727    }
  728}
  729
  730#[derive(Debug)]
  731pub struct RemoteSelection {
  732    pub replica_id: ReplicaId,
  733    pub selection: Selection<Anchor>,
  734    pub cursor_shape: CursorShape,
  735    pub peer_id: PeerId,
  736    pub line_mode: bool,
  737    pub participant_index: Option<ParticipantIndex>,
  738    pub user_name: Option<SharedString>,
  739}
  740
  741#[derive(Clone, Debug)]
  742struct SelectionHistoryEntry {
  743    selections: Arc<[Selection<Anchor>]>,
  744    select_next_state: Option<SelectNextState>,
  745    select_prev_state: Option<SelectNextState>,
  746    add_selections_state: Option<AddSelectionsState>,
  747}
  748
  749enum SelectionHistoryMode {
  750    Normal,
  751    Undoing,
  752    Redoing,
  753}
  754
  755#[derive(Clone, PartialEq, Eq, Hash)]
  756struct HoveredCursor {
  757    replica_id: u16,
  758    selection_id: usize,
  759}
  760
  761impl Default for SelectionHistoryMode {
  762    fn default() -> Self {
  763        Self::Normal
  764    }
  765}
  766
  767#[derive(Default)]
  768struct SelectionHistory {
  769    #[allow(clippy::type_complexity)]
  770    selections_by_transaction:
  771        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  772    mode: SelectionHistoryMode,
  773    undo_stack: VecDeque<SelectionHistoryEntry>,
  774    redo_stack: VecDeque<SelectionHistoryEntry>,
  775}
  776
  777impl SelectionHistory {
  778    fn insert_transaction(
  779        &mut self,
  780        transaction_id: TransactionId,
  781        selections: Arc<[Selection<Anchor>]>,
  782    ) {
  783        self.selections_by_transaction
  784            .insert(transaction_id, (selections, None));
  785    }
  786
  787    #[allow(clippy::type_complexity)]
  788    fn transaction(
  789        &self,
  790        transaction_id: TransactionId,
  791    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  792        self.selections_by_transaction.get(&transaction_id)
  793    }
  794
  795    #[allow(clippy::type_complexity)]
  796    fn transaction_mut(
  797        &mut self,
  798        transaction_id: TransactionId,
  799    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  800        self.selections_by_transaction.get_mut(&transaction_id)
  801    }
  802
  803    fn push(&mut self, entry: SelectionHistoryEntry) {
  804        if !entry.selections.is_empty() {
  805            match self.mode {
  806                SelectionHistoryMode::Normal => {
  807                    self.push_undo(entry);
  808                    self.redo_stack.clear();
  809                }
  810                SelectionHistoryMode::Undoing => self.push_redo(entry),
  811                SelectionHistoryMode::Redoing => self.push_undo(entry),
  812            }
  813        }
  814    }
  815
  816    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  817        if self
  818            .undo_stack
  819            .back()
  820            .map_or(true, |e| e.selections != entry.selections)
  821        {
  822            self.undo_stack.push_back(entry);
  823            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  824                self.undo_stack.pop_front();
  825            }
  826        }
  827    }
  828
  829    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  830        if self
  831            .redo_stack
  832            .back()
  833            .map_or(true, |e| e.selections != entry.selections)
  834        {
  835            self.redo_stack.push_back(entry);
  836            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  837                self.redo_stack.pop_front();
  838            }
  839        }
  840    }
  841}
  842
  843struct RowHighlight {
  844    index: usize,
  845    range: Range<Anchor>,
  846    color: Hsla,
  847    should_autoscroll: bool,
  848}
  849
  850#[derive(Clone, Debug)]
  851struct AddSelectionsState {
  852    above: bool,
  853    stack: Vec<usize>,
  854}
  855
  856#[derive(Clone)]
  857struct SelectNextState {
  858    query: AhoCorasick,
  859    wordwise: bool,
  860    done: bool,
  861}
  862
  863impl std::fmt::Debug for SelectNextState {
  864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  865        f.debug_struct(std::any::type_name::<Self>())
  866            .field("wordwise", &self.wordwise)
  867            .field("done", &self.done)
  868            .finish()
  869    }
  870}
  871
  872#[derive(Debug)]
  873struct AutocloseRegion {
  874    selection_id: usize,
  875    range: Range<Anchor>,
  876    pair: BracketPair,
  877}
  878
  879#[derive(Debug)]
  880struct SnippetState {
  881    ranges: Vec<Vec<Range<Anchor>>>,
  882    active_index: usize,
  883    choices: Vec<Option<Vec<String>>>,
  884}
  885
  886#[doc(hidden)]
  887pub struct RenameState {
  888    pub range: Range<Anchor>,
  889    pub old_name: Arc<str>,
  890    pub editor: View<Editor>,
  891    block_id: CustomBlockId,
  892}
  893
  894struct InvalidationStack<T>(Vec<T>);
  895
  896struct RegisteredInlineCompletionProvider {
  897    provider: Arc<dyn InlineCompletionProviderHandle>,
  898    _subscription: Subscription,
  899}
  900
  901#[derive(Debug)]
  902struct ActiveDiagnosticGroup {
  903    primary_range: Range<Anchor>,
  904    primary_message: String,
  905    group_id: usize,
  906    blocks: HashMap<CustomBlockId, Diagnostic>,
  907    is_valid: bool,
  908}
  909
  910#[derive(Serialize, Deserialize, Clone, Debug)]
  911pub struct ClipboardSelection {
  912    pub len: usize,
  913    pub is_entire_line: bool,
  914    pub first_line_indent: u32,
  915}
  916
  917#[derive(Debug)]
  918pub(crate) struct NavigationData {
  919    cursor_anchor: Anchor,
  920    cursor_position: Point,
  921    scroll_anchor: ScrollAnchor,
  922    scroll_top_row: u32,
  923}
  924
  925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  926pub enum GotoDefinitionKind {
  927    Symbol,
  928    Declaration,
  929    Type,
  930    Implementation,
  931}
  932
  933#[derive(Debug, Clone)]
  934enum InlayHintRefreshReason {
  935    Toggle(bool),
  936    SettingsChange(InlayHintSettings),
  937    NewLinesShown,
  938    BufferEdited(HashSet<Arc<Language>>),
  939    RefreshRequested,
  940    ExcerptsRemoved(Vec<ExcerptId>),
  941}
  942
  943impl InlayHintRefreshReason {
  944    fn description(&self) -> &'static str {
  945        match self {
  946            Self::Toggle(_) => "toggle",
  947            Self::SettingsChange(_) => "settings change",
  948            Self::NewLinesShown => "new lines shown",
  949            Self::BufferEdited(_) => "buffer edited",
  950            Self::RefreshRequested => "refresh requested",
  951            Self::ExcerptsRemoved(_) => "excerpts removed",
  952        }
  953    }
  954}
  955
  956pub(crate) struct FocusedBlock {
  957    id: BlockId,
  958    focus_handle: WeakFocusHandle,
  959}
  960
  961#[derive(Clone)]
  962struct JumpData {
  963    excerpt_id: ExcerptId,
  964    position: Point,
  965    anchor: text::Anchor,
  966    path: Option<project::ProjectPath>,
  967    line_offset_from_top: u32,
  968}
  969
  970impl Editor {
  971    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
  972        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  973        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  974        Self::new(
  975            EditorMode::SingleLine { auto_width: false },
  976            buffer,
  977            None,
  978            false,
  979            cx,
  980        )
  981    }
  982
  983    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
  984        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  985        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  986        Self::new(EditorMode::Full, buffer, None, false, cx)
  987    }
  988
  989    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
  990        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  991        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  992        Self::new(
  993            EditorMode::SingleLine { auto_width: true },
  994            buffer,
  995            None,
  996            false,
  997            cx,
  998        )
  999    }
 1000
 1001    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1002        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1003        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1004        Self::new(
 1005            EditorMode::AutoHeight { max_lines },
 1006            buffer,
 1007            None,
 1008            false,
 1009            cx,
 1010        )
 1011    }
 1012
 1013    pub fn for_buffer(
 1014        buffer: Model<Buffer>,
 1015        project: Option<Model<Project>>,
 1016        cx: &mut ViewContext<Self>,
 1017    ) -> Self {
 1018        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1019        Self::new(EditorMode::Full, buffer, project, false, cx)
 1020    }
 1021
 1022    pub fn for_multibuffer(
 1023        buffer: Model<MultiBuffer>,
 1024        project: Option<Model<Project>>,
 1025        show_excerpt_controls: bool,
 1026        cx: &mut ViewContext<Self>,
 1027    ) -> Self {
 1028        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1029    }
 1030
 1031    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1032        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1033        let mut clone = Self::new(
 1034            self.mode,
 1035            self.buffer.clone(),
 1036            self.project.clone(),
 1037            show_excerpt_controls,
 1038            cx,
 1039        );
 1040        self.display_map.update(cx, |display_map, cx| {
 1041            let snapshot = display_map.snapshot(cx);
 1042            clone.display_map.update(cx, |display_map, cx| {
 1043                display_map.set_state(&snapshot, cx);
 1044            });
 1045        });
 1046        clone.selections.clone_state(&self.selections);
 1047        clone.scroll_manager.clone_state(&self.scroll_manager);
 1048        clone.searchable = self.searchable;
 1049        clone
 1050    }
 1051
 1052    pub fn new(
 1053        mode: EditorMode,
 1054        buffer: Model<MultiBuffer>,
 1055        project: Option<Model<Project>>,
 1056        show_excerpt_controls: bool,
 1057        cx: &mut ViewContext<Self>,
 1058    ) -> Self {
 1059        let style = cx.text_style();
 1060        let font_size = style.font_size.to_pixels(cx.rem_size());
 1061        let editor = cx.view().downgrade();
 1062        let fold_placeholder = FoldPlaceholder {
 1063            constrain_width: true,
 1064            render: Arc::new(move |fold_id, fold_range, cx| {
 1065                let editor = editor.clone();
 1066                div()
 1067                    .id(fold_id)
 1068                    .bg(cx.theme().colors().ghost_element_background)
 1069                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1070                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1071                    .rounded_sm()
 1072                    .size_full()
 1073                    .cursor_pointer()
 1074                    .child("")
 1075                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1076                    .on_click(move |_, cx| {
 1077                        editor
 1078                            .update(cx, |editor, cx| {
 1079                                editor.unfold_ranges(
 1080                                    &[fold_range.start..fold_range.end],
 1081                                    true,
 1082                                    false,
 1083                                    cx,
 1084                                );
 1085                                cx.stop_propagation();
 1086                            })
 1087                            .ok();
 1088                    })
 1089                    .into_any()
 1090            }),
 1091            merge_adjacent: true,
 1092            ..Default::default()
 1093        };
 1094        let display_map = cx.new_model(|cx| {
 1095            DisplayMap::new(
 1096                buffer.clone(),
 1097                style.font(),
 1098                font_size,
 1099                None,
 1100                show_excerpt_controls,
 1101                FILE_HEADER_HEIGHT,
 1102                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1103                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1104                fold_placeholder,
 1105                cx,
 1106            )
 1107        });
 1108
 1109        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1110
 1111        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1112
 1113        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1114            .then(|| language_settings::SoftWrap::None);
 1115
 1116        let mut project_subscriptions = Vec::new();
 1117        if mode == EditorMode::Full {
 1118            if let Some(project) = project.as_ref() {
 1119                if buffer.read(cx).is_singleton() {
 1120                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1121                        cx.emit(EditorEvent::TitleChanged);
 1122                    }));
 1123                }
 1124                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1125                    if let project::Event::RefreshInlayHints = event {
 1126                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1127                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1128                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1129                            let focus_handle = editor.focus_handle(cx);
 1130                            if focus_handle.is_focused(cx) {
 1131                                let snapshot = buffer.read(cx).snapshot();
 1132                                for (range, snippet) in snippet_edits {
 1133                                    let editor_range =
 1134                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1135                                    editor
 1136                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1137                                        .ok();
 1138                                }
 1139                            }
 1140                        }
 1141                    }
 1142                }));
 1143                if let Some(task_inventory) = project
 1144                    .read(cx)
 1145                    .task_store()
 1146                    .read(cx)
 1147                    .task_inventory()
 1148                    .cloned()
 1149                {
 1150                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1151                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1152                    }));
 1153                }
 1154            }
 1155        }
 1156
 1157        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1158
 1159        let inlay_hint_settings =
 1160            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1161        let focus_handle = cx.focus_handle();
 1162        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1163        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1164            .detach();
 1165        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1166            .detach();
 1167        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1168
 1169        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1170            Some(false)
 1171        } else {
 1172            None
 1173        };
 1174
 1175        let mut code_action_providers = Vec::new();
 1176        if let Some(project) = project.clone() {
 1177            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1178            code_action_providers.push(Arc::new(project) as Arc<_>);
 1179        }
 1180
 1181        let mut this = Self {
 1182            focus_handle,
 1183            show_cursor_when_unfocused: false,
 1184            last_focused_descendant: None,
 1185            buffer: buffer.clone(),
 1186            display_map: display_map.clone(),
 1187            selections,
 1188            scroll_manager: ScrollManager::new(cx),
 1189            columnar_selection_tail: None,
 1190            add_selections_state: None,
 1191            select_next_state: None,
 1192            select_prev_state: None,
 1193            selection_history: Default::default(),
 1194            autoclose_regions: Default::default(),
 1195            snippet_stack: Default::default(),
 1196            select_larger_syntax_node_stack: Vec::new(),
 1197            ime_transaction: Default::default(),
 1198            active_diagnostics: None,
 1199            soft_wrap_mode_override,
 1200            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1201            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1202            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1203            project,
 1204            blink_manager: blink_manager.clone(),
 1205            show_local_selections: true,
 1206            mode,
 1207            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1208            show_gutter: mode == EditorMode::Full,
 1209            show_line_numbers: None,
 1210            use_relative_line_numbers: None,
 1211            show_git_diff_gutter: None,
 1212            show_code_actions: None,
 1213            show_runnables: None,
 1214            show_wrap_guides: None,
 1215            show_indent_guides,
 1216            placeholder_text: None,
 1217            highlight_order: 0,
 1218            highlighted_rows: HashMap::default(),
 1219            background_highlights: Default::default(),
 1220            gutter_highlights: TreeMap::default(),
 1221            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1222            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1223            nav_history: None,
 1224            context_menu: RwLock::new(None),
 1225            mouse_context_menu: None,
 1226            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1227            completion_tasks: Default::default(),
 1228            signature_help_state: SignatureHelpState::default(),
 1229            auto_signature_help: None,
 1230            find_all_references_task_sources: Vec::new(),
 1231            next_completion_id: 0,
 1232            next_inlay_id: 0,
 1233            code_action_providers,
 1234            available_code_actions: Default::default(),
 1235            code_actions_task: Default::default(),
 1236            document_highlights_task: Default::default(),
 1237            linked_editing_range_task: Default::default(),
 1238            pending_rename: Default::default(),
 1239            searchable: true,
 1240            cursor_shape: EditorSettings::get_global(cx)
 1241                .cursor_shape
 1242                .unwrap_or_default(),
 1243            current_line_highlight: None,
 1244            autoindent_mode: Some(AutoindentMode::EachLine),
 1245            collapse_matches: false,
 1246            workspace: None,
 1247            input_enabled: true,
 1248            use_modal_editing: mode == EditorMode::Full,
 1249            read_only: false,
 1250            use_autoclose: true,
 1251            use_auto_surround: true,
 1252            auto_replace_emoji_shortcode: false,
 1253            leader_peer_id: None,
 1254            remote_id: None,
 1255            hover_state: Default::default(),
 1256            hovered_link_state: Default::default(),
 1257            inline_completion_provider: None,
 1258            active_inline_completion: None,
 1259            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1260            diff_map: DiffMap::default(),
 1261            gutter_hovered: false,
 1262            pixel_position_of_newest_cursor: None,
 1263            last_bounds: None,
 1264            expect_bounds_change: None,
 1265            gutter_dimensions: GutterDimensions::default(),
 1266            style: None,
 1267            show_cursor_names: false,
 1268            hovered_cursors: Default::default(),
 1269            next_editor_action_id: EditorActionId::default(),
 1270            editor_actions: Rc::default(),
 1271            show_inline_completions_override: None,
 1272            enable_inline_completions: true,
 1273            custom_context_menu: None,
 1274            show_git_blame_gutter: false,
 1275            show_git_blame_inline: false,
 1276            show_selection_menu: None,
 1277            show_git_blame_inline_delay_task: None,
 1278            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1279            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1280                .session
 1281                .restore_unsaved_buffers,
 1282            blame: None,
 1283            blame_subscription: None,
 1284            tasks: Default::default(),
 1285            _subscriptions: vec![
 1286                cx.observe(&buffer, Self::on_buffer_changed),
 1287                cx.subscribe(&buffer, Self::on_buffer_event),
 1288                cx.observe(&display_map, Self::on_display_map_changed),
 1289                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1290                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1291                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1292                cx.observe_window_activation(|editor, cx| {
 1293                    let active = cx.is_window_active();
 1294                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1295                        if active {
 1296                            blink_manager.enable(cx);
 1297                        } else {
 1298                            blink_manager.disable(cx);
 1299                        }
 1300                    });
 1301                }),
 1302            ],
 1303            tasks_update_task: None,
 1304            linked_edit_ranges: Default::default(),
 1305            previous_search_ranges: None,
 1306            breadcrumb_header: None,
 1307            focused_block: None,
 1308            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1309            addons: HashMap::default(),
 1310            registered_buffers: HashMap::default(),
 1311            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1312            text_style_refinement: None,
 1313        };
 1314        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1315        this._subscriptions.extend(project_subscriptions);
 1316
 1317        this.end_selection(cx);
 1318        this.scroll_manager.show_scrollbar(cx);
 1319
 1320        if mode == EditorMode::Full {
 1321            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1322            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1323
 1324            if this.git_blame_inline_enabled {
 1325                this.git_blame_inline_enabled = true;
 1326                this.start_git_blame_inline(false, cx);
 1327            }
 1328
 1329            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1330                if let Some(project) = this.project.as_ref() {
 1331                    let lsp_store = project.read(cx).lsp_store();
 1332                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1333                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1334                    });
 1335                    this.registered_buffers
 1336                        .insert(buffer.read(cx).remote_id(), handle);
 1337                }
 1338            }
 1339        }
 1340
 1341        this.report_editor_event("open", None, cx);
 1342        this
 1343    }
 1344
 1345    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1346        self.mouse_context_menu
 1347            .as_ref()
 1348            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1349    }
 1350
 1351    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1352        let mut key_context = KeyContext::new_with_defaults();
 1353        key_context.add("Editor");
 1354        let mode = match self.mode {
 1355            EditorMode::SingleLine { .. } => "single_line",
 1356            EditorMode::AutoHeight { .. } => "auto_height",
 1357            EditorMode::Full => "full",
 1358        };
 1359
 1360        if EditorSettings::jupyter_enabled(cx) {
 1361            key_context.add("jupyter");
 1362        }
 1363
 1364        key_context.set("mode", mode);
 1365        if self.pending_rename.is_some() {
 1366            key_context.add("renaming");
 1367        }
 1368        if self.context_menu_visible() {
 1369            match self.context_menu.read().as_ref() {
 1370                Some(CodeContextMenu::Completions(_)) => {
 1371                    key_context.add("menu");
 1372                    key_context.add("showing_completions")
 1373                }
 1374                Some(CodeContextMenu::CodeActions(_)) => {
 1375                    key_context.add("menu");
 1376                    key_context.add("showing_code_actions")
 1377                }
 1378                None => {}
 1379            }
 1380        }
 1381
 1382        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1383        if !self.focus_handle(cx).contains_focused(cx)
 1384            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1385        {
 1386            for addon in self.addons.values() {
 1387                addon.extend_key_context(&mut key_context, cx)
 1388            }
 1389        }
 1390
 1391        if let Some(extension) = self
 1392            .buffer
 1393            .read(cx)
 1394            .as_singleton()
 1395            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1396        {
 1397            key_context.set("extension", extension.to_string());
 1398        }
 1399
 1400        if self.has_active_inline_completion() {
 1401            key_context.add("copilot_suggestion");
 1402            key_context.add("inline_completion");
 1403        }
 1404
 1405        if !self
 1406            .selections
 1407            .disjoint
 1408            .iter()
 1409            .all(|selection| selection.start == selection.end)
 1410        {
 1411            key_context.add("selection");
 1412        }
 1413
 1414        key_context
 1415    }
 1416
 1417    pub fn new_file(
 1418        workspace: &mut Workspace,
 1419        _: &workspace::NewFile,
 1420        cx: &mut ViewContext<Workspace>,
 1421    ) {
 1422        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1423            "Failed to create buffer",
 1424            cx,
 1425            |e, _| match e.error_code() {
 1426                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1427                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1428                e.error_tag("required").unwrap_or("the latest version")
 1429            )),
 1430                _ => None,
 1431            },
 1432        );
 1433    }
 1434
 1435    pub fn new_in_workspace(
 1436        workspace: &mut Workspace,
 1437        cx: &mut ViewContext<Workspace>,
 1438    ) -> Task<Result<View<Editor>>> {
 1439        let project = workspace.project().clone();
 1440        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1441
 1442        cx.spawn(|workspace, mut cx| async move {
 1443            let buffer = create.await?;
 1444            workspace.update(&mut cx, |workspace, cx| {
 1445                let editor =
 1446                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1447                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1448                editor
 1449            })
 1450        })
 1451    }
 1452
 1453    fn new_file_vertical(
 1454        workspace: &mut Workspace,
 1455        _: &workspace::NewFileSplitVertical,
 1456        cx: &mut ViewContext<Workspace>,
 1457    ) {
 1458        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1459    }
 1460
 1461    fn new_file_horizontal(
 1462        workspace: &mut Workspace,
 1463        _: &workspace::NewFileSplitHorizontal,
 1464        cx: &mut ViewContext<Workspace>,
 1465    ) {
 1466        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1467    }
 1468
 1469    fn new_file_in_direction(
 1470        workspace: &mut Workspace,
 1471        direction: SplitDirection,
 1472        cx: &mut ViewContext<Workspace>,
 1473    ) {
 1474        let project = workspace.project().clone();
 1475        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1476
 1477        cx.spawn(|workspace, mut cx| async move {
 1478            let buffer = create.await?;
 1479            workspace.update(&mut cx, move |workspace, cx| {
 1480                workspace.split_item(
 1481                    direction,
 1482                    Box::new(
 1483                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1484                    ),
 1485                    cx,
 1486                )
 1487            })?;
 1488            anyhow::Ok(())
 1489        })
 1490        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1491            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1492                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1493                e.error_tag("required").unwrap_or("the latest version")
 1494            )),
 1495            _ => None,
 1496        });
 1497    }
 1498
 1499    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1500        self.leader_peer_id
 1501    }
 1502
 1503    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1504        &self.buffer
 1505    }
 1506
 1507    pub fn workspace(&self) -> Option<View<Workspace>> {
 1508        self.workspace.as_ref()?.0.upgrade()
 1509    }
 1510
 1511    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1512        self.buffer().read(cx).title(cx)
 1513    }
 1514
 1515    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1516        let git_blame_gutter_max_author_length = self
 1517            .render_git_blame_gutter(cx)
 1518            .then(|| {
 1519                if let Some(blame) = self.blame.as_ref() {
 1520                    let max_author_length =
 1521                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1522                    Some(max_author_length)
 1523                } else {
 1524                    None
 1525                }
 1526            })
 1527            .flatten();
 1528
 1529        EditorSnapshot {
 1530            mode: self.mode,
 1531            show_gutter: self.show_gutter,
 1532            show_line_numbers: self.show_line_numbers,
 1533            show_git_diff_gutter: self.show_git_diff_gutter,
 1534            show_code_actions: self.show_code_actions,
 1535            show_runnables: self.show_runnables,
 1536            git_blame_gutter_max_author_length,
 1537            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1538            scroll_anchor: self.scroll_manager.anchor(),
 1539            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1540            placeholder_text: self.placeholder_text.clone(),
 1541            diff_map: self.diff_map.snapshot(),
 1542            is_focused: self.focus_handle.is_focused(cx),
 1543            current_line_highlight: self
 1544                .current_line_highlight
 1545                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1546            gutter_hovered: self.gutter_hovered,
 1547        }
 1548    }
 1549
 1550    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1551        self.buffer.read(cx).language_at(point, cx)
 1552    }
 1553
 1554    pub fn file_at<T: ToOffset>(
 1555        &self,
 1556        point: T,
 1557        cx: &AppContext,
 1558    ) -> Option<Arc<dyn language::File>> {
 1559        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1560    }
 1561
 1562    pub fn active_excerpt(
 1563        &self,
 1564        cx: &AppContext,
 1565    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1566        self.buffer
 1567            .read(cx)
 1568            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1569    }
 1570
 1571    pub fn mode(&self) -> EditorMode {
 1572        self.mode
 1573    }
 1574
 1575    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1576        self.collaboration_hub.as_deref()
 1577    }
 1578
 1579    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1580        self.collaboration_hub = Some(hub);
 1581    }
 1582
 1583    pub fn set_custom_context_menu(
 1584        &mut self,
 1585        f: impl 'static
 1586            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1587    ) {
 1588        self.custom_context_menu = Some(Box::new(f))
 1589    }
 1590
 1591    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1592        self.completion_provider = provider;
 1593    }
 1594
 1595    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1596        self.semantics_provider.clone()
 1597    }
 1598
 1599    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1600        self.semantics_provider = provider;
 1601    }
 1602
 1603    pub fn set_inline_completion_provider<T>(
 1604        &mut self,
 1605        provider: Option<Model<T>>,
 1606        cx: &mut ViewContext<Self>,
 1607    ) where
 1608        T: InlineCompletionProvider,
 1609    {
 1610        self.inline_completion_provider =
 1611            provider.map(|provider| RegisteredInlineCompletionProvider {
 1612                _subscription: cx.observe(&provider, |this, _, cx| {
 1613                    if this.focus_handle.is_focused(cx) {
 1614                        this.update_visible_inline_completion(cx);
 1615                    }
 1616                }),
 1617                provider: Arc::new(provider),
 1618            });
 1619        self.refresh_inline_completion(false, false, cx);
 1620    }
 1621
 1622    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1623        self.placeholder_text.as_deref()
 1624    }
 1625
 1626    pub fn set_placeholder_text(
 1627        &mut self,
 1628        placeholder_text: impl Into<Arc<str>>,
 1629        cx: &mut ViewContext<Self>,
 1630    ) {
 1631        let placeholder_text = Some(placeholder_text.into());
 1632        if self.placeholder_text != placeholder_text {
 1633            self.placeholder_text = placeholder_text;
 1634            cx.notify();
 1635        }
 1636    }
 1637
 1638    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1639        self.cursor_shape = cursor_shape;
 1640
 1641        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1642        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1643
 1644        cx.notify();
 1645    }
 1646
 1647    pub fn set_current_line_highlight(
 1648        &mut self,
 1649        current_line_highlight: Option<CurrentLineHighlight>,
 1650    ) {
 1651        self.current_line_highlight = current_line_highlight;
 1652    }
 1653
 1654    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1655        self.collapse_matches = collapse_matches;
 1656    }
 1657
 1658    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1659        let buffers = self.buffer.read(cx).all_buffers();
 1660        let Some(lsp_store) = self.lsp_store(cx) else {
 1661            return;
 1662        };
 1663        lsp_store.update(cx, |lsp_store, cx| {
 1664            for buffer in buffers {
 1665                self.registered_buffers
 1666                    .entry(buffer.read(cx).remote_id())
 1667                    .or_insert_with(|| {
 1668                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1669                    });
 1670            }
 1671        })
 1672    }
 1673
 1674    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1675        if self.collapse_matches {
 1676            return range.start..range.start;
 1677        }
 1678        range.clone()
 1679    }
 1680
 1681    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1682        if self.display_map.read(cx).clip_at_line_ends != clip {
 1683            self.display_map
 1684                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1685        }
 1686    }
 1687
 1688    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1689        self.input_enabled = input_enabled;
 1690    }
 1691
 1692    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1693        self.enable_inline_completions = enabled;
 1694    }
 1695
 1696    pub fn set_autoindent(&mut self, autoindent: bool) {
 1697        if autoindent {
 1698            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1699        } else {
 1700            self.autoindent_mode = None;
 1701        }
 1702    }
 1703
 1704    pub fn read_only(&self, cx: &AppContext) -> bool {
 1705        self.read_only || self.buffer.read(cx).read_only()
 1706    }
 1707
 1708    pub fn set_read_only(&mut self, read_only: bool) {
 1709        self.read_only = read_only;
 1710    }
 1711
 1712    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1713        self.use_autoclose = autoclose;
 1714    }
 1715
 1716    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1717        self.use_auto_surround = auto_surround;
 1718    }
 1719
 1720    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1721        self.auto_replace_emoji_shortcode = auto_replace;
 1722    }
 1723
 1724    pub fn toggle_inline_completions(
 1725        &mut self,
 1726        _: &ToggleInlineCompletions,
 1727        cx: &mut ViewContext<Self>,
 1728    ) {
 1729        if self.show_inline_completions_override.is_some() {
 1730            self.set_show_inline_completions(None, cx);
 1731        } else {
 1732            let cursor = self.selections.newest_anchor().head();
 1733            if let Some((buffer, cursor_buffer_position)) =
 1734                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1735            {
 1736                let show_inline_completions =
 1737                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1738                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1739            }
 1740        }
 1741    }
 1742
 1743    pub fn set_show_inline_completions(
 1744        &mut self,
 1745        show_inline_completions: Option<bool>,
 1746        cx: &mut ViewContext<Self>,
 1747    ) {
 1748        self.show_inline_completions_override = show_inline_completions;
 1749        self.refresh_inline_completion(false, true, cx);
 1750    }
 1751
 1752    fn should_show_inline_completions(
 1753        &self,
 1754        buffer: &Model<Buffer>,
 1755        buffer_position: language::Anchor,
 1756        cx: &AppContext,
 1757    ) -> bool {
 1758        if !self.snippet_stack.is_empty() {
 1759            return false;
 1760        }
 1761
 1762        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1763            return false;
 1764        }
 1765
 1766        if let Some(provider) = self.inline_completion_provider() {
 1767            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1768                show_inline_completions
 1769            } else {
 1770                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1771            }
 1772        } else {
 1773            false
 1774        }
 1775    }
 1776
 1777    fn inline_completions_disabled_in_scope(
 1778        &self,
 1779        buffer: &Model<Buffer>,
 1780        buffer_position: language::Anchor,
 1781        cx: &AppContext,
 1782    ) -> bool {
 1783        let snapshot = buffer.read(cx).snapshot();
 1784        let settings = snapshot.settings_at(buffer_position, cx);
 1785
 1786        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1787            return false;
 1788        };
 1789
 1790        scope.override_name().map_or(false, |scope_name| {
 1791            settings
 1792                .inline_completions_disabled_in
 1793                .iter()
 1794                .any(|s| s == scope_name)
 1795        })
 1796    }
 1797
 1798    pub fn set_use_modal_editing(&mut self, to: bool) {
 1799        self.use_modal_editing = to;
 1800    }
 1801
 1802    pub fn use_modal_editing(&self) -> bool {
 1803        self.use_modal_editing
 1804    }
 1805
 1806    fn selections_did_change(
 1807        &mut self,
 1808        local: bool,
 1809        old_cursor_position: &Anchor,
 1810        show_completions: bool,
 1811        cx: &mut ViewContext<Self>,
 1812    ) {
 1813        cx.invalidate_character_coordinates();
 1814
 1815        // Copy selections to primary selection buffer
 1816        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1817        if local {
 1818            let selections = self.selections.all::<usize>(cx);
 1819            let buffer_handle = self.buffer.read(cx).read(cx);
 1820
 1821            let mut text = String::new();
 1822            for (index, selection) in selections.iter().enumerate() {
 1823                let text_for_selection = buffer_handle
 1824                    .text_for_range(selection.start..selection.end)
 1825                    .collect::<String>();
 1826
 1827                text.push_str(&text_for_selection);
 1828                if index != selections.len() - 1 {
 1829                    text.push('\n');
 1830                }
 1831            }
 1832
 1833            if !text.is_empty() {
 1834                cx.write_to_primary(ClipboardItem::new_string(text));
 1835            }
 1836        }
 1837
 1838        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1839            self.buffer.update(cx, |buffer, cx| {
 1840                buffer.set_active_selections(
 1841                    &self.selections.disjoint_anchors(),
 1842                    self.selections.line_mode,
 1843                    self.cursor_shape,
 1844                    cx,
 1845                )
 1846            });
 1847        }
 1848        let display_map = self
 1849            .display_map
 1850            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1851        let buffer = &display_map.buffer_snapshot;
 1852        self.add_selections_state = None;
 1853        self.select_next_state = None;
 1854        self.select_prev_state = None;
 1855        self.select_larger_syntax_node_stack.clear();
 1856        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1857        self.snippet_stack
 1858            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1859        self.take_rename(false, cx);
 1860
 1861        let new_cursor_position = self.selections.newest_anchor().head();
 1862
 1863        self.push_to_nav_history(
 1864            *old_cursor_position,
 1865            Some(new_cursor_position.to_point(buffer)),
 1866            cx,
 1867        );
 1868
 1869        if local {
 1870            let new_cursor_position = self.selections.newest_anchor().head();
 1871            let mut context_menu = self.context_menu.write();
 1872            let completion_menu = match context_menu.as_ref() {
 1873                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1874
 1875                _ => {
 1876                    *context_menu = None;
 1877                    None
 1878                }
 1879            };
 1880
 1881            if let Some(completion_menu) = completion_menu {
 1882                let cursor_position = new_cursor_position.to_offset(buffer);
 1883                let (word_range, kind) =
 1884                    buffer.surrounding_word(completion_menu.initial_position, true);
 1885                if kind == Some(CharKind::Word)
 1886                    && word_range.to_inclusive().contains(&cursor_position)
 1887                {
 1888                    let mut completion_menu = completion_menu.clone();
 1889                    drop(context_menu);
 1890
 1891                    let query = Self::completion_query(buffer, cursor_position);
 1892                    cx.spawn(move |this, mut cx| async move {
 1893                        completion_menu
 1894                            .filter(query.as_deref(), cx.background_executor().clone())
 1895                            .await;
 1896
 1897                        this.update(&mut cx, |this, cx| {
 1898                            let mut context_menu = this.context_menu.write();
 1899                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1900                            else {
 1901                                return;
 1902                            };
 1903
 1904                            if menu.id > completion_menu.id {
 1905                                return;
 1906                            }
 1907
 1908                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1909                            drop(context_menu);
 1910                            cx.notify();
 1911                        })
 1912                    })
 1913                    .detach();
 1914
 1915                    if show_completions {
 1916                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1917                    }
 1918                } else {
 1919                    drop(context_menu);
 1920                    self.hide_context_menu(cx);
 1921                }
 1922            } else {
 1923                drop(context_menu);
 1924            }
 1925
 1926            hide_hover(self, cx);
 1927
 1928            if old_cursor_position.to_display_point(&display_map).row()
 1929                != new_cursor_position.to_display_point(&display_map).row()
 1930            {
 1931                self.available_code_actions.take();
 1932            }
 1933            self.refresh_code_actions(cx);
 1934            self.refresh_document_highlights(cx);
 1935            refresh_matching_bracket_highlights(self, cx);
 1936            self.update_visible_inline_completion(cx);
 1937            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1938            if self.git_blame_inline_enabled {
 1939                self.start_inline_blame_timer(cx);
 1940            }
 1941        }
 1942
 1943        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1944        cx.emit(EditorEvent::SelectionsChanged { local });
 1945
 1946        if self.selections.disjoint_anchors().len() == 1 {
 1947            cx.emit(SearchEvent::ActiveMatchChanged)
 1948        }
 1949        cx.notify();
 1950    }
 1951
 1952    pub fn change_selections<R>(
 1953        &mut self,
 1954        autoscroll: Option<Autoscroll>,
 1955        cx: &mut ViewContext<Self>,
 1956        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1957    ) -> R {
 1958        self.change_selections_inner(autoscroll, true, cx, change)
 1959    }
 1960
 1961    pub fn change_selections_inner<R>(
 1962        &mut self,
 1963        autoscroll: Option<Autoscroll>,
 1964        request_completions: bool,
 1965        cx: &mut ViewContext<Self>,
 1966        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1967    ) -> R {
 1968        let old_cursor_position = self.selections.newest_anchor().head();
 1969        self.push_to_selection_history();
 1970
 1971        let (changed, result) = self.selections.change_with(cx, change);
 1972
 1973        if changed {
 1974            if let Some(autoscroll) = autoscroll {
 1975                self.request_autoscroll(autoscroll, cx);
 1976            }
 1977            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 1978
 1979            if self.should_open_signature_help_automatically(
 1980                &old_cursor_position,
 1981                self.signature_help_state.backspace_pressed(),
 1982                cx,
 1983            ) {
 1984                self.show_signature_help(&ShowSignatureHelp, cx);
 1985            }
 1986            self.signature_help_state.set_backspace_pressed(false);
 1987        }
 1988
 1989        result
 1990    }
 1991
 1992    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 1993    where
 1994        I: IntoIterator<Item = (Range<S>, T)>,
 1995        S: ToOffset,
 1996        T: Into<Arc<str>>,
 1997    {
 1998        if self.read_only(cx) {
 1999            return;
 2000        }
 2001
 2002        self.buffer
 2003            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2004    }
 2005
 2006    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2007    where
 2008        I: IntoIterator<Item = (Range<S>, T)>,
 2009        S: ToOffset,
 2010        T: Into<Arc<str>>,
 2011    {
 2012        if self.read_only(cx) {
 2013            return;
 2014        }
 2015
 2016        self.buffer.update(cx, |buffer, cx| {
 2017            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2018        });
 2019    }
 2020
 2021    pub fn edit_with_block_indent<I, S, T>(
 2022        &mut self,
 2023        edits: I,
 2024        original_indent_columns: Vec<u32>,
 2025        cx: &mut ViewContext<Self>,
 2026    ) where
 2027        I: IntoIterator<Item = (Range<S>, T)>,
 2028        S: ToOffset,
 2029        T: Into<Arc<str>>,
 2030    {
 2031        if self.read_only(cx) {
 2032            return;
 2033        }
 2034
 2035        self.buffer.update(cx, |buffer, cx| {
 2036            buffer.edit(
 2037                edits,
 2038                Some(AutoindentMode::Block {
 2039                    original_indent_columns,
 2040                }),
 2041                cx,
 2042            )
 2043        });
 2044    }
 2045
 2046    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2047        self.hide_context_menu(cx);
 2048
 2049        match phase {
 2050            SelectPhase::Begin {
 2051                position,
 2052                add,
 2053                click_count,
 2054            } => self.begin_selection(position, add, click_count, cx),
 2055            SelectPhase::BeginColumnar {
 2056                position,
 2057                goal_column,
 2058                reset,
 2059            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2060            SelectPhase::Extend {
 2061                position,
 2062                click_count,
 2063            } => self.extend_selection(position, click_count, cx),
 2064            SelectPhase::Update {
 2065                position,
 2066                goal_column,
 2067                scroll_delta,
 2068            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2069            SelectPhase::End => self.end_selection(cx),
 2070        }
 2071    }
 2072
 2073    fn extend_selection(
 2074        &mut self,
 2075        position: DisplayPoint,
 2076        click_count: usize,
 2077        cx: &mut ViewContext<Self>,
 2078    ) {
 2079        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2080        let tail = self.selections.newest::<usize>(cx).tail();
 2081        self.begin_selection(position, false, click_count, cx);
 2082
 2083        let position = position.to_offset(&display_map, Bias::Left);
 2084        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2085
 2086        let mut pending_selection = self
 2087            .selections
 2088            .pending_anchor()
 2089            .expect("extend_selection not called with pending selection");
 2090        if position >= tail {
 2091            pending_selection.start = tail_anchor;
 2092        } else {
 2093            pending_selection.end = tail_anchor;
 2094            pending_selection.reversed = true;
 2095        }
 2096
 2097        let mut pending_mode = self.selections.pending_mode().unwrap();
 2098        match &mut pending_mode {
 2099            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2100            _ => {}
 2101        }
 2102
 2103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2104            s.set_pending(pending_selection, pending_mode)
 2105        });
 2106    }
 2107
 2108    fn begin_selection(
 2109        &mut self,
 2110        position: DisplayPoint,
 2111        add: bool,
 2112        click_count: usize,
 2113        cx: &mut ViewContext<Self>,
 2114    ) {
 2115        if !self.focus_handle.is_focused(cx) {
 2116            self.last_focused_descendant = None;
 2117            cx.focus(&self.focus_handle);
 2118        }
 2119
 2120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2121        let buffer = &display_map.buffer_snapshot;
 2122        let newest_selection = self.selections.newest_anchor().clone();
 2123        let position = display_map.clip_point(position, Bias::Left);
 2124
 2125        let start;
 2126        let end;
 2127        let mode;
 2128        let mut auto_scroll;
 2129        match click_count {
 2130            1 => {
 2131                start = buffer.anchor_before(position.to_point(&display_map));
 2132                end = start;
 2133                mode = SelectMode::Character;
 2134                auto_scroll = true;
 2135            }
 2136            2 => {
 2137                let range = movement::surrounding_word(&display_map, position);
 2138                start = buffer.anchor_before(range.start.to_point(&display_map));
 2139                end = buffer.anchor_before(range.end.to_point(&display_map));
 2140                mode = SelectMode::Word(start..end);
 2141                auto_scroll = true;
 2142            }
 2143            3 => {
 2144                let position = display_map
 2145                    .clip_point(position, Bias::Left)
 2146                    .to_point(&display_map);
 2147                let line_start = display_map.prev_line_boundary(position).0;
 2148                let next_line_start = buffer.clip_point(
 2149                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2150                    Bias::Left,
 2151                );
 2152                start = buffer.anchor_before(line_start);
 2153                end = buffer.anchor_before(next_line_start);
 2154                mode = SelectMode::Line(start..end);
 2155                auto_scroll = true;
 2156            }
 2157            _ => {
 2158                start = buffer.anchor_before(0);
 2159                end = buffer.anchor_before(buffer.len());
 2160                mode = SelectMode::All;
 2161                auto_scroll = false;
 2162            }
 2163        }
 2164        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2165
 2166        let point_to_delete: Option<usize> = {
 2167            let selected_points: Vec<Selection<Point>> =
 2168                self.selections.disjoint_in_range(start..end, cx);
 2169
 2170            if !add || click_count > 1 {
 2171                None
 2172            } else if !selected_points.is_empty() {
 2173                Some(selected_points[0].id)
 2174            } else {
 2175                let clicked_point_already_selected =
 2176                    self.selections.disjoint.iter().find(|selection| {
 2177                        selection.start.to_point(buffer) == start.to_point(buffer)
 2178                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2179                    });
 2180
 2181                clicked_point_already_selected.map(|selection| selection.id)
 2182            }
 2183        };
 2184
 2185        let selections_count = self.selections.count();
 2186
 2187        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2188            if let Some(point_to_delete) = point_to_delete {
 2189                s.delete(point_to_delete);
 2190
 2191                if selections_count == 1 {
 2192                    s.set_pending_anchor_range(start..end, mode);
 2193                }
 2194            } else {
 2195                if !add {
 2196                    s.clear_disjoint();
 2197                } else if click_count > 1 {
 2198                    s.delete(newest_selection.id)
 2199                }
 2200
 2201                s.set_pending_anchor_range(start..end, mode);
 2202            }
 2203        });
 2204    }
 2205
 2206    fn begin_columnar_selection(
 2207        &mut self,
 2208        position: DisplayPoint,
 2209        goal_column: u32,
 2210        reset: bool,
 2211        cx: &mut ViewContext<Self>,
 2212    ) {
 2213        if !self.focus_handle.is_focused(cx) {
 2214            self.last_focused_descendant = None;
 2215            cx.focus(&self.focus_handle);
 2216        }
 2217
 2218        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2219
 2220        if reset {
 2221            let pointer_position = display_map
 2222                .buffer_snapshot
 2223                .anchor_before(position.to_point(&display_map));
 2224
 2225            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2226                s.clear_disjoint();
 2227                s.set_pending_anchor_range(
 2228                    pointer_position..pointer_position,
 2229                    SelectMode::Character,
 2230                );
 2231            });
 2232        }
 2233
 2234        let tail = self.selections.newest::<Point>(cx).tail();
 2235        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2236
 2237        if !reset {
 2238            self.select_columns(
 2239                tail.to_display_point(&display_map),
 2240                position,
 2241                goal_column,
 2242                &display_map,
 2243                cx,
 2244            );
 2245        }
 2246    }
 2247
 2248    fn update_selection(
 2249        &mut self,
 2250        position: DisplayPoint,
 2251        goal_column: u32,
 2252        scroll_delta: gpui::Point<f32>,
 2253        cx: &mut ViewContext<Self>,
 2254    ) {
 2255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2256
 2257        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2258            let tail = tail.to_display_point(&display_map);
 2259            self.select_columns(tail, position, goal_column, &display_map, cx);
 2260        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2261            let buffer = self.buffer.read(cx).snapshot(cx);
 2262            let head;
 2263            let tail;
 2264            let mode = self.selections.pending_mode().unwrap();
 2265            match &mode {
 2266                SelectMode::Character => {
 2267                    head = position.to_point(&display_map);
 2268                    tail = pending.tail().to_point(&buffer);
 2269                }
 2270                SelectMode::Word(original_range) => {
 2271                    let original_display_range = original_range.start.to_display_point(&display_map)
 2272                        ..original_range.end.to_display_point(&display_map);
 2273                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2274                        ..original_display_range.end.to_point(&display_map);
 2275                    if movement::is_inside_word(&display_map, position)
 2276                        || original_display_range.contains(&position)
 2277                    {
 2278                        let word_range = movement::surrounding_word(&display_map, position);
 2279                        if word_range.start < original_display_range.start {
 2280                            head = word_range.start.to_point(&display_map);
 2281                        } else {
 2282                            head = word_range.end.to_point(&display_map);
 2283                        }
 2284                    } else {
 2285                        head = position.to_point(&display_map);
 2286                    }
 2287
 2288                    if head <= original_buffer_range.start {
 2289                        tail = original_buffer_range.end;
 2290                    } else {
 2291                        tail = original_buffer_range.start;
 2292                    }
 2293                }
 2294                SelectMode::Line(original_range) => {
 2295                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2296
 2297                    let position = display_map
 2298                        .clip_point(position, Bias::Left)
 2299                        .to_point(&display_map);
 2300                    let line_start = display_map.prev_line_boundary(position).0;
 2301                    let next_line_start = buffer.clip_point(
 2302                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2303                        Bias::Left,
 2304                    );
 2305
 2306                    if line_start < original_range.start {
 2307                        head = line_start
 2308                    } else {
 2309                        head = next_line_start
 2310                    }
 2311
 2312                    if head <= original_range.start {
 2313                        tail = original_range.end;
 2314                    } else {
 2315                        tail = original_range.start;
 2316                    }
 2317                }
 2318                SelectMode::All => {
 2319                    return;
 2320                }
 2321            };
 2322
 2323            if head < tail {
 2324                pending.start = buffer.anchor_before(head);
 2325                pending.end = buffer.anchor_before(tail);
 2326                pending.reversed = true;
 2327            } else {
 2328                pending.start = buffer.anchor_before(tail);
 2329                pending.end = buffer.anchor_before(head);
 2330                pending.reversed = false;
 2331            }
 2332
 2333            self.change_selections(None, cx, |s| {
 2334                s.set_pending(pending, mode);
 2335            });
 2336        } else {
 2337            log::error!("update_selection dispatched with no pending selection");
 2338            return;
 2339        }
 2340
 2341        self.apply_scroll_delta(scroll_delta, cx);
 2342        cx.notify();
 2343    }
 2344
 2345    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2346        self.columnar_selection_tail.take();
 2347        if self.selections.pending_anchor().is_some() {
 2348            let selections = self.selections.all::<usize>(cx);
 2349            self.change_selections(None, cx, |s| {
 2350                s.select(selections);
 2351                s.clear_pending();
 2352            });
 2353        }
 2354    }
 2355
 2356    fn select_columns(
 2357        &mut self,
 2358        tail: DisplayPoint,
 2359        head: DisplayPoint,
 2360        goal_column: u32,
 2361        display_map: &DisplaySnapshot,
 2362        cx: &mut ViewContext<Self>,
 2363    ) {
 2364        let start_row = cmp::min(tail.row(), head.row());
 2365        let end_row = cmp::max(tail.row(), head.row());
 2366        let start_column = cmp::min(tail.column(), goal_column);
 2367        let end_column = cmp::max(tail.column(), goal_column);
 2368        let reversed = start_column < tail.column();
 2369
 2370        let selection_ranges = (start_row.0..=end_row.0)
 2371            .map(DisplayRow)
 2372            .filter_map(|row| {
 2373                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2374                    let start = display_map
 2375                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2376                        .to_point(display_map);
 2377                    let end = display_map
 2378                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2379                        .to_point(display_map);
 2380                    if reversed {
 2381                        Some(end..start)
 2382                    } else {
 2383                        Some(start..end)
 2384                    }
 2385                } else {
 2386                    None
 2387                }
 2388            })
 2389            .collect::<Vec<_>>();
 2390
 2391        self.change_selections(None, cx, |s| {
 2392            s.select_ranges(selection_ranges);
 2393        });
 2394        cx.notify();
 2395    }
 2396
 2397    pub fn has_pending_nonempty_selection(&self) -> bool {
 2398        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2399            Some(Selection { start, end, .. }) => start != end,
 2400            None => false,
 2401        };
 2402
 2403        pending_nonempty_selection
 2404            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2405    }
 2406
 2407    pub fn has_pending_selection(&self) -> bool {
 2408        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2409    }
 2410
 2411    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2412        if self.clear_expanded_diff_hunks(cx) {
 2413            cx.notify();
 2414            return;
 2415        }
 2416        if self.dismiss_menus_and_popups(true, cx) {
 2417            return;
 2418        }
 2419
 2420        if self.mode == EditorMode::Full
 2421            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2422        {
 2423            return;
 2424        }
 2425
 2426        cx.propagate();
 2427    }
 2428
 2429    pub fn dismiss_menus_and_popups(
 2430        &mut self,
 2431        should_report_inline_completion_event: bool,
 2432        cx: &mut ViewContext<Self>,
 2433    ) -> bool {
 2434        if self.take_rename(false, cx).is_some() {
 2435            return true;
 2436        }
 2437
 2438        if hide_hover(self, cx) {
 2439            return true;
 2440        }
 2441
 2442        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2443            return true;
 2444        }
 2445
 2446        if self.hide_context_menu(cx).is_some() {
 2447            return true;
 2448        }
 2449
 2450        if self.mouse_context_menu.take().is_some() {
 2451            return true;
 2452        }
 2453
 2454        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2455            return true;
 2456        }
 2457
 2458        if self.snippet_stack.pop().is_some() {
 2459            return true;
 2460        }
 2461
 2462        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2463            self.dismiss_diagnostics(cx);
 2464            return true;
 2465        }
 2466
 2467        false
 2468    }
 2469
 2470    fn linked_editing_ranges_for(
 2471        &self,
 2472        selection: Range<text::Anchor>,
 2473        cx: &AppContext,
 2474    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2475        if self.linked_edit_ranges.is_empty() {
 2476            return None;
 2477        }
 2478        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2479            selection.end.buffer_id.and_then(|end_buffer_id| {
 2480                if selection.start.buffer_id != Some(end_buffer_id) {
 2481                    return None;
 2482                }
 2483                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2484                let snapshot = buffer.read(cx).snapshot();
 2485                self.linked_edit_ranges
 2486                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2487                    .map(|ranges| (ranges, snapshot, buffer))
 2488            })?;
 2489        use text::ToOffset as TO;
 2490        // find offset from the start of current range to current cursor position
 2491        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2492
 2493        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2494        let start_difference = start_offset - start_byte_offset;
 2495        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2496        let end_difference = end_offset - start_byte_offset;
 2497        // Current range has associated linked ranges.
 2498        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2499        for range in linked_ranges.iter() {
 2500            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2501            let end_offset = start_offset + end_difference;
 2502            let start_offset = start_offset + start_difference;
 2503            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2504                continue;
 2505            }
 2506            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2507                if s.start.buffer_id != selection.start.buffer_id
 2508                    || s.end.buffer_id != selection.end.buffer_id
 2509                {
 2510                    return false;
 2511                }
 2512                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2513                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2514            }) {
 2515                continue;
 2516            }
 2517            let start = buffer_snapshot.anchor_after(start_offset);
 2518            let end = buffer_snapshot.anchor_after(end_offset);
 2519            linked_edits
 2520                .entry(buffer.clone())
 2521                .or_default()
 2522                .push(start..end);
 2523        }
 2524        Some(linked_edits)
 2525    }
 2526
 2527    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2528        let text: Arc<str> = text.into();
 2529
 2530        if self.read_only(cx) {
 2531            return;
 2532        }
 2533
 2534        let selections = self.selections.all_adjusted(cx);
 2535        let mut bracket_inserted = false;
 2536        let mut edits = Vec::new();
 2537        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2538        let mut new_selections = Vec::with_capacity(selections.len());
 2539        let mut new_autoclose_regions = Vec::new();
 2540        let snapshot = self.buffer.read(cx).read(cx);
 2541
 2542        for (selection, autoclose_region) in
 2543            self.selections_with_autoclose_regions(selections, &snapshot)
 2544        {
 2545            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2546                // Determine if the inserted text matches the opening or closing
 2547                // bracket of any of this language's bracket pairs.
 2548                let mut bracket_pair = None;
 2549                let mut is_bracket_pair_start = false;
 2550                let mut is_bracket_pair_end = false;
 2551                if !text.is_empty() {
 2552                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2553                    //  and they are removing the character that triggered IME popup.
 2554                    for (pair, enabled) in scope.brackets() {
 2555                        if !pair.close && !pair.surround {
 2556                            continue;
 2557                        }
 2558
 2559                        if enabled && pair.start.ends_with(text.as_ref()) {
 2560                            let prefix_len = pair.start.len() - text.len();
 2561                            let preceding_text_matches_prefix = prefix_len == 0
 2562                                || (selection.start.column >= (prefix_len as u32)
 2563                                    && snapshot.contains_str_at(
 2564                                        Point::new(
 2565                                            selection.start.row,
 2566                                            selection.start.column - (prefix_len as u32),
 2567                                        ),
 2568                                        &pair.start[..prefix_len],
 2569                                    ));
 2570                            if preceding_text_matches_prefix {
 2571                                bracket_pair = Some(pair.clone());
 2572                                is_bracket_pair_start = true;
 2573                                break;
 2574                            }
 2575                        }
 2576                        if pair.end.as_str() == text.as_ref() {
 2577                            bracket_pair = Some(pair.clone());
 2578                            is_bracket_pair_end = true;
 2579                            break;
 2580                        }
 2581                    }
 2582                }
 2583
 2584                if let Some(bracket_pair) = bracket_pair {
 2585                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2586                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2587                    let auto_surround =
 2588                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2589                    if selection.is_empty() {
 2590                        if is_bracket_pair_start {
 2591                            // If the inserted text is a suffix of an opening bracket and the
 2592                            // selection is preceded by the rest of the opening bracket, then
 2593                            // insert the closing bracket.
 2594                            let following_text_allows_autoclose = snapshot
 2595                                .chars_at(selection.start)
 2596                                .next()
 2597                                .map_or(true, |c| scope.should_autoclose_before(c));
 2598
 2599                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2600                                && bracket_pair.start.len() == 1
 2601                            {
 2602                                let target = bracket_pair.start.chars().next().unwrap();
 2603                                let current_line_count = snapshot
 2604                                    .reversed_chars_at(selection.start)
 2605                                    .take_while(|&c| c != '\n')
 2606                                    .filter(|&c| c == target)
 2607                                    .count();
 2608                                current_line_count % 2 == 1
 2609                            } else {
 2610                                false
 2611                            };
 2612
 2613                            if autoclose
 2614                                && bracket_pair.close
 2615                                && following_text_allows_autoclose
 2616                                && !is_closing_quote
 2617                            {
 2618                                let anchor = snapshot.anchor_before(selection.end);
 2619                                new_selections.push((selection.map(|_| anchor), text.len()));
 2620                                new_autoclose_regions.push((
 2621                                    anchor,
 2622                                    text.len(),
 2623                                    selection.id,
 2624                                    bracket_pair.clone(),
 2625                                ));
 2626                                edits.push((
 2627                                    selection.range(),
 2628                                    format!("{}{}", text, bracket_pair.end).into(),
 2629                                ));
 2630                                bracket_inserted = true;
 2631                                continue;
 2632                            }
 2633                        }
 2634
 2635                        if let Some(region) = autoclose_region {
 2636                            // If the selection is followed by an auto-inserted closing bracket,
 2637                            // then don't insert that closing bracket again; just move the selection
 2638                            // past the closing bracket.
 2639                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2640                                && text.as_ref() == region.pair.end.as_str();
 2641                            if should_skip {
 2642                                let anchor = snapshot.anchor_after(selection.end);
 2643                                new_selections
 2644                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2645                                continue;
 2646                            }
 2647                        }
 2648
 2649                        let always_treat_brackets_as_autoclosed = snapshot
 2650                            .settings_at(selection.start, cx)
 2651                            .always_treat_brackets_as_autoclosed;
 2652                        if always_treat_brackets_as_autoclosed
 2653                            && is_bracket_pair_end
 2654                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2655                        {
 2656                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2657                            // and the inserted text is a closing bracket and the selection is followed
 2658                            // by the closing bracket then move the selection past the closing bracket.
 2659                            let anchor = snapshot.anchor_after(selection.end);
 2660                            new_selections.push((selection.map(|_| anchor), text.len()));
 2661                            continue;
 2662                        }
 2663                    }
 2664                    // If an opening bracket is 1 character long and is typed while
 2665                    // text is selected, then surround that text with the bracket pair.
 2666                    else if auto_surround
 2667                        && bracket_pair.surround
 2668                        && is_bracket_pair_start
 2669                        && bracket_pair.start.chars().count() == 1
 2670                    {
 2671                        edits.push((selection.start..selection.start, text.clone()));
 2672                        edits.push((
 2673                            selection.end..selection.end,
 2674                            bracket_pair.end.as_str().into(),
 2675                        ));
 2676                        bracket_inserted = true;
 2677                        new_selections.push((
 2678                            Selection {
 2679                                id: selection.id,
 2680                                start: snapshot.anchor_after(selection.start),
 2681                                end: snapshot.anchor_before(selection.end),
 2682                                reversed: selection.reversed,
 2683                                goal: selection.goal,
 2684                            },
 2685                            0,
 2686                        ));
 2687                        continue;
 2688                    }
 2689                }
 2690            }
 2691
 2692            if self.auto_replace_emoji_shortcode
 2693                && selection.is_empty()
 2694                && text.as_ref().ends_with(':')
 2695            {
 2696                if let Some(possible_emoji_short_code) =
 2697                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2698                {
 2699                    if !possible_emoji_short_code.is_empty() {
 2700                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2701                            let emoji_shortcode_start = Point::new(
 2702                                selection.start.row,
 2703                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2704                            );
 2705
 2706                            // Remove shortcode from buffer
 2707                            edits.push((
 2708                                emoji_shortcode_start..selection.start,
 2709                                "".to_string().into(),
 2710                            ));
 2711                            new_selections.push((
 2712                                Selection {
 2713                                    id: selection.id,
 2714                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2715                                    end: snapshot.anchor_before(selection.start),
 2716                                    reversed: selection.reversed,
 2717                                    goal: selection.goal,
 2718                                },
 2719                                0,
 2720                            ));
 2721
 2722                            // Insert emoji
 2723                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2724                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2725                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2726
 2727                            continue;
 2728                        }
 2729                    }
 2730                }
 2731            }
 2732
 2733            // If not handling any auto-close operation, then just replace the selected
 2734            // text with the given input and move the selection to the end of the
 2735            // newly inserted text.
 2736            let anchor = snapshot.anchor_after(selection.end);
 2737            if !self.linked_edit_ranges.is_empty() {
 2738                let start_anchor = snapshot.anchor_before(selection.start);
 2739
 2740                let is_word_char = text.chars().next().map_or(true, |char| {
 2741                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2742                    classifier.is_word(char)
 2743                });
 2744
 2745                if is_word_char {
 2746                    if let Some(ranges) = self
 2747                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2748                    {
 2749                        for (buffer, edits) in ranges {
 2750                            linked_edits
 2751                                .entry(buffer.clone())
 2752                                .or_default()
 2753                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2754                        }
 2755                    }
 2756                }
 2757            }
 2758
 2759            new_selections.push((selection.map(|_| anchor), 0));
 2760            edits.push((selection.start..selection.end, text.clone()));
 2761        }
 2762
 2763        drop(snapshot);
 2764
 2765        self.transact(cx, |this, cx| {
 2766            this.buffer.update(cx, |buffer, cx| {
 2767                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2768            });
 2769            for (buffer, edits) in linked_edits {
 2770                buffer.update(cx, |buffer, cx| {
 2771                    let snapshot = buffer.snapshot();
 2772                    let edits = edits
 2773                        .into_iter()
 2774                        .map(|(range, text)| {
 2775                            use text::ToPoint as TP;
 2776                            let end_point = TP::to_point(&range.end, &snapshot);
 2777                            let start_point = TP::to_point(&range.start, &snapshot);
 2778                            (start_point..end_point, text)
 2779                        })
 2780                        .sorted_by_key(|(range, _)| range.start)
 2781                        .collect::<Vec<_>>();
 2782                    buffer.edit(edits, None, cx);
 2783                })
 2784            }
 2785            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2786            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2787            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2788            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2789                .zip(new_selection_deltas)
 2790                .map(|(selection, delta)| Selection {
 2791                    id: selection.id,
 2792                    start: selection.start + delta,
 2793                    end: selection.end + delta,
 2794                    reversed: selection.reversed,
 2795                    goal: SelectionGoal::None,
 2796                })
 2797                .collect::<Vec<_>>();
 2798
 2799            let mut i = 0;
 2800            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2801                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2802                let start = map.buffer_snapshot.anchor_before(position);
 2803                let end = map.buffer_snapshot.anchor_after(position);
 2804                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2805                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2806                        Ordering::Less => i += 1,
 2807                        Ordering::Greater => break,
 2808                        Ordering::Equal => {
 2809                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2810                                Ordering::Less => i += 1,
 2811                                Ordering::Equal => break,
 2812                                Ordering::Greater => break,
 2813                            }
 2814                        }
 2815                    }
 2816                }
 2817                this.autoclose_regions.insert(
 2818                    i,
 2819                    AutocloseRegion {
 2820                        selection_id,
 2821                        range: start..end,
 2822                        pair,
 2823                    },
 2824                );
 2825            }
 2826
 2827            let had_active_inline_completion = this.has_active_inline_completion();
 2828            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2829                s.select(new_selections)
 2830            });
 2831
 2832            if !bracket_inserted {
 2833                if let Some(on_type_format_task) =
 2834                    this.trigger_on_type_formatting(text.to_string(), cx)
 2835                {
 2836                    on_type_format_task.detach_and_log_err(cx);
 2837                }
 2838            }
 2839
 2840            let editor_settings = EditorSettings::get_global(cx);
 2841            if bracket_inserted
 2842                && (editor_settings.auto_signature_help
 2843                    || editor_settings.show_signature_help_after_edits)
 2844            {
 2845                this.show_signature_help(&ShowSignatureHelp, cx);
 2846            }
 2847
 2848            let trigger_in_words = !had_active_inline_completion;
 2849            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2850            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2851            this.refresh_inline_completion(true, false, cx);
 2852        });
 2853    }
 2854
 2855    fn find_possible_emoji_shortcode_at_position(
 2856        snapshot: &MultiBufferSnapshot,
 2857        position: Point,
 2858    ) -> Option<String> {
 2859        let mut chars = Vec::new();
 2860        let mut found_colon = false;
 2861        for char in snapshot.reversed_chars_at(position).take(100) {
 2862            // Found a possible emoji shortcode in the middle of the buffer
 2863            if found_colon {
 2864                if char.is_whitespace() {
 2865                    chars.reverse();
 2866                    return Some(chars.iter().collect());
 2867                }
 2868                // If the previous character is not a whitespace, we are in the middle of a word
 2869                // and we only want to complete the shortcode if the word is made up of other emojis
 2870                let mut containing_word = String::new();
 2871                for ch in snapshot
 2872                    .reversed_chars_at(position)
 2873                    .skip(chars.len() + 1)
 2874                    .take(100)
 2875                {
 2876                    if ch.is_whitespace() {
 2877                        break;
 2878                    }
 2879                    containing_word.push(ch);
 2880                }
 2881                let containing_word = containing_word.chars().rev().collect::<String>();
 2882                if util::word_consists_of_emojis(containing_word.as_str()) {
 2883                    chars.reverse();
 2884                    return Some(chars.iter().collect());
 2885                }
 2886            }
 2887
 2888            if char.is_whitespace() || !char.is_ascii() {
 2889                return None;
 2890            }
 2891            if char == ':' {
 2892                found_colon = true;
 2893            } else {
 2894                chars.push(char);
 2895            }
 2896        }
 2897        // Found a possible emoji shortcode at the beginning of the buffer
 2898        chars.reverse();
 2899        Some(chars.iter().collect())
 2900    }
 2901
 2902    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2903        self.transact(cx, |this, cx| {
 2904            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2905                let selections = this.selections.all::<usize>(cx);
 2906                let multi_buffer = this.buffer.read(cx);
 2907                let buffer = multi_buffer.snapshot(cx);
 2908                selections
 2909                    .iter()
 2910                    .map(|selection| {
 2911                        let start_point = selection.start.to_point(&buffer);
 2912                        let mut indent =
 2913                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2914                        indent.len = cmp::min(indent.len, start_point.column);
 2915                        let start = selection.start;
 2916                        let end = selection.end;
 2917                        let selection_is_empty = start == end;
 2918                        let language_scope = buffer.language_scope_at(start);
 2919                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2920                            &language_scope
 2921                        {
 2922                            let leading_whitespace_len = buffer
 2923                                .reversed_chars_at(start)
 2924                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2925                                .map(|c| c.len_utf8())
 2926                                .sum::<usize>();
 2927
 2928                            let trailing_whitespace_len = buffer
 2929                                .chars_at(end)
 2930                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2931                                .map(|c| c.len_utf8())
 2932                                .sum::<usize>();
 2933
 2934                            let insert_extra_newline =
 2935                                language.brackets().any(|(pair, enabled)| {
 2936                                    let pair_start = pair.start.trim_end();
 2937                                    let pair_end = pair.end.trim_start();
 2938
 2939                                    enabled
 2940                                        && pair.newline
 2941                                        && buffer.contains_str_at(
 2942                                            end + trailing_whitespace_len,
 2943                                            pair_end,
 2944                                        )
 2945                                        && buffer.contains_str_at(
 2946                                            (start - leading_whitespace_len)
 2947                                                .saturating_sub(pair_start.len()),
 2948                                            pair_start,
 2949                                        )
 2950                                });
 2951
 2952                            // Comment extension on newline is allowed only for cursor selections
 2953                            let comment_delimiter = maybe!({
 2954                                if !selection_is_empty {
 2955                                    return None;
 2956                                }
 2957
 2958                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2959                                    return None;
 2960                                }
 2961
 2962                                let delimiters = language.line_comment_prefixes();
 2963                                let max_len_of_delimiter =
 2964                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2965                                let (snapshot, range) =
 2966                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2967
 2968                                let mut index_of_first_non_whitespace = 0;
 2969                                let comment_candidate = snapshot
 2970                                    .chars_for_range(range)
 2971                                    .skip_while(|c| {
 2972                                        let should_skip = c.is_whitespace();
 2973                                        if should_skip {
 2974                                            index_of_first_non_whitespace += 1;
 2975                                        }
 2976                                        should_skip
 2977                                    })
 2978                                    .take(max_len_of_delimiter)
 2979                                    .collect::<String>();
 2980                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2981                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2982                                })?;
 2983                                let cursor_is_placed_after_comment_marker =
 2984                                    index_of_first_non_whitespace + comment_prefix.len()
 2985                                        <= start_point.column as usize;
 2986                                if cursor_is_placed_after_comment_marker {
 2987                                    Some(comment_prefix.clone())
 2988                                } else {
 2989                                    None
 2990                                }
 2991                            });
 2992                            (comment_delimiter, insert_extra_newline)
 2993                        } else {
 2994                            (None, false)
 2995                        };
 2996
 2997                        let capacity_for_delimiter = comment_delimiter
 2998                            .as_deref()
 2999                            .map(str::len)
 3000                            .unwrap_or_default();
 3001                        let mut new_text =
 3002                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3003                        new_text.push('\n');
 3004                        new_text.extend(indent.chars());
 3005                        if let Some(delimiter) = &comment_delimiter {
 3006                            new_text.push_str(delimiter);
 3007                        }
 3008                        if insert_extra_newline {
 3009                            new_text = new_text.repeat(2);
 3010                        }
 3011
 3012                        let anchor = buffer.anchor_after(end);
 3013                        let new_selection = selection.map(|_| anchor);
 3014                        (
 3015                            (start..end, new_text),
 3016                            (insert_extra_newline, new_selection),
 3017                        )
 3018                    })
 3019                    .unzip()
 3020            };
 3021
 3022            this.edit_with_autoindent(edits, cx);
 3023            let buffer = this.buffer.read(cx).snapshot(cx);
 3024            let new_selections = selection_fixup_info
 3025                .into_iter()
 3026                .map(|(extra_newline_inserted, new_selection)| {
 3027                    let mut cursor = new_selection.end.to_point(&buffer);
 3028                    if extra_newline_inserted {
 3029                        cursor.row -= 1;
 3030                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3031                    }
 3032                    new_selection.map(|_| cursor)
 3033                })
 3034                .collect();
 3035
 3036            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3037            this.refresh_inline_completion(true, false, cx);
 3038        });
 3039    }
 3040
 3041    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3042        let buffer = self.buffer.read(cx);
 3043        let snapshot = buffer.snapshot(cx);
 3044
 3045        let mut edits = Vec::new();
 3046        let mut rows = Vec::new();
 3047
 3048        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3049            let cursor = selection.head();
 3050            let row = cursor.row;
 3051
 3052            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3053
 3054            let newline = "\n".to_string();
 3055            edits.push((start_of_line..start_of_line, newline));
 3056
 3057            rows.push(row + rows_inserted as u32);
 3058        }
 3059
 3060        self.transact(cx, |editor, cx| {
 3061            editor.edit(edits, cx);
 3062
 3063            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3064                let mut index = 0;
 3065                s.move_cursors_with(|map, _, _| {
 3066                    let row = rows[index];
 3067                    index += 1;
 3068
 3069                    let point = Point::new(row, 0);
 3070                    let boundary = map.next_line_boundary(point).1;
 3071                    let clipped = map.clip_point(boundary, Bias::Left);
 3072
 3073                    (clipped, SelectionGoal::None)
 3074                });
 3075            });
 3076
 3077            let mut indent_edits = Vec::new();
 3078            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3079            for row in rows {
 3080                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3081                for (row, indent) in indents {
 3082                    if indent.len == 0 {
 3083                        continue;
 3084                    }
 3085
 3086                    let text = match indent.kind {
 3087                        IndentKind::Space => " ".repeat(indent.len as usize),
 3088                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3089                    };
 3090                    let point = Point::new(row.0, 0);
 3091                    indent_edits.push((point..point, text));
 3092                }
 3093            }
 3094            editor.edit(indent_edits, cx);
 3095        });
 3096    }
 3097
 3098    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3099        let buffer = self.buffer.read(cx);
 3100        let snapshot = buffer.snapshot(cx);
 3101
 3102        let mut edits = Vec::new();
 3103        let mut rows = Vec::new();
 3104        let mut rows_inserted = 0;
 3105
 3106        for selection in self.selections.all_adjusted(cx) {
 3107            let cursor = selection.head();
 3108            let row = cursor.row;
 3109
 3110            let point = Point::new(row + 1, 0);
 3111            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3112
 3113            let newline = "\n".to_string();
 3114            edits.push((start_of_line..start_of_line, newline));
 3115
 3116            rows_inserted += 1;
 3117            rows.push(row + rows_inserted);
 3118        }
 3119
 3120        self.transact(cx, |editor, cx| {
 3121            editor.edit(edits, cx);
 3122
 3123            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3124                let mut index = 0;
 3125                s.move_cursors_with(|map, _, _| {
 3126                    let row = rows[index];
 3127                    index += 1;
 3128
 3129                    let point = Point::new(row, 0);
 3130                    let boundary = map.next_line_boundary(point).1;
 3131                    let clipped = map.clip_point(boundary, Bias::Left);
 3132
 3133                    (clipped, SelectionGoal::None)
 3134                });
 3135            });
 3136
 3137            let mut indent_edits = Vec::new();
 3138            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3139            for row in rows {
 3140                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3141                for (row, indent) in indents {
 3142                    if indent.len == 0 {
 3143                        continue;
 3144                    }
 3145
 3146                    let text = match indent.kind {
 3147                        IndentKind::Space => " ".repeat(indent.len as usize),
 3148                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3149                    };
 3150                    let point = Point::new(row.0, 0);
 3151                    indent_edits.push((point..point, text));
 3152                }
 3153            }
 3154            editor.edit(indent_edits, cx);
 3155        });
 3156    }
 3157
 3158    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3159        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3160            original_indent_columns: Vec::new(),
 3161        });
 3162        self.insert_with_autoindent_mode(text, autoindent, cx);
 3163    }
 3164
 3165    fn insert_with_autoindent_mode(
 3166        &mut self,
 3167        text: &str,
 3168        autoindent_mode: Option<AutoindentMode>,
 3169        cx: &mut ViewContext<Self>,
 3170    ) {
 3171        if self.read_only(cx) {
 3172            return;
 3173        }
 3174
 3175        let text: Arc<str> = text.into();
 3176        self.transact(cx, |this, cx| {
 3177            let old_selections = this.selections.all_adjusted(cx);
 3178            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3179                let anchors = {
 3180                    let snapshot = buffer.read(cx);
 3181                    old_selections
 3182                        .iter()
 3183                        .map(|s| {
 3184                            let anchor = snapshot.anchor_after(s.head());
 3185                            s.map(|_| anchor)
 3186                        })
 3187                        .collect::<Vec<_>>()
 3188                };
 3189                buffer.edit(
 3190                    old_selections
 3191                        .iter()
 3192                        .map(|s| (s.start..s.end, text.clone())),
 3193                    autoindent_mode,
 3194                    cx,
 3195                );
 3196                anchors
 3197            });
 3198
 3199            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3200                s.select_anchors(selection_anchors);
 3201            })
 3202        });
 3203    }
 3204
 3205    fn trigger_completion_on_input(
 3206        &mut self,
 3207        text: &str,
 3208        trigger_in_words: bool,
 3209        cx: &mut ViewContext<Self>,
 3210    ) {
 3211        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3212            self.show_completions(
 3213                &ShowCompletions {
 3214                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3215                },
 3216                cx,
 3217            );
 3218        } else {
 3219            self.hide_context_menu(cx);
 3220        }
 3221    }
 3222
 3223    fn is_completion_trigger(
 3224        &self,
 3225        text: &str,
 3226        trigger_in_words: bool,
 3227        cx: &mut ViewContext<Self>,
 3228    ) -> bool {
 3229        let position = self.selections.newest_anchor().head();
 3230        let multibuffer = self.buffer.read(cx);
 3231        let Some(buffer) = position
 3232            .buffer_id
 3233            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3234        else {
 3235            return false;
 3236        };
 3237
 3238        if let Some(completion_provider) = &self.completion_provider {
 3239            completion_provider.is_completion_trigger(
 3240                &buffer,
 3241                position.text_anchor,
 3242                text,
 3243                trigger_in_words,
 3244                cx,
 3245            )
 3246        } else {
 3247            false
 3248        }
 3249    }
 3250
 3251    /// If any empty selections is touching the start of its innermost containing autoclose
 3252    /// region, expand it to select the brackets.
 3253    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3254        let selections = self.selections.all::<usize>(cx);
 3255        let buffer = self.buffer.read(cx).read(cx);
 3256        let new_selections = self
 3257            .selections_with_autoclose_regions(selections, &buffer)
 3258            .map(|(mut selection, region)| {
 3259                if !selection.is_empty() {
 3260                    return selection;
 3261                }
 3262
 3263                if let Some(region) = region {
 3264                    let mut range = region.range.to_offset(&buffer);
 3265                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3266                        range.start -= region.pair.start.len();
 3267                        if buffer.contains_str_at(range.start, &region.pair.start)
 3268                            && buffer.contains_str_at(range.end, &region.pair.end)
 3269                        {
 3270                            range.end += region.pair.end.len();
 3271                            selection.start = range.start;
 3272                            selection.end = range.end;
 3273
 3274                            return selection;
 3275                        }
 3276                    }
 3277                }
 3278
 3279                let always_treat_brackets_as_autoclosed = buffer
 3280                    .settings_at(selection.start, cx)
 3281                    .always_treat_brackets_as_autoclosed;
 3282
 3283                if !always_treat_brackets_as_autoclosed {
 3284                    return selection;
 3285                }
 3286
 3287                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3288                    for (pair, enabled) in scope.brackets() {
 3289                        if !enabled || !pair.close {
 3290                            continue;
 3291                        }
 3292
 3293                        if buffer.contains_str_at(selection.start, &pair.end) {
 3294                            let pair_start_len = pair.start.len();
 3295                            if buffer.contains_str_at(
 3296                                selection.start.saturating_sub(pair_start_len),
 3297                                &pair.start,
 3298                            ) {
 3299                                selection.start -= pair_start_len;
 3300                                selection.end += pair.end.len();
 3301
 3302                                return selection;
 3303                            }
 3304                        }
 3305                    }
 3306                }
 3307
 3308                selection
 3309            })
 3310            .collect();
 3311
 3312        drop(buffer);
 3313        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3314    }
 3315
 3316    /// Iterate the given selections, and for each one, find the smallest surrounding
 3317    /// autoclose region. This uses the ordering of the selections and the autoclose
 3318    /// regions to avoid repeated comparisons.
 3319    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3320        &'a self,
 3321        selections: impl IntoIterator<Item = Selection<D>>,
 3322        buffer: &'a MultiBufferSnapshot,
 3323    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3324        let mut i = 0;
 3325        let mut regions = self.autoclose_regions.as_slice();
 3326        selections.into_iter().map(move |selection| {
 3327            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3328
 3329            let mut enclosing = None;
 3330            while let Some(pair_state) = regions.get(i) {
 3331                if pair_state.range.end.to_offset(buffer) < range.start {
 3332                    regions = &regions[i + 1..];
 3333                    i = 0;
 3334                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3335                    break;
 3336                } else {
 3337                    if pair_state.selection_id == selection.id {
 3338                        enclosing = Some(pair_state);
 3339                    }
 3340                    i += 1;
 3341                }
 3342            }
 3343
 3344            (selection, enclosing)
 3345        })
 3346    }
 3347
 3348    /// Remove any autoclose regions that no longer contain their selection.
 3349    fn invalidate_autoclose_regions(
 3350        &mut self,
 3351        mut selections: &[Selection<Anchor>],
 3352        buffer: &MultiBufferSnapshot,
 3353    ) {
 3354        self.autoclose_regions.retain(|state| {
 3355            let mut i = 0;
 3356            while let Some(selection) = selections.get(i) {
 3357                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3358                    selections = &selections[1..];
 3359                    continue;
 3360                }
 3361                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3362                    break;
 3363                }
 3364                if selection.id == state.selection_id {
 3365                    return true;
 3366                } else {
 3367                    i += 1;
 3368                }
 3369            }
 3370            false
 3371        });
 3372    }
 3373
 3374    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3375        let offset = position.to_offset(buffer);
 3376        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3377        if offset > word_range.start && kind == Some(CharKind::Word) {
 3378            Some(
 3379                buffer
 3380                    .text_for_range(word_range.start..offset)
 3381                    .collect::<String>(),
 3382            )
 3383        } else {
 3384            None
 3385        }
 3386    }
 3387
 3388    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3389        self.refresh_inlay_hints(
 3390            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3391            cx,
 3392        );
 3393    }
 3394
 3395    pub fn inlay_hints_enabled(&self) -> bool {
 3396        self.inlay_hint_cache.enabled
 3397    }
 3398
 3399    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3400        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3401            return;
 3402        }
 3403
 3404        let reason_description = reason.description();
 3405        let ignore_debounce = matches!(
 3406            reason,
 3407            InlayHintRefreshReason::SettingsChange(_)
 3408                | InlayHintRefreshReason::Toggle(_)
 3409                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3410        );
 3411        let (invalidate_cache, required_languages) = match reason {
 3412            InlayHintRefreshReason::Toggle(enabled) => {
 3413                self.inlay_hint_cache.enabled = enabled;
 3414                if enabled {
 3415                    (InvalidationStrategy::RefreshRequested, None)
 3416                } else {
 3417                    self.inlay_hint_cache.clear();
 3418                    self.splice_inlays(
 3419                        self.visible_inlay_hints(cx)
 3420                            .iter()
 3421                            .map(|inlay| inlay.id)
 3422                            .collect(),
 3423                        Vec::new(),
 3424                        cx,
 3425                    );
 3426                    return;
 3427                }
 3428            }
 3429            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3430                match self.inlay_hint_cache.update_settings(
 3431                    &self.buffer,
 3432                    new_settings,
 3433                    self.visible_inlay_hints(cx),
 3434                    cx,
 3435                ) {
 3436                    ControlFlow::Break(Some(InlaySplice {
 3437                        to_remove,
 3438                        to_insert,
 3439                    })) => {
 3440                        self.splice_inlays(to_remove, to_insert, cx);
 3441                        return;
 3442                    }
 3443                    ControlFlow::Break(None) => return,
 3444                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3445                }
 3446            }
 3447            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3448                if let Some(InlaySplice {
 3449                    to_remove,
 3450                    to_insert,
 3451                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3452                {
 3453                    self.splice_inlays(to_remove, to_insert, cx);
 3454                }
 3455                return;
 3456            }
 3457            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3458            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3459                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3460            }
 3461            InlayHintRefreshReason::RefreshRequested => {
 3462                (InvalidationStrategy::RefreshRequested, None)
 3463            }
 3464        };
 3465
 3466        if let Some(InlaySplice {
 3467            to_remove,
 3468            to_insert,
 3469        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3470            reason_description,
 3471            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3472            invalidate_cache,
 3473            ignore_debounce,
 3474            cx,
 3475        ) {
 3476            self.splice_inlays(to_remove, to_insert, cx);
 3477        }
 3478    }
 3479
 3480    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3481        self.display_map
 3482            .read(cx)
 3483            .current_inlays()
 3484            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3485            .cloned()
 3486            .collect()
 3487    }
 3488
 3489    pub fn excerpts_for_inlay_hints_query(
 3490        &self,
 3491        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3492        cx: &mut ViewContext<Editor>,
 3493    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3494        let Some(project) = self.project.as_ref() else {
 3495            return HashMap::default();
 3496        };
 3497        let project = project.read(cx);
 3498        let multi_buffer = self.buffer().read(cx);
 3499        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3500        let multi_buffer_visible_start = self
 3501            .scroll_manager
 3502            .anchor()
 3503            .anchor
 3504            .to_point(&multi_buffer_snapshot);
 3505        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3506            multi_buffer_visible_start
 3507                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3508            Bias::Left,
 3509        );
 3510        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3511        multi_buffer
 3512            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3513            .into_iter()
 3514            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3515            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3516                let buffer = buffer_handle.read(cx);
 3517                let buffer_file = project::File::from_dyn(buffer.file())?;
 3518                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3519                let worktree_entry = buffer_worktree
 3520                    .read(cx)
 3521                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3522                if worktree_entry.is_ignored {
 3523                    return None;
 3524                }
 3525
 3526                let language = buffer.language()?;
 3527                if let Some(restrict_to_languages) = restrict_to_languages {
 3528                    if !restrict_to_languages.contains(language) {
 3529                        return None;
 3530                    }
 3531                }
 3532                Some((
 3533                    excerpt_id,
 3534                    (
 3535                        buffer_handle,
 3536                        buffer.version().clone(),
 3537                        excerpt_visible_range,
 3538                    ),
 3539                ))
 3540            })
 3541            .collect()
 3542    }
 3543
 3544    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3545        TextLayoutDetails {
 3546            text_system: cx.text_system().clone(),
 3547            editor_style: self.style.clone().unwrap(),
 3548            rem_size: cx.rem_size(),
 3549            scroll_anchor: self.scroll_manager.anchor(),
 3550            visible_rows: self.visible_line_count(),
 3551            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3552        }
 3553    }
 3554
 3555    fn splice_inlays(
 3556        &self,
 3557        to_remove: Vec<InlayId>,
 3558        to_insert: Vec<Inlay>,
 3559        cx: &mut ViewContext<Self>,
 3560    ) {
 3561        self.display_map.update(cx, |display_map, cx| {
 3562            display_map.splice_inlays(to_remove, to_insert, cx)
 3563        });
 3564        cx.notify();
 3565    }
 3566
 3567    fn trigger_on_type_formatting(
 3568        &self,
 3569        input: String,
 3570        cx: &mut ViewContext<Self>,
 3571    ) -> Option<Task<Result<()>>> {
 3572        if input.len() != 1 {
 3573            return None;
 3574        }
 3575
 3576        let project = self.project.as_ref()?;
 3577        let position = self.selections.newest_anchor().head();
 3578        let (buffer, buffer_position) = self
 3579            .buffer
 3580            .read(cx)
 3581            .text_anchor_for_position(position, cx)?;
 3582
 3583        let settings = language_settings::language_settings(
 3584            buffer
 3585                .read(cx)
 3586                .language_at(buffer_position)
 3587                .map(|l| l.name()),
 3588            buffer.read(cx).file(),
 3589            cx,
 3590        );
 3591        if !settings.use_on_type_format {
 3592            return None;
 3593        }
 3594
 3595        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3596        // hence we do LSP request & edit on host side only — add formats to host's history.
 3597        let push_to_lsp_host_history = true;
 3598        // If this is not the host, append its history with new edits.
 3599        let push_to_client_history = project.read(cx).is_via_collab();
 3600
 3601        let on_type_formatting = project.update(cx, |project, cx| {
 3602            project.on_type_format(
 3603                buffer.clone(),
 3604                buffer_position,
 3605                input,
 3606                push_to_lsp_host_history,
 3607                cx,
 3608            )
 3609        });
 3610        Some(cx.spawn(|editor, mut cx| async move {
 3611            if let Some(transaction) = on_type_formatting.await? {
 3612                if push_to_client_history {
 3613                    buffer
 3614                        .update(&mut cx, |buffer, _| {
 3615                            buffer.push_transaction(transaction, Instant::now());
 3616                        })
 3617                        .ok();
 3618                }
 3619                editor.update(&mut cx, |editor, cx| {
 3620                    editor.refresh_document_highlights(cx);
 3621                })?;
 3622            }
 3623            Ok(())
 3624        }))
 3625    }
 3626
 3627    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3628        if self.pending_rename.is_some() {
 3629            return;
 3630        }
 3631
 3632        let Some(provider) = self.completion_provider.as_ref() else {
 3633            return;
 3634        };
 3635
 3636        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 3637            return;
 3638        }
 3639
 3640        let position = self.selections.newest_anchor().head();
 3641        let (buffer, buffer_position) =
 3642            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3643                output
 3644            } else {
 3645                return;
 3646            };
 3647        let show_completion_documentation = buffer
 3648            .read(cx)
 3649            .snapshot()
 3650            .settings_at(buffer_position, cx)
 3651            .show_completion_documentation;
 3652
 3653        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3654
 3655        let aside_was_displayed = match self.context_menu.read().deref() {
 3656            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3657            _ => false,
 3658        };
 3659        let trigger_kind = match &options.trigger {
 3660            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3661                CompletionTriggerKind::TRIGGER_CHARACTER
 3662            }
 3663            _ => CompletionTriggerKind::INVOKED,
 3664        };
 3665        let completion_context = CompletionContext {
 3666            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3667                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3668                    Some(String::from(trigger))
 3669                } else {
 3670                    None
 3671                }
 3672            }),
 3673            trigger_kind,
 3674        };
 3675        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3676        let sort_completions = provider.sort_completions();
 3677
 3678        let id = post_inc(&mut self.next_completion_id);
 3679        let task = cx.spawn(|editor, mut cx| {
 3680            async move {
 3681                editor.update(&mut cx, |this, _| {
 3682                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3683                })?;
 3684                let completions = completions.await.log_err();
 3685                let menu = if let Some(completions) = completions {
 3686                    let mut menu = CompletionsMenu::new(
 3687                        id,
 3688                        sort_completions,
 3689                        show_completion_documentation,
 3690                        position,
 3691                        buffer.clone(),
 3692                        completions.into(),
 3693                        aside_was_displayed,
 3694                    );
 3695                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3696                        .await;
 3697
 3698                    if menu.matches.is_empty() {
 3699                        None
 3700                    } else {
 3701                        Some(menu)
 3702                    }
 3703                } else {
 3704                    None
 3705                };
 3706
 3707                editor.update(&mut cx, |editor, cx| {
 3708                    let mut context_menu = editor.context_menu.write();
 3709                    match context_menu.as_ref() {
 3710                        None => {}
 3711
 3712                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3713                            if prev_menu.id > id {
 3714                                return;
 3715                            }
 3716                        }
 3717
 3718                        _ => return,
 3719                    }
 3720
 3721                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3722                        let mut menu = menu.unwrap();
 3723                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3724                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3725                        drop(context_menu);
 3726                        cx.notify();
 3727                    } else if editor.completion_tasks.len() <= 1 {
 3728                        // If there are no more completion tasks and the last menu was
 3729                        // empty, we should hide it. If it was already hidden, we should
 3730                        // also show the copilot completion when available.
 3731                        drop(context_menu);
 3732                        editor.hide_context_menu(cx);
 3733                    }
 3734                })?;
 3735
 3736                Ok::<_, anyhow::Error>(())
 3737            }
 3738            .log_err()
 3739        });
 3740
 3741        self.completion_tasks.push((id, task));
 3742    }
 3743
 3744    pub fn confirm_completion(
 3745        &mut self,
 3746        action: &ConfirmCompletion,
 3747        cx: &mut ViewContext<Self>,
 3748    ) -> Option<Task<Result<()>>> {
 3749        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3750    }
 3751
 3752    pub fn compose_completion(
 3753        &mut self,
 3754        action: &ComposeCompletion,
 3755        cx: &mut ViewContext<Self>,
 3756    ) -> Option<Task<Result<()>>> {
 3757        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3758    }
 3759
 3760    fn do_completion(
 3761        &mut self,
 3762        item_ix: Option<usize>,
 3763        intent: CompletionIntent,
 3764        cx: &mut ViewContext<Editor>,
 3765    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3766        use language::ToOffset as _;
 3767
 3768        self.discard_inline_completion(true, cx);
 3769        let completions_menu =
 3770            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3771                menu
 3772            } else {
 3773                return None;
 3774            };
 3775
 3776        let mat = completions_menu
 3777            .matches
 3778            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3779        let buffer_handle = completions_menu.buffer;
 3780        let completions = completions_menu.completions.read();
 3781        let completion = completions.get(mat.candidate_id)?;
 3782        cx.stop_propagation();
 3783
 3784        let snippet;
 3785        let text;
 3786
 3787        if completion.is_snippet() {
 3788            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3789            text = snippet.as_ref().unwrap().text.clone();
 3790        } else {
 3791            snippet = None;
 3792            text = completion.new_text.clone();
 3793        };
 3794        let selections = self.selections.all::<usize>(cx);
 3795        let buffer = buffer_handle.read(cx);
 3796        let old_range = completion.old_range.to_offset(buffer);
 3797        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3798
 3799        let newest_selection = self.selections.newest_anchor();
 3800        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3801            return None;
 3802        }
 3803
 3804        let lookbehind = newest_selection
 3805            .start
 3806            .text_anchor
 3807            .to_offset(buffer)
 3808            .saturating_sub(old_range.start);
 3809        let lookahead = old_range
 3810            .end
 3811            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3812        let mut common_prefix_len = old_text
 3813            .bytes()
 3814            .zip(text.bytes())
 3815            .take_while(|(a, b)| a == b)
 3816            .count();
 3817
 3818        let snapshot = self.buffer.read(cx).snapshot(cx);
 3819        let mut range_to_replace: Option<Range<isize>> = None;
 3820        let mut ranges = Vec::new();
 3821        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3822        for selection in &selections {
 3823            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3824                let start = selection.start.saturating_sub(lookbehind);
 3825                let end = selection.end + lookahead;
 3826                if selection.id == newest_selection.id {
 3827                    range_to_replace = Some(
 3828                        ((start + common_prefix_len) as isize - selection.start as isize)
 3829                            ..(end as isize - selection.start as isize),
 3830                    );
 3831                }
 3832                ranges.push(start + common_prefix_len..end);
 3833            } else {
 3834                common_prefix_len = 0;
 3835                ranges.clear();
 3836                ranges.extend(selections.iter().map(|s| {
 3837                    if s.id == newest_selection.id {
 3838                        range_to_replace = Some(
 3839                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3840                                - selection.start as isize
 3841                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3842                                    - selection.start as isize,
 3843                        );
 3844                        old_range.clone()
 3845                    } else {
 3846                        s.start..s.end
 3847                    }
 3848                }));
 3849                break;
 3850            }
 3851            if !self.linked_edit_ranges.is_empty() {
 3852                let start_anchor = snapshot.anchor_before(selection.head());
 3853                let end_anchor = snapshot.anchor_after(selection.tail());
 3854                if let Some(ranges) = self
 3855                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3856                {
 3857                    for (buffer, edits) in ranges {
 3858                        linked_edits.entry(buffer.clone()).or_default().extend(
 3859                            edits
 3860                                .into_iter()
 3861                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3862                        );
 3863                    }
 3864                }
 3865            }
 3866        }
 3867        let text = &text[common_prefix_len..];
 3868
 3869        cx.emit(EditorEvent::InputHandled {
 3870            utf16_range_to_replace: range_to_replace,
 3871            text: text.into(),
 3872        });
 3873
 3874        self.transact(cx, |this, cx| {
 3875            if let Some(mut snippet) = snippet {
 3876                snippet.text = text.to_string();
 3877                for tabstop in snippet
 3878                    .tabstops
 3879                    .iter_mut()
 3880                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3881                {
 3882                    tabstop.start -= common_prefix_len as isize;
 3883                    tabstop.end -= common_prefix_len as isize;
 3884                }
 3885
 3886                this.insert_snippet(&ranges, snippet, cx).log_err();
 3887            } else {
 3888                this.buffer.update(cx, |buffer, cx| {
 3889                    buffer.edit(
 3890                        ranges.iter().map(|range| (range.clone(), text)),
 3891                        this.autoindent_mode.clone(),
 3892                        cx,
 3893                    );
 3894                });
 3895            }
 3896            for (buffer, edits) in linked_edits {
 3897                buffer.update(cx, |buffer, cx| {
 3898                    let snapshot = buffer.snapshot();
 3899                    let edits = edits
 3900                        .into_iter()
 3901                        .map(|(range, text)| {
 3902                            use text::ToPoint as TP;
 3903                            let end_point = TP::to_point(&range.end, &snapshot);
 3904                            let start_point = TP::to_point(&range.start, &snapshot);
 3905                            (start_point..end_point, text)
 3906                        })
 3907                        .sorted_by_key(|(range, _)| range.start)
 3908                        .collect::<Vec<_>>();
 3909                    buffer.edit(edits, None, cx);
 3910                })
 3911            }
 3912
 3913            this.refresh_inline_completion(true, false, cx);
 3914        });
 3915
 3916        let show_new_completions_on_confirm = completion
 3917            .confirm
 3918            .as_ref()
 3919            .map_or(false, |confirm| confirm(intent, cx));
 3920        if show_new_completions_on_confirm {
 3921            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3922        }
 3923
 3924        let provider = self.completion_provider.as_ref()?;
 3925        let apply_edits = provider.apply_additional_edits_for_completion(
 3926            buffer_handle,
 3927            completion.clone(),
 3928            true,
 3929            cx,
 3930        );
 3931
 3932        let editor_settings = EditorSettings::get_global(cx);
 3933        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3934            // After the code completion is finished, users often want to know what signatures are needed.
 3935            // so we should automatically call signature_help
 3936            self.show_signature_help(&ShowSignatureHelp, cx);
 3937        }
 3938
 3939        Some(cx.foreground_executor().spawn(async move {
 3940            apply_edits.await?;
 3941            Ok(())
 3942        }))
 3943    }
 3944
 3945    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3946        let mut context_menu = self.context_menu.write();
 3947        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3948            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3949                // Toggle if we're selecting the same one
 3950                *context_menu = None;
 3951                cx.notify();
 3952                return;
 3953            } else {
 3954                // Otherwise, clear it and start a new one
 3955                *context_menu = None;
 3956                cx.notify();
 3957            }
 3958        }
 3959        drop(context_menu);
 3960        let snapshot = self.snapshot(cx);
 3961        let deployed_from_indicator = action.deployed_from_indicator;
 3962        let mut task = self.code_actions_task.take();
 3963        let action = action.clone();
 3964        cx.spawn(|editor, mut cx| async move {
 3965            while let Some(prev_task) = task {
 3966                prev_task.await.log_err();
 3967                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3968            }
 3969
 3970            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3971                if editor.focus_handle.is_focused(cx) {
 3972                    let multibuffer_point = action
 3973                        .deployed_from_indicator
 3974                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3975                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3976                    let (buffer, buffer_row) = snapshot
 3977                        .buffer_snapshot
 3978                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3979                        .and_then(|(buffer_snapshot, range)| {
 3980                            editor
 3981                                .buffer
 3982                                .read(cx)
 3983                                .buffer(buffer_snapshot.remote_id())
 3984                                .map(|buffer| (buffer, range.start.row))
 3985                        })?;
 3986                    let (_, code_actions) = editor
 3987                        .available_code_actions
 3988                        .clone()
 3989                        .and_then(|(location, code_actions)| {
 3990                            let snapshot = location.buffer.read(cx).snapshot();
 3991                            let point_range = location.range.to_point(&snapshot);
 3992                            let point_range = point_range.start.row..=point_range.end.row;
 3993                            if point_range.contains(&buffer_row) {
 3994                                Some((location, code_actions))
 3995                            } else {
 3996                                None
 3997                            }
 3998                        })
 3999                        .unzip();
 4000                    let buffer_id = buffer.read(cx).remote_id();
 4001                    let tasks = editor
 4002                        .tasks
 4003                        .get(&(buffer_id, buffer_row))
 4004                        .map(|t| Arc::new(t.to_owned()));
 4005                    if tasks.is_none() && code_actions.is_none() {
 4006                        return None;
 4007                    }
 4008
 4009                    editor.completion_tasks.clear();
 4010                    editor.discard_inline_completion(false, cx);
 4011                    let task_context =
 4012                        tasks
 4013                            .as_ref()
 4014                            .zip(editor.project.clone())
 4015                            .map(|(tasks, project)| {
 4016                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4017                            });
 4018
 4019                    Some(cx.spawn(|editor, mut cx| async move {
 4020                        let task_context = match task_context {
 4021                            Some(task_context) => task_context.await,
 4022                            None => None,
 4023                        };
 4024                        let resolved_tasks =
 4025                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4026                                Arc::new(ResolvedTasks {
 4027                                    templates: tasks.resolve(&task_context).collect(),
 4028                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4029                                        multibuffer_point.row,
 4030                                        tasks.column,
 4031                                    )),
 4032                                })
 4033                            });
 4034                        let spawn_straight_away = resolved_tasks
 4035                            .as_ref()
 4036                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4037                            && code_actions
 4038                                .as_ref()
 4039                                .map_or(true, |actions| actions.is_empty());
 4040                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4041                            *editor.context_menu.write() =
 4042                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4043                                    buffer,
 4044                                    actions: CodeActionContents {
 4045                                        tasks: resolved_tasks,
 4046                                        actions: code_actions,
 4047                                    },
 4048                                    selected_item: Default::default(),
 4049                                    scroll_handle: UniformListScrollHandle::default(),
 4050                                    deployed_from_indicator,
 4051                                }));
 4052                            if spawn_straight_away {
 4053                                if let Some(task) = editor.confirm_code_action(
 4054                                    &ConfirmCodeAction { item_ix: Some(0) },
 4055                                    cx,
 4056                                ) {
 4057                                    cx.notify();
 4058                                    return task;
 4059                                }
 4060                            }
 4061                            cx.notify();
 4062                            Task::ready(Ok(()))
 4063                        }) {
 4064                            task.await
 4065                        } else {
 4066                            Ok(())
 4067                        }
 4068                    }))
 4069                } else {
 4070                    Some(Task::ready(Ok(())))
 4071                }
 4072            })?;
 4073            if let Some(task) = spawned_test_task {
 4074                task.await?;
 4075            }
 4076
 4077            Ok::<_, anyhow::Error>(())
 4078        })
 4079        .detach_and_log_err(cx);
 4080    }
 4081
 4082    pub fn confirm_code_action(
 4083        &mut self,
 4084        action: &ConfirmCodeAction,
 4085        cx: &mut ViewContext<Self>,
 4086    ) -> Option<Task<Result<()>>> {
 4087        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4088            menu
 4089        } else {
 4090            return None;
 4091        };
 4092        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4093        let action = actions_menu.actions.get(action_ix)?;
 4094        let title = action.label();
 4095        let buffer = actions_menu.buffer;
 4096        let workspace = self.workspace()?;
 4097
 4098        match action {
 4099            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4100                workspace.update(cx, |workspace, cx| {
 4101                    workspace::tasks::schedule_resolved_task(
 4102                        workspace,
 4103                        task_source_kind,
 4104                        resolved_task,
 4105                        false,
 4106                        cx,
 4107                    );
 4108
 4109                    Some(Task::ready(Ok(())))
 4110                })
 4111            }
 4112            CodeActionsItem::CodeAction {
 4113                excerpt_id,
 4114                action,
 4115                provider,
 4116            } => {
 4117                let apply_code_action =
 4118                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4119                let workspace = workspace.downgrade();
 4120                Some(cx.spawn(|editor, cx| async move {
 4121                    let project_transaction = apply_code_action.await?;
 4122                    Self::open_project_transaction(
 4123                        &editor,
 4124                        workspace,
 4125                        project_transaction,
 4126                        title,
 4127                        cx,
 4128                    )
 4129                    .await
 4130                }))
 4131            }
 4132        }
 4133    }
 4134
 4135    pub async fn open_project_transaction(
 4136        this: &WeakView<Editor>,
 4137        workspace: WeakView<Workspace>,
 4138        transaction: ProjectTransaction,
 4139        title: String,
 4140        mut cx: AsyncWindowContext,
 4141    ) -> Result<()> {
 4142        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4143        cx.update(|cx| {
 4144            entries.sort_unstable_by_key(|(buffer, _)| {
 4145                buffer.read(cx).file().map(|f| f.path().clone())
 4146            });
 4147        })?;
 4148
 4149        // If the project transaction's edits are all contained within this editor, then
 4150        // avoid opening a new editor to display them.
 4151
 4152        if let Some((buffer, transaction)) = entries.first() {
 4153            if entries.len() == 1 {
 4154                let excerpt = this.update(&mut cx, |editor, cx| {
 4155                    editor
 4156                        .buffer()
 4157                        .read(cx)
 4158                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4159                })?;
 4160                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4161                    if excerpted_buffer == *buffer {
 4162                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4163                            let excerpt_range = excerpt_range.to_offset(buffer);
 4164                            buffer
 4165                                .edited_ranges_for_transaction::<usize>(transaction)
 4166                                .all(|range| {
 4167                                    excerpt_range.start <= range.start
 4168                                        && excerpt_range.end >= range.end
 4169                                })
 4170                        })?;
 4171
 4172                        if all_edits_within_excerpt {
 4173                            return Ok(());
 4174                        }
 4175                    }
 4176                }
 4177            }
 4178        } else {
 4179            return Ok(());
 4180        }
 4181
 4182        let mut ranges_to_highlight = Vec::new();
 4183        let excerpt_buffer = cx.new_model(|cx| {
 4184            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4185            for (buffer_handle, transaction) in &entries {
 4186                let buffer = buffer_handle.read(cx);
 4187                ranges_to_highlight.extend(
 4188                    multibuffer.push_excerpts_with_context_lines(
 4189                        buffer_handle.clone(),
 4190                        buffer
 4191                            .edited_ranges_for_transaction::<usize>(transaction)
 4192                            .collect(),
 4193                        DEFAULT_MULTIBUFFER_CONTEXT,
 4194                        cx,
 4195                    ),
 4196                );
 4197            }
 4198            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4199            multibuffer
 4200        })?;
 4201
 4202        workspace.update(&mut cx, |workspace, cx| {
 4203            let project = workspace.project().clone();
 4204            let editor =
 4205                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4206            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4207            editor.update(cx, |editor, cx| {
 4208                editor.highlight_background::<Self>(
 4209                    &ranges_to_highlight,
 4210                    |theme| theme.editor_highlighted_line_background,
 4211                    cx,
 4212                );
 4213            });
 4214        })?;
 4215
 4216        Ok(())
 4217    }
 4218
 4219    pub fn clear_code_action_providers(&mut self) {
 4220        self.code_action_providers.clear();
 4221        self.available_code_actions.take();
 4222    }
 4223
 4224    pub fn push_code_action_provider(
 4225        &mut self,
 4226        provider: Arc<dyn CodeActionProvider>,
 4227        cx: &mut ViewContext<Self>,
 4228    ) {
 4229        self.code_action_providers.push(provider);
 4230        self.refresh_code_actions(cx);
 4231    }
 4232
 4233    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4234        let buffer = self.buffer.read(cx);
 4235        let newest_selection = self.selections.newest_anchor().clone();
 4236        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4237        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4238        if start_buffer != end_buffer {
 4239            return None;
 4240        }
 4241
 4242        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4243            cx.background_executor()
 4244                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4245                .await;
 4246
 4247            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4248                let providers = this.code_action_providers.clone();
 4249                let tasks = this
 4250                    .code_action_providers
 4251                    .iter()
 4252                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4253                    .collect::<Vec<_>>();
 4254                (providers, tasks)
 4255            })?;
 4256
 4257            let mut actions = Vec::new();
 4258            for (provider, provider_actions) in
 4259                providers.into_iter().zip(future::join_all(tasks).await)
 4260            {
 4261                if let Some(provider_actions) = provider_actions.log_err() {
 4262                    actions.extend(provider_actions.into_iter().map(|action| {
 4263                        AvailableCodeAction {
 4264                            excerpt_id: newest_selection.start.excerpt_id,
 4265                            action,
 4266                            provider: provider.clone(),
 4267                        }
 4268                    }));
 4269                }
 4270            }
 4271
 4272            this.update(&mut cx, |this, cx| {
 4273                this.available_code_actions = if actions.is_empty() {
 4274                    None
 4275                } else {
 4276                    Some((
 4277                        Location {
 4278                            buffer: start_buffer,
 4279                            range: start..end,
 4280                        },
 4281                        actions.into(),
 4282                    ))
 4283                };
 4284                cx.notify();
 4285            })
 4286        }));
 4287        None
 4288    }
 4289
 4290    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4291        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4292            self.show_git_blame_inline = false;
 4293
 4294            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4295                cx.background_executor().timer(delay).await;
 4296
 4297                this.update(&mut cx, |this, cx| {
 4298                    this.show_git_blame_inline = true;
 4299                    cx.notify();
 4300                })
 4301                .log_err();
 4302            }));
 4303        }
 4304    }
 4305
 4306    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4307        if self.pending_rename.is_some() {
 4308            return None;
 4309        }
 4310
 4311        let provider = self.semantics_provider.clone()?;
 4312        let buffer = self.buffer.read(cx);
 4313        let newest_selection = self.selections.newest_anchor().clone();
 4314        let cursor_position = newest_selection.head();
 4315        let (cursor_buffer, cursor_buffer_position) =
 4316            buffer.text_anchor_for_position(cursor_position, cx)?;
 4317        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4318        if cursor_buffer != tail_buffer {
 4319            return None;
 4320        }
 4321        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4322        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4323            cx.background_executor()
 4324                .timer(Duration::from_millis(debounce))
 4325                .await;
 4326
 4327            let highlights = if let Some(highlights) = cx
 4328                .update(|cx| {
 4329                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4330                })
 4331                .ok()
 4332                .flatten()
 4333            {
 4334                highlights.await.log_err()
 4335            } else {
 4336                None
 4337            };
 4338
 4339            if let Some(highlights) = highlights {
 4340                this.update(&mut cx, |this, cx| {
 4341                    if this.pending_rename.is_some() {
 4342                        return;
 4343                    }
 4344
 4345                    let buffer_id = cursor_position.buffer_id;
 4346                    let buffer = this.buffer.read(cx);
 4347                    if !buffer
 4348                        .text_anchor_for_position(cursor_position, cx)
 4349                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4350                    {
 4351                        return;
 4352                    }
 4353
 4354                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4355                    let mut write_ranges = Vec::new();
 4356                    let mut read_ranges = Vec::new();
 4357                    for highlight in highlights {
 4358                        for (excerpt_id, excerpt_range) in
 4359                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4360                        {
 4361                            let start = highlight
 4362                                .range
 4363                                .start
 4364                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4365                            let end = highlight
 4366                                .range
 4367                                .end
 4368                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4369                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4370                                continue;
 4371                            }
 4372
 4373                            let range = Anchor {
 4374                                buffer_id,
 4375                                excerpt_id,
 4376                                text_anchor: start,
 4377                            }..Anchor {
 4378                                buffer_id,
 4379                                excerpt_id,
 4380                                text_anchor: end,
 4381                            };
 4382                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4383                                write_ranges.push(range);
 4384                            } else {
 4385                                read_ranges.push(range);
 4386                            }
 4387                        }
 4388                    }
 4389
 4390                    this.highlight_background::<DocumentHighlightRead>(
 4391                        &read_ranges,
 4392                        |theme| theme.editor_document_highlight_read_background,
 4393                        cx,
 4394                    );
 4395                    this.highlight_background::<DocumentHighlightWrite>(
 4396                        &write_ranges,
 4397                        |theme| theme.editor_document_highlight_write_background,
 4398                        cx,
 4399                    );
 4400                    cx.notify();
 4401                })
 4402                .log_err();
 4403            }
 4404        }));
 4405        None
 4406    }
 4407
 4408    pub fn refresh_inline_completion(
 4409        &mut self,
 4410        debounce: bool,
 4411        user_requested: bool,
 4412        cx: &mut ViewContext<Self>,
 4413    ) -> Option<()> {
 4414        let provider = self.inline_completion_provider()?;
 4415        let cursor = self.selections.newest_anchor().head();
 4416        let (buffer, cursor_buffer_position) =
 4417            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4418
 4419        if !user_requested
 4420            && (!self.enable_inline_completions
 4421                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4422                || !self.is_focused(cx))
 4423        {
 4424            self.discard_inline_completion(false, cx);
 4425            return None;
 4426        }
 4427
 4428        self.update_visible_inline_completion(cx);
 4429        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4430        Some(())
 4431    }
 4432
 4433    fn cycle_inline_completion(
 4434        &mut self,
 4435        direction: Direction,
 4436        cx: &mut ViewContext<Self>,
 4437    ) -> Option<()> {
 4438        let provider = self.inline_completion_provider()?;
 4439        let cursor = self.selections.newest_anchor().head();
 4440        let (buffer, cursor_buffer_position) =
 4441            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4442        if !self.enable_inline_completions
 4443            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4444        {
 4445            return None;
 4446        }
 4447
 4448        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4449        self.update_visible_inline_completion(cx);
 4450
 4451        Some(())
 4452    }
 4453
 4454    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4455        if !self.has_active_inline_completion() {
 4456            self.refresh_inline_completion(false, true, cx);
 4457            return;
 4458        }
 4459
 4460        self.update_visible_inline_completion(cx);
 4461    }
 4462
 4463    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4464        self.show_cursor_names(cx);
 4465    }
 4466
 4467    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4468        self.show_cursor_names = true;
 4469        cx.notify();
 4470        cx.spawn(|this, mut cx| async move {
 4471            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4472            this.update(&mut cx, |this, cx| {
 4473                this.show_cursor_names = false;
 4474                cx.notify()
 4475            })
 4476            .ok()
 4477        })
 4478        .detach();
 4479    }
 4480
 4481    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4482        if self.has_active_inline_completion() {
 4483            self.cycle_inline_completion(Direction::Next, cx);
 4484        } else {
 4485            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4486            if is_copilot_disabled {
 4487                cx.propagate();
 4488            }
 4489        }
 4490    }
 4491
 4492    pub fn previous_inline_completion(
 4493        &mut self,
 4494        _: &PreviousInlineCompletion,
 4495        cx: &mut ViewContext<Self>,
 4496    ) {
 4497        if self.has_active_inline_completion() {
 4498            self.cycle_inline_completion(Direction::Prev, cx);
 4499        } else {
 4500            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4501            if is_copilot_disabled {
 4502                cx.propagate();
 4503            }
 4504        }
 4505    }
 4506
 4507    pub fn accept_inline_completion(
 4508        &mut self,
 4509        _: &AcceptInlineCompletion,
 4510        cx: &mut ViewContext<Self>,
 4511    ) {
 4512        self.hide_context_menu(cx);
 4513
 4514        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4515            return;
 4516        };
 4517
 4518        self.report_inline_completion_event(true, cx);
 4519
 4520        match &active_inline_completion.completion {
 4521            InlineCompletion::Move(position) => {
 4522                let position = *position;
 4523                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4524                    selections.select_anchor_ranges([position..position]);
 4525                });
 4526            }
 4527            InlineCompletion::Edit(edits) => {
 4528                if let Some(provider) = self.inline_completion_provider() {
 4529                    provider.accept(cx);
 4530                }
 4531
 4532                let snapshot = self.buffer.read(cx).snapshot(cx);
 4533                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4534
 4535                self.buffer.update(cx, |buffer, cx| {
 4536                    buffer.edit(edits.iter().cloned(), None, cx)
 4537                });
 4538
 4539                self.change_selections(None, cx, |s| {
 4540                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4541                });
 4542
 4543                self.update_visible_inline_completion(cx);
 4544                if self.active_inline_completion.is_none() {
 4545                    self.refresh_inline_completion(true, true, cx);
 4546                }
 4547
 4548                cx.notify();
 4549            }
 4550        }
 4551    }
 4552
 4553    pub fn accept_partial_inline_completion(
 4554        &mut self,
 4555        _: &AcceptPartialInlineCompletion,
 4556        cx: &mut ViewContext<Self>,
 4557    ) {
 4558        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4559            return;
 4560        };
 4561        if self.selections.count() != 1 {
 4562            return;
 4563        }
 4564
 4565        self.report_inline_completion_event(true, cx);
 4566
 4567        match &active_inline_completion.completion {
 4568            InlineCompletion::Move(position) => {
 4569                let position = *position;
 4570                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4571                    selections.select_anchor_ranges([position..position]);
 4572                });
 4573            }
 4574            InlineCompletion::Edit(edits) => {
 4575                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4576                    let text = edits[0].1.as_str();
 4577                    let mut partial_completion = text
 4578                        .chars()
 4579                        .by_ref()
 4580                        .take_while(|c| c.is_alphabetic())
 4581                        .collect::<String>();
 4582                    if partial_completion.is_empty() {
 4583                        partial_completion = text
 4584                            .chars()
 4585                            .by_ref()
 4586                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4587                            .collect::<String>();
 4588                    }
 4589
 4590                    cx.emit(EditorEvent::InputHandled {
 4591                        utf16_range_to_replace: None,
 4592                        text: partial_completion.clone().into(),
 4593                    });
 4594
 4595                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4596
 4597                    self.refresh_inline_completion(true, true, cx);
 4598                    cx.notify();
 4599                }
 4600            }
 4601        }
 4602    }
 4603
 4604    fn discard_inline_completion(
 4605        &mut self,
 4606        should_report_inline_completion_event: bool,
 4607        cx: &mut ViewContext<Self>,
 4608    ) -> bool {
 4609        if should_report_inline_completion_event {
 4610            self.report_inline_completion_event(false, cx);
 4611        }
 4612
 4613        if let Some(provider) = self.inline_completion_provider() {
 4614            provider.discard(cx);
 4615        }
 4616
 4617        self.take_active_inline_completion(cx).is_some()
 4618    }
 4619
 4620    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4621        let Some(provider) = self.inline_completion_provider() else {
 4622            return;
 4623        };
 4624        let Some(project) = self.project.as_ref() else {
 4625            return;
 4626        };
 4627        let Some((_, buffer, _)) = self
 4628            .buffer
 4629            .read(cx)
 4630            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4631        else {
 4632            return;
 4633        };
 4634
 4635        let project = project.read(cx);
 4636        let extension = buffer
 4637            .read(cx)
 4638            .file()
 4639            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4640        project.client().telemetry().report_inline_completion_event(
 4641            provider.name().into(),
 4642            accepted,
 4643            extension,
 4644        );
 4645    }
 4646
 4647    pub fn has_active_inline_completion(&self) -> bool {
 4648        self.active_inline_completion.is_some()
 4649    }
 4650
 4651    fn take_active_inline_completion(
 4652        &mut self,
 4653        cx: &mut ViewContext<Self>,
 4654    ) -> Option<InlineCompletion> {
 4655        let active_inline_completion = self.active_inline_completion.take()?;
 4656        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4657        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4658        Some(active_inline_completion.completion)
 4659    }
 4660
 4661    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4662        let selection = self.selections.newest_anchor();
 4663        let cursor = selection.head();
 4664        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4665        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4666        let excerpt_id = cursor.excerpt_id;
 4667
 4668        if !offset_selection.is_empty()
 4669            || self
 4670                .active_inline_completion
 4671                .as_ref()
 4672                .map_or(false, |completion| {
 4673                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4674                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4675                    !invalidation_range.contains(&offset_selection.head())
 4676                })
 4677        {
 4678            self.discard_inline_completion(false, cx);
 4679            return None;
 4680        }
 4681
 4682        self.take_active_inline_completion(cx);
 4683        let provider = self.inline_completion_provider()?;
 4684
 4685        let (buffer, cursor_buffer_position) =
 4686            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4687
 4688        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4689        let edits = completion
 4690            .edits
 4691            .into_iter()
 4692            .map(|(range, new_text)| {
 4693                (
 4694                    multibuffer
 4695                        .anchor_in_excerpt(excerpt_id, range.start)
 4696                        .unwrap()
 4697                        ..multibuffer
 4698                            .anchor_in_excerpt(excerpt_id, range.end)
 4699                            .unwrap(),
 4700                    new_text,
 4701                )
 4702            })
 4703            .collect::<Vec<_>>();
 4704        if edits.is_empty() {
 4705            return None;
 4706        }
 4707
 4708        let first_edit_start = edits.first().unwrap().0.start;
 4709        let edit_start_row = first_edit_start
 4710            .to_point(&multibuffer)
 4711            .row
 4712            .saturating_sub(2);
 4713
 4714        let last_edit_end = edits.last().unwrap().0.end;
 4715        let edit_end_row = cmp::min(
 4716            multibuffer.max_point().row,
 4717            last_edit_end.to_point(&multibuffer).row + 2,
 4718        );
 4719
 4720        let cursor_row = cursor.to_point(&multibuffer).row;
 4721
 4722        let mut inlay_ids = Vec::new();
 4723        let invalidation_row_range;
 4724        let completion;
 4725        if cursor_row < edit_start_row {
 4726            invalidation_row_range = cursor_row..edit_end_row;
 4727            completion = InlineCompletion::Move(first_edit_start);
 4728        } else if cursor_row > edit_end_row {
 4729            invalidation_row_range = edit_start_row..cursor_row;
 4730            completion = InlineCompletion::Move(first_edit_start);
 4731        } else {
 4732            if edits
 4733                .iter()
 4734                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4735            {
 4736                let mut inlays = Vec::new();
 4737                for (range, new_text) in &edits {
 4738                    let inlay = Inlay::suggestion(
 4739                        post_inc(&mut self.next_inlay_id),
 4740                        range.start,
 4741                        new_text.as_str(),
 4742                    );
 4743                    inlay_ids.push(inlay.id);
 4744                    inlays.push(inlay);
 4745                }
 4746
 4747                self.splice_inlays(vec![], inlays, cx);
 4748            } else {
 4749                let background_color = cx.theme().status().deleted_background;
 4750                self.highlight_text::<InlineCompletionHighlight>(
 4751                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4752                    HighlightStyle {
 4753                        background_color: Some(background_color),
 4754                        ..Default::default()
 4755                    },
 4756                    cx,
 4757                );
 4758            }
 4759
 4760            invalidation_row_range = edit_start_row..edit_end_row;
 4761            completion = InlineCompletion::Edit(edits);
 4762        };
 4763
 4764        let invalidation_range = multibuffer
 4765            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4766            ..multibuffer.anchor_after(Point::new(
 4767                invalidation_row_range.end,
 4768                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4769            ));
 4770
 4771        self.active_inline_completion = Some(InlineCompletionState {
 4772            inlay_ids,
 4773            completion,
 4774            invalidation_range,
 4775        });
 4776        cx.notify();
 4777
 4778        Some(())
 4779    }
 4780
 4781    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4782        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4783    }
 4784
 4785    fn render_code_actions_indicator(
 4786        &self,
 4787        _style: &EditorStyle,
 4788        row: DisplayRow,
 4789        is_active: bool,
 4790        cx: &mut ViewContext<Self>,
 4791    ) -> Option<IconButton> {
 4792        if self.available_code_actions.is_some() {
 4793            Some(
 4794                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4795                    .shape(ui::IconButtonShape::Square)
 4796                    .icon_size(IconSize::XSmall)
 4797                    .icon_color(Color::Muted)
 4798                    .selected(is_active)
 4799                    .tooltip({
 4800                        let focus_handle = self.focus_handle.clone();
 4801                        move |cx| {
 4802                            Tooltip::for_action_in(
 4803                                "Toggle Code Actions",
 4804                                &ToggleCodeActions {
 4805                                    deployed_from_indicator: None,
 4806                                },
 4807                                &focus_handle,
 4808                                cx,
 4809                            )
 4810                        }
 4811                    })
 4812                    .on_click(cx.listener(move |editor, _e, cx| {
 4813                        editor.focus(cx);
 4814                        editor.toggle_code_actions(
 4815                            &ToggleCodeActions {
 4816                                deployed_from_indicator: Some(row),
 4817                            },
 4818                            cx,
 4819                        );
 4820                    })),
 4821            )
 4822        } else {
 4823            None
 4824        }
 4825    }
 4826
 4827    fn clear_tasks(&mut self) {
 4828        self.tasks.clear()
 4829    }
 4830
 4831    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4832        if self.tasks.insert(key, value).is_some() {
 4833            // This case should hopefully be rare, but just in case...
 4834            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4835        }
 4836    }
 4837
 4838    fn build_tasks_context(
 4839        project: &Model<Project>,
 4840        buffer: &Model<Buffer>,
 4841        buffer_row: u32,
 4842        tasks: &Arc<RunnableTasks>,
 4843        cx: &mut ViewContext<Self>,
 4844    ) -> Task<Option<task::TaskContext>> {
 4845        let position = Point::new(buffer_row, tasks.column);
 4846        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4847        let location = Location {
 4848            buffer: buffer.clone(),
 4849            range: range_start..range_start,
 4850        };
 4851        // Fill in the environmental variables from the tree-sitter captures
 4852        let mut captured_task_variables = TaskVariables::default();
 4853        for (capture_name, value) in tasks.extra_variables.clone() {
 4854            captured_task_variables.insert(
 4855                task::VariableName::Custom(capture_name.into()),
 4856                value.clone(),
 4857            );
 4858        }
 4859        project.update(cx, |project, cx| {
 4860            project.task_store().update(cx, |task_store, cx| {
 4861                task_store.task_context_for_location(captured_task_variables, location, cx)
 4862            })
 4863        })
 4864    }
 4865
 4866    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4867        let Some((workspace, _)) = self.workspace.clone() else {
 4868            return;
 4869        };
 4870        let Some(project) = self.project.clone() else {
 4871            return;
 4872        };
 4873
 4874        // Try to find a closest, enclosing node using tree-sitter that has a
 4875        // task
 4876        let Some((buffer, buffer_row, tasks)) = self
 4877            .find_enclosing_node_task(cx)
 4878            // Or find the task that's closest in row-distance.
 4879            .or_else(|| self.find_closest_task(cx))
 4880        else {
 4881            return;
 4882        };
 4883
 4884        let reveal_strategy = action.reveal;
 4885        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4886        cx.spawn(|_, mut cx| async move {
 4887            let context = task_context.await?;
 4888            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4889
 4890            let resolved = resolved_task.resolved.as_mut()?;
 4891            resolved.reveal = reveal_strategy;
 4892
 4893            workspace
 4894                .update(&mut cx, |workspace, cx| {
 4895                    workspace::tasks::schedule_resolved_task(
 4896                        workspace,
 4897                        task_source_kind,
 4898                        resolved_task,
 4899                        false,
 4900                        cx,
 4901                    );
 4902                })
 4903                .ok()
 4904        })
 4905        .detach();
 4906    }
 4907
 4908    fn find_closest_task(
 4909        &mut self,
 4910        cx: &mut ViewContext<Self>,
 4911    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4912        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4913
 4914        let ((buffer_id, row), tasks) = self
 4915            .tasks
 4916            .iter()
 4917            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4918
 4919        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4920        let tasks = Arc::new(tasks.to_owned());
 4921        Some((buffer, *row, tasks))
 4922    }
 4923
 4924    fn find_enclosing_node_task(
 4925        &mut self,
 4926        cx: &mut ViewContext<Self>,
 4927    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4928        let snapshot = self.buffer.read(cx).snapshot(cx);
 4929        let offset = self.selections.newest::<usize>(cx).head();
 4930        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4931        let buffer_id = excerpt.buffer().remote_id();
 4932
 4933        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4934        let mut cursor = layer.node().walk();
 4935
 4936        while cursor.goto_first_child_for_byte(offset).is_some() {
 4937            if cursor.node().end_byte() == offset {
 4938                cursor.goto_next_sibling();
 4939            }
 4940        }
 4941
 4942        // Ascend to the smallest ancestor that contains the range and has a task.
 4943        loop {
 4944            let node = cursor.node();
 4945            let node_range = node.byte_range();
 4946            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4947
 4948            // Check if this node contains our offset
 4949            if node_range.start <= offset && node_range.end >= offset {
 4950                // If it contains offset, check for task
 4951                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4952                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4953                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4954                }
 4955            }
 4956
 4957            if !cursor.goto_parent() {
 4958                break;
 4959            }
 4960        }
 4961        None
 4962    }
 4963
 4964    fn render_run_indicator(
 4965        &self,
 4966        _style: &EditorStyle,
 4967        is_active: bool,
 4968        row: DisplayRow,
 4969        cx: &mut ViewContext<Self>,
 4970    ) -> IconButton {
 4971        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4972            .shape(ui::IconButtonShape::Square)
 4973            .icon_size(IconSize::XSmall)
 4974            .icon_color(Color::Muted)
 4975            .selected(is_active)
 4976            .on_click(cx.listener(move |editor, _e, cx| {
 4977                editor.focus(cx);
 4978                editor.toggle_code_actions(
 4979                    &ToggleCodeActions {
 4980                        deployed_from_indicator: Some(row),
 4981                    },
 4982                    cx,
 4983                );
 4984            }))
 4985    }
 4986
 4987    pub fn context_menu_visible(&self) -> bool {
 4988        self.context_menu
 4989            .read()
 4990            .as_ref()
 4991            .map_or(false, |menu| menu.visible())
 4992    }
 4993
 4994    fn render_context_menu(
 4995        &self,
 4996        cursor_position: DisplayPoint,
 4997        style: &EditorStyle,
 4998        max_height: Pixels,
 4999        cx: &mut ViewContext<Editor>,
 5000    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5001        self.context_menu.read().as_ref().map(|menu| {
 5002            menu.render(
 5003                cursor_position,
 5004                style,
 5005                max_height,
 5006                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5007                cx,
 5008            )
 5009        })
 5010    }
 5011
 5012    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5013        cx.notify();
 5014        self.completion_tasks.clear();
 5015        self.context_menu.write().take()
 5016    }
 5017
 5018    fn show_snippet_choices(
 5019        &mut self,
 5020        choices: &Vec<String>,
 5021        selection: Range<Anchor>,
 5022        cx: &mut ViewContext<Self>,
 5023    ) {
 5024        if selection.start.buffer_id.is_none() {
 5025            return;
 5026        }
 5027        let buffer_id = selection.start.buffer_id.unwrap();
 5028        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5029        let id = post_inc(&mut self.next_completion_id);
 5030
 5031        if let Some(buffer) = buffer {
 5032            *self.context_menu.write() = Some(CodeContextMenu::Completions(
 5033                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5034            ));
 5035        }
 5036    }
 5037
 5038    pub fn insert_snippet(
 5039        &mut self,
 5040        insertion_ranges: &[Range<usize>],
 5041        snippet: Snippet,
 5042        cx: &mut ViewContext<Self>,
 5043    ) -> Result<()> {
 5044        struct Tabstop<T> {
 5045            is_end_tabstop: bool,
 5046            ranges: Vec<Range<T>>,
 5047            choices: Option<Vec<String>>,
 5048        }
 5049
 5050        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5051            let snippet_text: Arc<str> = snippet.text.clone().into();
 5052            buffer.edit(
 5053                insertion_ranges
 5054                    .iter()
 5055                    .cloned()
 5056                    .map(|range| (range, snippet_text.clone())),
 5057                Some(AutoindentMode::EachLine),
 5058                cx,
 5059            );
 5060
 5061            let snapshot = &*buffer.read(cx);
 5062            let snippet = &snippet;
 5063            snippet
 5064                .tabstops
 5065                .iter()
 5066                .map(|tabstop| {
 5067                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5068                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5069                    });
 5070                    let mut tabstop_ranges = tabstop
 5071                        .ranges
 5072                        .iter()
 5073                        .flat_map(|tabstop_range| {
 5074                            let mut delta = 0_isize;
 5075                            insertion_ranges.iter().map(move |insertion_range| {
 5076                                let insertion_start = insertion_range.start as isize + delta;
 5077                                delta +=
 5078                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5079
 5080                                let start = ((insertion_start + tabstop_range.start) as usize)
 5081                                    .min(snapshot.len());
 5082                                let end = ((insertion_start + tabstop_range.end) as usize)
 5083                                    .min(snapshot.len());
 5084                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5085                            })
 5086                        })
 5087                        .collect::<Vec<_>>();
 5088                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5089
 5090                    Tabstop {
 5091                        is_end_tabstop,
 5092                        ranges: tabstop_ranges,
 5093                        choices: tabstop.choices.clone(),
 5094                    }
 5095                })
 5096                .collect::<Vec<_>>()
 5097        });
 5098        if let Some(tabstop) = tabstops.first() {
 5099            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5100                s.select_ranges(tabstop.ranges.iter().cloned());
 5101            });
 5102
 5103            if let Some(choices) = &tabstop.choices {
 5104                if let Some(selection) = tabstop.ranges.first() {
 5105                    self.show_snippet_choices(choices, selection.clone(), cx)
 5106                }
 5107            }
 5108
 5109            // If we're already at the last tabstop and it's at the end of the snippet,
 5110            // we're done, we don't need to keep the state around.
 5111            if !tabstop.is_end_tabstop {
 5112                let choices = tabstops
 5113                    .iter()
 5114                    .map(|tabstop| tabstop.choices.clone())
 5115                    .collect();
 5116
 5117                let ranges = tabstops
 5118                    .into_iter()
 5119                    .map(|tabstop| tabstop.ranges)
 5120                    .collect::<Vec<_>>();
 5121
 5122                self.snippet_stack.push(SnippetState {
 5123                    active_index: 0,
 5124                    ranges,
 5125                    choices,
 5126                });
 5127            }
 5128
 5129            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5130            if self.autoclose_regions.is_empty() {
 5131                let snapshot = self.buffer.read(cx).snapshot(cx);
 5132                for selection in &mut self.selections.all::<Point>(cx) {
 5133                    let selection_head = selection.head();
 5134                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5135                        continue;
 5136                    };
 5137
 5138                    let mut bracket_pair = None;
 5139                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5140                    let prev_chars = snapshot
 5141                        .reversed_chars_at(selection_head)
 5142                        .collect::<String>();
 5143                    for (pair, enabled) in scope.brackets() {
 5144                        if enabled
 5145                            && pair.close
 5146                            && prev_chars.starts_with(pair.start.as_str())
 5147                            && next_chars.starts_with(pair.end.as_str())
 5148                        {
 5149                            bracket_pair = Some(pair.clone());
 5150                            break;
 5151                        }
 5152                    }
 5153                    if let Some(pair) = bracket_pair {
 5154                        let start = snapshot.anchor_after(selection_head);
 5155                        let end = snapshot.anchor_after(selection_head);
 5156                        self.autoclose_regions.push(AutocloseRegion {
 5157                            selection_id: selection.id,
 5158                            range: start..end,
 5159                            pair,
 5160                        });
 5161                    }
 5162                }
 5163            }
 5164        }
 5165        Ok(())
 5166    }
 5167
 5168    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5169        self.move_to_snippet_tabstop(Bias::Right, cx)
 5170    }
 5171
 5172    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5173        self.move_to_snippet_tabstop(Bias::Left, cx)
 5174    }
 5175
 5176    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5177        if let Some(mut snippet) = self.snippet_stack.pop() {
 5178            match bias {
 5179                Bias::Left => {
 5180                    if snippet.active_index > 0 {
 5181                        snippet.active_index -= 1;
 5182                    } else {
 5183                        self.snippet_stack.push(snippet);
 5184                        return false;
 5185                    }
 5186                }
 5187                Bias::Right => {
 5188                    if snippet.active_index + 1 < snippet.ranges.len() {
 5189                        snippet.active_index += 1;
 5190                    } else {
 5191                        self.snippet_stack.push(snippet);
 5192                        return false;
 5193                    }
 5194                }
 5195            }
 5196            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5197                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5198                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5199                });
 5200
 5201                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5202                    if let Some(selection) = current_ranges.first() {
 5203                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5204                    }
 5205                }
 5206
 5207                // If snippet state is not at the last tabstop, push it back on the stack
 5208                if snippet.active_index + 1 < snippet.ranges.len() {
 5209                    self.snippet_stack.push(snippet);
 5210                }
 5211                return true;
 5212            }
 5213        }
 5214
 5215        false
 5216    }
 5217
 5218    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5219        self.transact(cx, |this, cx| {
 5220            this.select_all(&SelectAll, cx);
 5221            this.insert("", cx);
 5222        });
 5223    }
 5224
 5225    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5226        self.transact(cx, |this, cx| {
 5227            this.select_autoclose_pair(cx);
 5228            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5229            if !this.linked_edit_ranges.is_empty() {
 5230                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5231                let snapshot = this.buffer.read(cx).snapshot(cx);
 5232
 5233                for selection in selections.iter() {
 5234                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5235                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5236                    if selection_start.buffer_id != selection_end.buffer_id {
 5237                        continue;
 5238                    }
 5239                    if let Some(ranges) =
 5240                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5241                    {
 5242                        for (buffer, entries) in ranges {
 5243                            linked_ranges.entry(buffer).or_default().extend(entries);
 5244                        }
 5245                    }
 5246                }
 5247            }
 5248
 5249            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5250            if !this.selections.line_mode {
 5251                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5252                for selection in &mut selections {
 5253                    if selection.is_empty() {
 5254                        let old_head = selection.head();
 5255                        let mut new_head =
 5256                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5257                                .to_point(&display_map);
 5258                        if let Some((buffer, line_buffer_range)) = display_map
 5259                            .buffer_snapshot
 5260                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5261                        {
 5262                            let indent_size =
 5263                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5264                            let indent_len = match indent_size.kind {
 5265                                IndentKind::Space => {
 5266                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5267                                }
 5268                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5269                            };
 5270                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5271                                let indent_len = indent_len.get();
 5272                                new_head = cmp::min(
 5273                                    new_head,
 5274                                    MultiBufferPoint::new(
 5275                                        old_head.row,
 5276                                        ((old_head.column - 1) / indent_len) * indent_len,
 5277                                    ),
 5278                                );
 5279                            }
 5280                        }
 5281
 5282                        selection.set_head(new_head, SelectionGoal::None);
 5283                    }
 5284                }
 5285            }
 5286
 5287            this.signature_help_state.set_backspace_pressed(true);
 5288            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5289            this.insert("", cx);
 5290            let empty_str: Arc<str> = Arc::from("");
 5291            for (buffer, edits) in linked_ranges {
 5292                let snapshot = buffer.read(cx).snapshot();
 5293                use text::ToPoint as TP;
 5294
 5295                let edits = edits
 5296                    .into_iter()
 5297                    .map(|range| {
 5298                        let end_point = TP::to_point(&range.end, &snapshot);
 5299                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5300
 5301                        if end_point == start_point {
 5302                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5303                                .saturating_sub(1);
 5304                            start_point = TP::to_point(&offset, &snapshot);
 5305                        };
 5306
 5307                        (start_point..end_point, empty_str.clone())
 5308                    })
 5309                    .sorted_by_key(|(range, _)| range.start)
 5310                    .collect::<Vec<_>>();
 5311                buffer.update(cx, |this, cx| {
 5312                    this.edit(edits, None, cx);
 5313                })
 5314            }
 5315            this.refresh_inline_completion(true, false, cx);
 5316            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5317        });
 5318    }
 5319
 5320    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5321        self.transact(cx, |this, cx| {
 5322            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5323                let line_mode = s.line_mode;
 5324                s.move_with(|map, selection| {
 5325                    if selection.is_empty() && !line_mode {
 5326                        let cursor = movement::right(map, selection.head());
 5327                        selection.end = cursor;
 5328                        selection.reversed = true;
 5329                        selection.goal = SelectionGoal::None;
 5330                    }
 5331                })
 5332            });
 5333            this.insert("", cx);
 5334            this.refresh_inline_completion(true, false, cx);
 5335        });
 5336    }
 5337
 5338    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5339        if self.move_to_prev_snippet_tabstop(cx) {
 5340            return;
 5341        }
 5342
 5343        self.outdent(&Outdent, cx);
 5344    }
 5345
 5346    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5347        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5348            return;
 5349        }
 5350
 5351        let mut selections = self.selections.all_adjusted(cx);
 5352        let buffer = self.buffer.read(cx);
 5353        let snapshot = buffer.snapshot(cx);
 5354        let rows_iter = selections.iter().map(|s| s.head().row);
 5355        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5356
 5357        let mut edits = Vec::new();
 5358        let mut prev_edited_row = 0;
 5359        let mut row_delta = 0;
 5360        for selection in &mut selections {
 5361            if selection.start.row != prev_edited_row {
 5362                row_delta = 0;
 5363            }
 5364            prev_edited_row = selection.end.row;
 5365
 5366            // If the selection is non-empty, then increase the indentation of the selected lines.
 5367            if !selection.is_empty() {
 5368                row_delta =
 5369                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5370                continue;
 5371            }
 5372
 5373            // If the selection is empty and the cursor is in the leading whitespace before the
 5374            // suggested indentation, then auto-indent the line.
 5375            let cursor = selection.head();
 5376            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5377            if let Some(suggested_indent) =
 5378                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5379            {
 5380                if cursor.column < suggested_indent.len
 5381                    && cursor.column <= current_indent.len
 5382                    && current_indent.len <= suggested_indent.len
 5383                {
 5384                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5385                    selection.end = selection.start;
 5386                    if row_delta == 0 {
 5387                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5388                            cursor.row,
 5389                            current_indent,
 5390                            suggested_indent,
 5391                        ));
 5392                        row_delta = suggested_indent.len - current_indent.len;
 5393                    }
 5394                    continue;
 5395                }
 5396            }
 5397
 5398            // Otherwise, insert a hard or soft tab.
 5399            let settings = buffer.settings_at(cursor, cx);
 5400            let tab_size = if settings.hard_tabs {
 5401                IndentSize::tab()
 5402            } else {
 5403                let tab_size = settings.tab_size.get();
 5404                let char_column = snapshot
 5405                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5406                    .flat_map(str::chars)
 5407                    .count()
 5408                    + row_delta as usize;
 5409                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5410                IndentSize::spaces(chars_to_next_tab_stop)
 5411            };
 5412            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5413            selection.end = selection.start;
 5414            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5415            row_delta += tab_size.len;
 5416        }
 5417
 5418        self.transact(cx, |this, cx| {
 5419            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5420            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5421            this.refresh_inline_completion(true, false, cx);
 5422        });
 5423    }
 5424
 5425    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5426        if self.read_only(cx) {
 5427            return;
 5428        }
 5429        let mut selections = self.selections.all::<Point>(cx);
 5430        let mut prev_edited_row = 0;
 5431        let mut row_delta = 0;
 5432        let mut edits = Vec::new();
 5433        let buffer = self.buffer.read(cx);
 5434        let snapshot = buffer.snapshot(cx);
 5435        for selection in &mut selections {
 5436            if selection.start.row != prev_edited_row {
 5437                row_delta = 0;
 5438            }
 5439            prev_edited_row = selection.end.row;
 5440
 5441            row_delta =
 5442                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5443        }
 5444
 5445        self.transact(cx, |this, cx| {
 5446            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5447            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5448        });
 5449    }
 5450
 5451    fn indent_selection(
 5452        buffer: &MultiBuffer,
 5453        snapshot: &MultiBufferSnapshot,
 5454        selection: &mut Selection<Point>,
 5455        edits: &mut Vec<(Range<Point>, String)>,
 5456        delta_for_start_row: u32,
 5457        cx: &AppContext,
 5458    ) -> u32 {
 5459        let settings = buffer.settings_at(selection.start, cx);
 5460        let tab_size = settings.tab_size.get();
 5461        let indent_kind = if settings.hard_tabs {
 5462            IndentKind::Tab
 5463        } else {
 5464            IndentKind::Space
 5465        };
 5466        let mut start_row = selection.start.row;
 5467        let mut end_row = selection.end.row + 1;
 5468
 5469        // If a selection ends at the beginning of a line, don't indent
 5470        // that last line.
 5471        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5472            end_row -= 1;
 5473        }
 5474
 5475        // Avoid re-indenting a row that has already been indented by a
 5476        // previous selection, but still update this selection's column
 5477        // to reflect that indentation.
 5478        if delta_for_start_row > 0 {
 5479            start_row += 1;
 5480            selection.start.column += delta_for_start_row;
 5481            if selection.end.row == selection.start.row {
 5482                selection.end.column += delta_for_start_row;
 5483            }
 5484        }
 5485
 5486        let mut delta_for_end_row = 0;
 5487        let has_multiple_rows = start_row + 1 != end_row;
 5488        for row in start_row..end_row {
 5489            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5490            let indent_delta = match (current_indent.kind, indent_kind) {
 5491                (IndentKind::Space, IndentKind::Space) => {
 5492                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5493                    IndentSize::spaces(columns_to_next_tab_stop)
 5494                }
 5495                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5496                (_, IndentKind::Tab) => IndentSize::tab(),
 5497            };
 5498
 5499            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5500                0
 5501            } else {
 5502                selection.start.column
 5503            };
 5504            let row_start = Point::new(row, start);
 5505            edits.push((
 5506                row_start..row_start,
 5507                indent_delta.chars().collect::<String>(),
 5508            ));
 5509
 5510            // Update this selection's endpoints to reflect the indentation.
 5511            if row == selection.start.row {
 5512                selection.start.column += indent_delta.len;
 5513            }
 5514            if row == selection.end.row {
 5515                selection.end.column += indent_delta.len;
 5516                delta_for_end_row = indent_delta.len;
 5517            }
 5518        }
 5519
 5520        if selection.start.row == selection.end.row {
 5521            delta_for_start_row + delta_for_end_row
 5522        } else {
 5523            delta_for_end_row
 5524        }
 5525    }
 5526
 5527    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5528        if self.read_only(cx) {
 5529            return;
 5530        }
 5531        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5532        let selections = self.selections.all::<Point>(cx);
 5533        let mut deletion_ranges = Vec::new();
 5534        let mut last_outdent = None;
 5535        {
 5536            let buffer = self.buffer.read(cx);
 5537            let snapshot = buffer.snapshot(cx);
 5538            for selection in &selections {
 5539                let settings = buffer.settings_at(selection.start, cx);
 5540                let tab_size = settings.tab_size.get();
 5541                let mut rows = selection.spanned_rows(false, &display_map);
 5542
 5543                // Avoid re-outdenting a row that has already been outdented by a
 5544                // previous selection.
 5545                if let Some(last_row) = last_outdent {
 5546                    if last_row == rows.start {
 5547                        rows.start = rows.start.next_row();
 5548                    }
 5549                }
 5550                let has_multiple_rows = rows.len() > 1;
 5551                for row in rows.iter_rows() {
 5552                    let indent_size = snapshot.indent_size_for_line(row);
 5553                    if indent_size.len > 0 {
 5554                        let deletion_len = match indent_size.kind {
 5555                            IndentKind::Space => {
 5556                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5557                                if columns_to_prev_tab_stop == 0 {
 5558                                    tab_size
 5559                                } else {
 5560                                    columns_to_prev_tab_stop
 5561                                }
 5562                            }
 5563                            IndentKind::Tab => 1,
 5564                        };
 5565                        let start = if has_multiple_rows
 5566                            || deletion_len > selection.start.column
 5567                            || indent_size.len < selection.start.column
 5568                        {
 5569                            0
 5570                        } else {
 5571                            selection.start.column - deletion_len
 5572                        };
 5573                        deletion_ranges.push(
 5574                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5575                        );
 5576                        last_outdent = Some(row);
 5577                    }
 5578                }
 5579            }
 5580        }
 5581
 5582        self.transact(cx, |this, cx| {
 5583            this.buffer.update(cx, |buffer, cx| {
 5584                let empty_str: Arc<str> = Arc::default();
 5585                buffer.edit(
 5586                    deletion_ranges
 5587                        .into_iter()
 5588                        .map(|range| (range, empty_str.clone())),
 5589                    None,
 5590                    cx,
 5591                );
 5592            });
 5593            let selections = this.selections.all::<usize>(cx);
 5594            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5595        });
 5596    }
 5597
 5598    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5599        if self.read_only(cx) {
 5600            return;
 5601        }
 5602        let selections = self
 5603            .selections
 5604            .all::<usize>(cx)
 5605            .into_iter()
 5606            .map(|s| s.range());
 5607
 5608        self.transact(cx, |this, cx| {
 5609            this.buffer.update(cx, |buffer, cx| {
 5610                buffer.autoindent_ranges(selections, cx);
 5611            });
 5612            let selections = this.selections.all::<usize>(cx);
 5613            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5614        });
 5615    }
 5616
 5617    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5619        let selections = self.selections.all::<Point>(cx);
 5620
 5621        let mut new_cursors = Vec::new();
 5622        let mut edit_ranges = Vec::new();
 5623        let mut selections = selections.iter().peekable();
 5624        while let Some(selection) = selections.next() {
 5625            let mut rows = selection.spanned_rows(false, &display_map);
 5626            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5627
 5628            // Accumulate contiguous regions of rows that we want to delete.
 5629            while let Some(next_selection) = selections.peek() {
 5630                let next_rows = next_selection.spanned_rows(false, &display_map);
 5631                if next_rows.start <= rows.end {
 5632                    rows.end = next_rows.end;
 5633                    selections.next().unwrap();
 5634                } else {
 5635                    break;
 5636                }
 5637            }
 5638
 5639            let buffer = &display_map.buffer_snapshot;
 5640            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5641            let edit_end;
 5642            let cursor_buffer_row;
 5643            if buffer.max_point().row >= rows.end.0 {
 5644                // If there's a line after the range, delete the \n from the end of the row range
 5645                // and position the cursor on the next line.
 5646                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5647                cursor_buffer_row = rows.end;
 5648            } else {
 5649                // If there isn't a line after the range, delete the \n from the line before the
 5650                // start of the row range and position the cursor there.
 5651                edit_start = edit_start.saturating_sub(1);
 5652                edit_end = buffer.len();
 5653                cursor_buffer_row = rows.start.previous_row();
 5654            }
 5655
 5656            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5657            *cursor.column_mut() =
 5658                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5659
 5660            new_cursors.push((
 5661                selection.id,
 5662                buffer.anchor_after(cursor.to_point(&display_map)),
 5663            ));
 5664            edit_ranges.push(edit_start..edit_end);
 5665        }
 5666
 5667        self.transact(cx, |this, cx| {
 5668            let buffer = this.buffer.update(cx, |buffer, cx| {
 5669                let empty_str: Arc<str> = Arc::default();
 5670                buffer.edit(
 5671                    edit_ranges
 5672                        .into_iter()
 5673                        .map(|range| (range, empty_str.clone())),
 5674                    None,
 5675                    cx,
 5676                );
 5677                buffer.snapshot(cx)
 5678            });
 5679            let new_selections = new_cursors
 5680                .into_iter()
 5681                .map(|(id, cursor)| {
 5682                    let cursor = cursor.to_point(&buffer);
 5683                    Selection {
 5684                        id,
 5685                        start: cursor,
 5686                        end: cursor,
 5687                        reversed: false,
 5688                        goal: SelectionGoal::None,
 5689                    }
 5690                })
 5691                .collect();
 5692
 5693            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5694                s.select(new_selections);
 5695            });
 5696        });
 5697    }
 5698
 5699    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5700        if self.read_only(cx) {
 5701            return;
 5702        }
 5703        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5704        for selection in self.selections.all::<Point>(cx) {
 5705            let start = MultiBufferRow(selection.start.row);
 5706            // Treat single line selections as if they include the next line. Otherwise this action
 5707            // would do nothing for single line selections individual cursors.
 5708            let end = if selection.start.row == selection.end.row {
 5709                MultiBufferRow(selection.start.row + 1)
 5710            } else {
 5711                MultiBufferRow(selection.end.row)
 5712            };
 5713
 5714            if let Some(last_row_range) = row_ranges.last_mut() {
 5715                if start <= last_row_range.end {
 5716                    last_row_range.end = end;
 5717                    continue;
 5718                }
 5719            }
 5720            row_ranges.push(start..end);
 5721        }
 5722
 5723        let snapshot = self.buffer.read(cx).snapshot(cx);
 5724        let mut cursor_positions = Vec::new();
 5725        for row_range in &row_ranges {
 5726            let anchor = snapshot.anchor_before(Point::new(
 5727                row_range.end.previous_row().0,
 5728                snapshot.line_len(row_range.end.previous_row()),
 5729            ));
 5730            cursor_positions.push(anchor..anchor);
 5731        }
 5732
 5733        self.transact(cx, |this, cx| {
 5734            for row_range in row_ranges.into_iter().rev() {
 5735                for row in row_range.iter_rows().rev() {
 5736                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5737                    let next_line_row = row.next_row();
 5738                    let indent = snapshot.indent_size_for_line(next_line_row);
 5739                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5740
 5741                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5742                        " "
 5743                    } else {
 5744                        ""
 5745                    };
 5746
 5747                    this.buffer.update(cx, |buffer, cx| {
 5748                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5749                    });
 5750                }
 5751            }
 5752
 5753            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5754                s.select_anchor_ranges(cursor_positions)
 5755            });
 5756        });
 5757    }
 5758
 5759    pub fn sort_lines_case_sensitive(
 5760        &mut self,
 5761        _: &SortLinesCaseSensitive,
 5762        cx: &mut ViewContext<Self>,
 5763    ) {
 5764        self.manipulate_lines(cx, |lines| lines.sort())
 5765    }
 5766
 5767    pub fn sort_lines_case_insensitive(
 5768        &mut self,
 5769        _: &SortLinesCaseInsensitive,
 5770        cx: &mut ViewContext<Self>,
 5771    ) {
 5772        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5773    }
 5774
 5775    pub fn unique_lines_case_insensitive(
 5776        &mut self,
 5777        _: &UniqueLinesCaseInsensitive,
 5778        cx: &mut ViewContext<Self>,
 5779    ) {
 5780        self.manipulate_lines(cx, |lines| {
 5781            let mut seen = HashSet::default();
 5782            lines.retain(|line| seen.insert(line.to_lowercase()));
 5783        })
 5784    }
 5785
 5786    pub fn unique_lines_case_sensitive(
 5787        &mut self,
 5788        _: &UniqueLinesCaseSensitive,
 5789        cx: &mut ViewContext<Self>,
 5790    ) {
 5791        self.manipulate_lines(cx, |lines| {
 5792            let mut seen = HashSet::default();
 5793            lines.retain(|line| seen.insert(*line));
 5794        })
 5795    }
 5796
 5797    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5798        let mut revert_changes = HashMap::default();
 5799        let snapshot = self.snapshot(cx);
 5800        for hunk in hunks_for_ranges(
 5801            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5802            &snapshot,
 5803        ) {
 5804            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5805        }
 5806        if !revert_changes.is_empty() {
 5807            self.transact(cx, |editor, cx| {
 5808                editor.revert(revert_changes, cx);
 5809            });
 5810        }
 5811    }
 5812
 5813    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5814        let Some(project) = self.project.clone() else {
 5815            return;
 5816        };
 5817        self.reload(project, cx).detach_and_notify_err(cx);
 5818    }
 5819
 5820    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5821        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5822        if !revert_changes.is_empty() {
 5823            self.transact(cx, |editor, cx| {
 5824                editor.revert(revert_changes, cx);
 5825            });
 5826        }
 5827    }
 5828
 5829    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5830        let snapshot = self.buffer.read(cx).read(cx);
 5831        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5832            drop(snapshot);
 5833            let mut revert_changes = HashMap::default();
 5834            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5835            if !revert_changes.is_empty() {
 5836                self.revert(revert_changes, cx)
 5837            }
 5838        }
 5839    }
 5840
 5841    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5842        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5843            let project_path = buffer.read(cx).project_path(cx)?;
 5844            let project = self.project.as_ref()?.read(cx);
 5845            let entry = project.entry_for_path(&project_path, cx)?;
 5846            let parent = match &entry.canonical_path {
 5847                Some(canonical_path) => canonical_path.to_path_buf(),
 5848                None => project.absolute_path(&project_path, cx)?,
 5849            }
 5850            .parent()?
 5851            .to_path_buf();
 5852            Some(parent)
 5853        }) {
 5854            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5855        }
 5856    }
 5857
 5858    fn gather_revert_changes(
 5859        &mut self,
 5860        selections: &[Selection<Point>],
 5861        cx: &mut ViewContext<'_, Editor>,
 5862    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5863        let mut revert_changes = HashMap::default();
 5864        let snapshot = self.snapshot(cx);
 5865        for hunk in hunks_for_selections(&snapshot, selections) {
 5866            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5867        }
 5868        revert_changes
 5869    }
 5870
 5871    pub fn prepare_revert_change(
 5872        &mut self,
 5873        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5874        hunk: &MultiBufferDiffHunk,
 5875        cx: &AppContext,
 5876    ) -> Option<()> {
 5877        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5878        let buffer = buffer.read(cx);
 5879        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5880        let original_text = change_set
 5881            .read(cx)
 5882            .base_text
 5883            .as_ref()?
 5884            .read(cx)
 5885            .as_rope()
 5886            .slice(hunk.diff_base_byte_range.clone());
 5887        let buffer_snapshot = buffer.snapshot();
 5888        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5889        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5890            probe
 5891                .0
 5892                .start
 5893                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5894                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5895        }) {
 5896            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5897            Some(())
 5898        } else {
 5899            None
 5900        }
 5901    }
 5902
 5903    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5904        self.manipulate_lines(cx, |lines| lines.reverse())
 5905    }
 5906
 5907    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5908        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5909    }
 5910
 5911    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5912    where
 5913        Fn: FnMut(&mut Vec<&str>),
 5914    {
 5915        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5916        let buffer = self.buffer.read(cx).snapshot(cx);
 5917
 5918        let mut edits = Vec::new();
 5919
 5920        let selections = self.selections.all::<Point>(cx);
 5921        let mut selections = selections.iter().peekable();
 5922        let mut contiguous_row_selections = Vec::new();
 5923        let mut new_selections = Vec::new();
 5924        let mut added_lines = 0;
 5925        let mut removed_lines = 0;
 5926
 5927        while let Some(selection) = selections.next() {
 5928            let (start_row, end_row) = consume_contiguous_rows(
 5929                &mut contiguous_row_selections,
 5930                selection,
 5931                &display_map,
 5932                &mut selections,
 5933            );
 5934
 5935            let start_point = Point::new(start_row.0, 0);
 5936            let end_point = Point::new(
 5937                end_row.previous_row().0,
 5938                buffer.line_len(end_row.previous_row()),
 5939            );
 5940            let text = buffer
 5941                .text_for_range(start_point..end_point)
 5942                .collect::<String>();
 5943
 5944            let mut lines = text.split('\n').collect_vec();
 5945
 5946            let lines_before = lines.len();
 5947            callback(&mut lines);
 5948            let lines_after = lines.len();
 5949
 5950            edits.push((start_point..end_point, lines.join("\n")));
 5951
 5952            // Selections must change based on added and removed line count
 5953            let start_row =
 5954                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5955            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5956            new_selections.push(Selection {
 5957                id: selection.id,
 5958                start: start_row,
 5959                end: end_row,
 5960                goal: SelectionGoal::None,
 5961                reversed: selection.reversed,
 5962            });
 5963
 5964            if lines_after > lines_before {
 5965                added_lines += lines_after - lines_before;
 5966            } else if lines_before > lines_after {
 5967                removed_lines += lines_before - lines_after;
 5968            }
 5969        }
 5970
 5971        self.transact(cx, |this, cx| {
 5972            let buffer = this.buffer.update(cx, |buffer, cx| {
 5973                buffer.edit(edits, None, cx);
 5974                buffer.snapshot(cx)
 5975            });
 5976
 5977            // Recalculate offsets on newly edited buffer
 5978            let new_selections = new_selections
 5979                .iter()
 5980                .map(|s| {
 5981                    let start_point = Point::new(s.start.0, 0);
 5982                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5983                    Selection {
 5984                        id: s.id,
 5985                        start: buffer.point_to_offset(start_point),
 5986                        end: buffer.point_to_offset(end_point),
 5987                        goal: s.goal,
 5988                        reversed: s.reversed,
 5989                    }
 5990                })
 5991                .collect();
 5992
 5993            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5994                s.select(new_selections);
 5995            });
 5996
 5997            this.request_autoscroll(Autoscroll::fit(), cx);
 5998        });
 5999    }
 6000
 6001    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6002        self.manipulate_text(cx, |text| text.to_uppercase())
 6003    }
 6004
 6005    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6006        self.manipulate_text(cx, |text| text.to_lowercase())
 6007    }
 6008
 6009    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6010        self.manipulate_text(cx, |text| {
 6011            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6012            // https://github.com/rutrum/convert-case/issues/16
 6013            text.split('\n')
 6014                .map(|line| line.to_case(Case::Title))
 6015                .join("\n")
 6016        })
 6017    }
 6018
 6019    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6020        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6021    }
 6022
 6023    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6024        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6025    }
 6026
 6027    pub fn convert_to_upper_camel_case(
 6028        &mut self,
 6029        _: &ConvertToUpperCamelCase,
 6030        cx: &mut ViewContext<Self>,
 6031    ) {
 6032        self.manipulate_text(cx, |text| {
 6033            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6034            // https://github.com/rutrum/convert-case/issues/16
 6035            text.split('\n')
 6036                .map(|line| line.to_case(Case::UpperCamel))
 6037                .join("\n")
 6038        })
 6039    }
 6040
 6041    pub fn convert_to_lower_camel_case(
 6042        &mut self,
 6043        _: &ConvertToLowerCamelCase,
 6044        cx: &mut ViewContext<Self>,
 6045    ) {
 6046        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6047    }
 6048
 6049    pub fn convert_to_opposite_case(
 6050        &mut self,
 6051        _: &ConvertToOppositeCase,
 6052        cx: &mut ViewContext<Self>,
 6053    ) {
 6054        self.manipulate_text(cx, |text| {
 6055            text.chars()
 6056                .fold(String::with_capacity(text.len()), |mut t, c| {
 6057                    if c.is_uppercase() {
 6058                        t.extend(c.to_lowercase());
 6059                    } else {
 6060                        t.extend(c.to_uppercase());
 6061                    }
 6062                    t
 6063                })
 6064        })
 6065    }
 6066
 6067    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6068    where
 6069        Fn: FnMut(&str) -> String,
 6070    {
 6071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6072        let buffer = self.buffer.read(cx).snapshot(cx);
 6073
 6074        let mut new_selections = Vec::new();
 6075        let mut edits = Vec::new();
 6076        let mut selection_adjustment = 0i32;
 6077
 6078        for selection in self.selections.all::<usize>(cx) {
 6079            let selection_is_empty = selection.is_empty();
 6080
 6081            let (start, end) = if selection_is_empty {
 6082                let word_range = movement::surrounding_word(
 6083                    &display_map,
 6084                    selection.start.to_display_point(&display_map),
 6085                );
 6086                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6087                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6088                (start, end)
 6089            } else {
 6090                (selection.start, selection.end)
 6091            };
 6092
 6093            let text = buffer.text_for_range(start..end).collect::<String>();
 6094            let old_length = text.len() as i32;
 6095            let text = callback(&text);
 6096
 6097            new_selections.push(Selection {
 6098                start: (start as i32 - selection_adjustment) as usize,
 6099                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6100                goal: SelectionGoal::None,
 6101                ..selection
 6102            });
 6103
 6104            selection_adjustment += old_length - text.len() as i32;
 6105
 6106            edits.push((start..end, text));
 6107        }
 6108
 6109        self.transact(cx, |this, cx| {
 6110            this.buffer.update(cx, |buffer, cx| {
 6111                buffer.edit(edits, None, cx);
 6112            });
 6113
 6114            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6115                s.select(new_selections);
 6116            });
 6117
 6118            this.request_autoscroll(Autoscroll::fit(), cx);
 6119        });
 6120    }
 6121
 6122    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6124        let buffer = &display_map.buffer_snapshot;
 6125        let selections = self.selections.all::<Point>(cx);
 6126
 6127        let mut edits = Vec::new();
 6128        for selection in selections.iter() {
 6129            let start = selection.start;
 6130            let end = selection.end;
 6131            let text = buffer.text_for_range(start..end).collect::<String>();
 6132            edits.push((selection.end..selection.end, text));
 6133        }
 6134
 6135        self.transact(cx, |this, cx| {
 6136            this.buffer.update(cx, |buffer, cx| {
 6137                buffer.edit(edits, None, cx);
 6138            });
 6139
 6140            this.request_autoscroll(Autoscroll::fit(), cx);
 6141        });
 6142    }
 6143
 6144    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6145        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6146        let buffer = &display_map.buffer_snapshot;
 6147        let selections = self.selections.all::<Point>(cx);
 6148
 6149        let mut edits = Vec::new();
 6150        let mut selections_iter = selections.iter().peekable();
 6151        while let Some(selection) = selections_iter.next() {
 6152            // Avoid duplicating the same lines twice.
 6153            let mut rows = selection.spanned_rows(false, &display_map);
 6154
 6155            while let Some(next_selection) = selections_iter.peek() {
 6156                let next_rows = next_selection.spanned_rows(false, &display_map);
 6157                if next_rows.start < rows.end {
 6158                    rows.end = next_rows.end;
 6159                    selections_iter.next().unwrap();
 6160                } else {
 6161                    break;
 6162                }
 6163            }
 6164
 6165            // Copy the text from the selected row region and splice it either at the start
 6166            // or end of the region.
 6167            let start = Point::new(rows.start.0, 0);
 6168            let end = Point::new(
 6169                rows.end.previous_row().0,
 6170                buffer.line_len(rows.end.previous_row()),
 6171            );
 6172            let text = buffer
 6173                .text_for_range(start..end)
 6174                .chain(Some("\n"))
 6175                .collect::<String>();
 6176            let insert_location = if upwards {
 6177                Point::new(rows.end.0, 0)
 6178            } else {
 6179                start
 6180            };
 6181            edits.push((insert_location..insert_location, text));
 6182        }
 6183
 6184        self.transact(cx, |this, cx| {
 6185            this.buffer.update(cx, |buffer, cx| {
 6186                buffer.edit(edits, None, cx);
 6187            });
 6188
 6189            this.request_autoscroll(Autoscroll::fit(), cx);
 6190        });
 6191    }
 6192
 6193    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6194        self.duplicate_line(true, cx);
 6195    }
 6196
 6197    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6198        self.duplicate_line(false, cx);
 6199    }
 6200
 6201    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6203        let buffer = self.buffer.read(cx).snapshot(cx);
 6204
 6205        let mut edits = Vec::new();
 6206        let mut unfold_ranges = Vec::new();
 6207        let mut refold_creases = Vec::new();
 6208
 6209        let selections = self.selections.all::<Point>(cx);
 6210        let mut selections = selections.iter().peekable();
 6211        let mut contiguous_row_selections = Vec::new();
 6212        let mut new_selections = Vec::new();
 6213
 6214        while let Some(selection) = selections.next() {
 6215            // Find all the selections that span a contiguous row range
 6216            let (start_row, end_row) = consume_contiguous_rows(
 6217                &mut contiguous_row_selections,
 6218                selection,
 6219                &display_map,
 6220                &mut selections,
 6221            );
 6222
 6223            // Move the text spanned by the row range to be before the line preceding the row range
 6224            if start_row.0 > 0 {
 6225                let range_to_move = Point::new(
 6226                    start_row.previous_row().0,
 6227                    buffer.line_len(start_row.previous_row()),
 6228                )
 6229                    ..Point::new(
 6230                        end_row.previous_row().0,
 6231                        buffer.line_len(end_row.previous_row()),
 6232                    );
 6233                let insertion_point = display_map
 6234                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6235                    .0;
 6236
 6237                // Don't move lines across excerpts
 6238                if buffer
 6239                    .excerpt_boundaries_in_range((
 6240                        Bound::Excluded(insertion_point),
 6241                        Bound::Included(range_to_move.end),
 6242                    ))
 6243                    .next()
 6244                    .is_none()
 6245                {
 6246                    let text = buffer
 6247                        .text_for_range(range_to_move.clone())
 6248                        .flat_map(|s| s.chars())
 6249                        .skip(1)
 6250                        .chain(['\n'])
 6251                        .collect::<String>();
 6252
 6253                    edits.push((
 6254                        buffer.anchor_after(range_to_move.start)
 6255                            ..buffer.anchor_before(range_to_move.end),
 6256                        String::new(),
 6257                    ));
 6258                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6259                    edits.push((insertion_anchor..insertion_anchor, text));
 6260
 6261                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6262
 6263                    // Move selections up
 6264                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6265                        |mut selection| {
 6266                            selection.start.row -= row_delta;
 6267                            selection.end.row -= row_delta;
 6268                            selection
 6269                        },
 6270                    ));
 6271
 6272                    // Move folds up
 6273                    unfold_ranges.push(range_to_move.clone());
 6274                    for fold in display_map.folds_in_range(
 6275                        buffer.anchor_before(range_to_move.start)
 6276                            ..buffer.anchor_after(range_to_move.end),
 6277                    ) {
 6278                        let mut start = fold.range.start.to_point(&buffer);
 6279                        let mut end = fold.range.end.to_point(&buffer);
 6280                        start.row -= row_delta;
 6281                        end.row -= row_delta;
 6282                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6283                    }
 6284                }
 6285            }
 6286
 6287            // If we didn't move line(s), preserve the existing selections
 6288            new_selections.append(&mut contiguous_row_selections);
 6289        }
 6290
 6291        self.transact(cx, |this, cx| {
 6292            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6293            this.buffer.update(cx, |buffer, cx| {
 6294                for (range, text) in edits {
 6295                    buffer.edit([(range, text)], None, cx);
 6296                }
 6297            });
 6298            this.fold_creases(refold_creases, true, cx);
 6299            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6300                s.select(new_selections);
 6301            })
 6302        });
 6303    }
 6304
 6305    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6306        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6307        let buffer = self.buffer.read(cx).snapshot(cx);
 6308
 6309        let mut edits = Vec::new();
 6310        let mut unfold_ranges = Vec::new();
 6311        let mut refold_creases = Vec::new();
 6312
 6313        let selections = self.selections.all::<Point>(cx);
 6314        let mut selections = selections.iter().peekable();
 6315        let mut contiguous_row_selections = Vec::new();
 6316        let mut new_selections = Vec::new();
 6317
 6318        while let Some(selection) = selections.next() {
 6319            // Find all the selections that span a contiguous row range
 6320            let (start_row, end_row) = consume_contiguous_rows(
 6321                &mut contiguous_row_selections,
 6322                selection,
 6323                &display_map,
 6324                &mut selections,
 6325            );
 6326
 6327            // Move the text spanned by the row range to be after the last line of the row range
 6328            if end_row.0 <= buffer.max_point().row {
 6329                let range_to_move =
 6330                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6331                let insertion_point = display_map
 6332                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6333                    .0;
 6334
 6335                // Don't move lines across excerpt boundaries
 6336                if buffer
 6337                    .excerpt_boundaries_in_range((
 6338                        Bound::Excluded(range_to_move.start),
 6339                        Bound::Included(insertion_point),
 6340                    ))
 6341                    .next()
 6342                    .is_none()
 6343                {
 6344                    let mut text = String::from("\n");
 6345                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6346                    text.pop(); // Drop trailing newline
 6347                    edits.push((
 6348                        buffer.anchor_after(range_to_move.start)
 6349                            ..buffer.anchor_before(range_to_move.end),
 6350                        String::new(),
 6351                    ));
 6352                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6353                    edits.push((insertion_anchor..insertion_anchor, text));
 6354
 6355                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6356
 6357                    // Move selections down
 6358                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6359                        |mut selection| {
 6360                            selection.start.row += row_delta;
 6361                            selection.end.row += row_delta;
 6362                            selection
 6363                        },
 6364                    ));
 6365
 6366                    // Move folds down
 6367                    unfold_ranges.push(range_to_move.clone());
 6368                    for fold in display_map.folds_in_range(
 6369                        buffer.anchor_before(range_to_move.start)
 6370                            ..buffer.anchor_after(range_to_move.end),
 6371                    ) {
 6372                        let mut start = fold.range.start.to_point(&buffer);
 6373                        let mut end = fold.range.end.to_point(&buffer);
 6374                        start.row += row_delta;
 6375                        end.row += row_delta;
 6376                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6377                    }
 6378                }
 6379            }
 6380
 6381            // If we didn't move line(s), preserve the existing selections
 6382            new_selections.append(&mut contiguous_row_selections);
 6383        }
 6384
 6385        self.transact(cx, |this, cx| {
 6386            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6387            this.buffer.update(cx, |buffer, cx| {
 6388                for (range, text) in edits {
 6389                    buffer.edit([(range, text)], None, cx);
 6390                }
 6391            });
 6392            this.fold_creases(refold_creases, true, cx);
 6393            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6394        });
 6395    }
 6396
 6397    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6398        let text_layout_details = &self.text_layout_details(cx);
 6399        self.transact(cx, |this, cx| {
 6400            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6401                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6402                let line_mode = s.line_mode;
 6403                s.move_with(|display_map, selection| {
 6404                    if !selection.is_empty() || line_mode {
 6405                        return;
 6406                    }
 6407
 6408                    let mut head = selection.head();
 6409                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6410                    if head.column() == display_map.line_len(head.row()) {
 6411                        transpose_offset = display_map
 6412                            .buffer_snapshot
 6413                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6414                    }
 6415
 6416                    if transpose_offset == 0 {
 6417                        return;
 6418                    }
 6419
 6420                    *head.column_mut() += 1;
 6421                    head = display_map.clip_point(head, Bias::Right);
 6422                    let goal = SelectionGoal::HorizontalPosition(
 6423                        display_map
 6424                            .x_for_display_point(head, text_layout_details)
 6425                            .into(),
 6426                    );
 6427                    selection.collapse_to(head, goal);
 6428
 6429                    let transpose_start = display_map
 6430                        .buffer_snapshot
 6431                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6432                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6433                        let transpose_end = display_map
 6434                            .buffer_snapshot
 6435                            .clip_offset(transpose_offset + 1, Bias::Right);
 6436                        if let Some(ch) =
 6437                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6438                        {
 6439                            edits.push((transpose_start..transpose_offset, String::new()));
 6440                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6441                        }
 6442                    }
 6443                });
 6444                edits
 6445            });
 6446            this.buffer
 6447                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6448            let selections = this.selections.all::<usize>(cx);
 6449            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6450                s.select(selections);
 6451            });
 6452        });
 6453    }
 6454
 6455    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6456        self.rewrap_impl(IsVimMode::No, cx)
 6457    }
 6458
 6459    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6460        let buffer = self.buffer.read(cx).snapshot(cx);
 6461        let selections = self.selections.all::<Point>(cx);
 6462        let mut selections = selections.iter().peekable();
 6463
 6464        let mut edits = Vec::new();
 6465        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6466
 6467        while let Some(selection) = selections.next() {
 6468            let mut start_row = selection.start.row;
 6469            let mut end_row = selection.end.row;
 6470
 6471            // Skip selections that overlap with a range that has already been rewrapped.
 6472            let selection_range = start_row..end_row;
 6473            if rewrapped_row_ranges
 6474                .iter()
 6475                .any(|range| range.overlaps(&selection_range))
 6476            {
 6477                continue;
 6478            }
 6479
 6480            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6481
 6482            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6483                match language_scope.language_name().0.as_ref() {
 6484                    "Markdown" | "Plain Text" => {
 6485                        should_rewrap = true;
 6486                    }
 6487                    _ => {}
 6488                }
 6489            }
 6490
 6491            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6492
 6493            // Since not all lines in the selection may be at the same indent
 6494            // level, choose the indent size that is the most common between all
 6495            // of the lines.
 6496            //
 6497            // If there is a tie, we use the deepest indent.
 6498            let (indent_size, indent_end) = {
 6499                let mut indent_size_occurrences = HashMap::default();
 6500                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6501
 6502                for row in start_row..=end_row {
 6503                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6504                    rows_by_indent_size.entry(indent).or_default().push(row);
 6505                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6506                }
 6507
 6508                let indent_size = indent_size_occurrences
 6509                    .into_iter()
 6510                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6511                    .map(|(indent, _)| indent)
 6512                    .unwrap_or_default();
 6513                let row = rows_by_indent_size[&indent_size][0];
 6514                let indent_end = Point::new(row, indent_size.len);
 6515
 6516                (indent_size, indent_end)
 6517            };
 6518
 6519            let mut line_prefix = indent_size.chars().collect::<String>();
 6520
 6521            if let Some(comment_prefix) =
 6522                buffer
 6523                    .language_scope_at(selection.head())
 6524                    .and_then(|language| {
 6525                        language
 6526                            .line_comment_prefixes()
 6527                            .iter()
 6528                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6529                            .cloned()
 6530                    })
 6531            {
 6532                line_prefix.push_str(&comment_prefix);
 6533                should_rewrap = true;
 6534            }
 6535
 6536            if !should_rewrap {
 6537                continue;
 6538            }
 6539
 6540            if selection.is_empty() {
 6541                'expand_upwards: while start_row > 0 {
 6542                    let prev_row = start_row - 1;
 6543                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6544                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6545                    {
 6546                        start_row = prev_row;
 6547                    } else {
 6548                        break 'expand_upwards;
 6549                    }
 6550                }
 6551
 6552                'expand_downwards: while end_row < buffer.max_point().row {
 6553                    let next_row = end_row + 1;
 6554                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6555                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6556                    {
 6557                        end_row = next_row;
 6558                    } else {
 6559                        break 'expand_downwards;
 6560                    }
 6561                }
 6562            }
 6563
 6564            let start = Point::new(start_row, 0);
 6565            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6566            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6567            let Some(lines_without_prefixes) = selection_text
 6568                .lines()
 6569                .map(|line| {
 6570                    line.strip_prefix(&line_prefix)
 6571                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6572                        .ok_or_else(|| {
 6573                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6574                        })
 6575                })
 6576                .collect::<Result<Vec<_>, _>>()
 6577                .log_err()
 6578            else {
 6579                continue;
 6580            };
 6581
 6582            let wrap_column = buffer
 6583                .settings_at(Point::new(start_row, 0), cx)
 6584                .preferred_line_length as usize;
 6585            let wrapped_text = wrap_with_prefix(
 6586                line_prefix,
 6587                lines_without_prefixes.join(" "),
 6588                wrap_column,
 6589                tab_size,
 6590            );
 6591
 6592            // TODO: should always use char-based diff while still supporting cursor behavior that
 6593            // matches vim.
 6594            let diff = match is_vim_mode {
 6595                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6596                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6597            };
 6598            let mut offset = start.to_offset(&buffer);
 6599            let mut moved_since_edit = true;
 6600
 6601            for change in diff.iter_all_changes() {
 6602                let value = change.value();
 6603                match change.tag() {
 6604                    ChangeTag::Equal => {
 6605                        offset += value.len();
 6606                        moved_since_edit = true;
 6607                    }
 6608                    ChangeTag::Delete => {
 6609                        let start = buffer.anchor_after(offset);
 6610                        let end = buffer.anchor_before(offset + value.len());
 6611
 6612                        if moved_since_edit {
 6613                            edits.push((start..end, String::new()));
 6614                        } else {
 6615                            edits.last_mut().unwrap().0.end = end;
 6616                        }
 6617
 6618                        offset += value.len();
 6619                        moved_since_edit = false;
 6620                    }
 6621                    ChangeTag::Insert => {
 6622                        if moved_since_edit {
 6623                            let anchor = buffer.anchor_after(offset);
 6624                            edits.push((anchor..anchor, value.to_string()));
 6625                        } else {
 6626                            edits.last_mut().unwrap().1.push_str(value);
 6627                        }
 6628
 6629                        moved_since_edit = false;
 6630                    }
 6631                }
 6632            }
 6633
 6634            rewrapped_row_ranges.push(start_row..=end_row);
 6635        }
 6636
 6637        self.buffer
 6638            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6639    }
 6640
 6641    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6642        let mut text = String::new();
 6643        let buffer = self.buffer.read(cx).snapshot(cx);
 6644        let mut selections = self.selections.all::<Point>(cx);
 6645        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6646        {
 6647            let max_point = buffer.max_point();
 6648            let mut is_first = true;
 6649            for selection in &mut selections {
 6650                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6651                if is_entire_line {
 6652                    selection.start = Point::new(selection.start.row, 0);
 6653                    if !selection.is_empty() && selection.end.column == 0 {
 6654                        selection.end = cmp::min(max_point, selection.end);
 6655                    } else {
 6656                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6657                    }
 6658                    selection.goal = SelectionGoal::None;
 6659                }
 6660                if is_first {
 6661                    is_first = false;
 6662                } else {
 6663                    text += "\n";
 6664                }
 6665                let mut len = 0;
 6666                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6667                    text.push_str(chunk);
 6668                    len += chunk.len();
 6669                }
 6670                clipboard_selections.push(ClipboardSelection {
 6671                    len,
 6672                    is_entire_line,
 6673                    first_line_indent: buffer
 6674                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6675                        .len,
 6676                });
 6677            }
 6678        }
 6679
 6680        self.transact(cx, |this, cx| {
 6681            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6682                s.select(selections);
 6683            });
 6684            this.insert("", cx);
 6685        });
 6686        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6687    }
 6688
 6689    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6690        let item = self.cut_common(cx);
 6691        cx.write_to_clipboard(item);
 6692    }
 6693
 6694    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6695        self.change_selections(None, cx, |s| {
 6696            s.move_with(|snapshot, sel| {
 6697                if sel.is_empty() {
 6698                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6699                }
 6700            });
 6701        });
 6702        let item = self.cut_common(cx);
 6703        cx.set_global(KillRing(item))
 6704    }
 6705
 6706    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6707        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6708            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6709                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6710            } else {
 6711                return;
 6712            }
 6713        } else {
 6714            return;
 6715        };
 6716        self.do_paste(&text, metadata, false, cx);
 6717    }
 6718
 6719    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6720        let selections = self.selections.all::<Point>(cx);
 6721        let buffer = self.buffer.read(cx).read(cx);
 6722        let mut text = String::new();
 6723
 6724        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6725        {
 6726            let max_point = buffer.max_point();
 6727            let mut is_first = true;
 6728            for selection in selections.iter() {
 6729                let mut start = selection.start;
 6730                let mut end = selection.end;
 6731                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6732                if is_entire_line {
 6733                    start = Point::new(start.row, 0);
 6734                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6735                }
 6736                if is_first {
 6737                    is_first = false;
 6738                } else {
 6739                    text += "\n";
 6740                }
 6741                let mut len = 0;
 6742                for chunk in buffer.text_for_range(start..end) {
 6743                    text.push_str(chunk);
 6744                    len += chunk.len();
 6745                }
 6746                clipboard_selections.push(ClipboardSelection {
 6747                    len,
 6748                    is_entire_line,
 6749                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6750                });
 6751            }
 6752        }
 6753
 6754        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6755            text,
 6756            clipboard_selections,
 6757        ));
 6758    }
 6759
 6760    pub fn do_paste(
 6761        &mut self,
 6762        text: &String,
 6763        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6764        handle_entire_lines: bool,
 6765        cx: &mut ViewContext<Self>,
 6766    ) {
 6767        if self.read_only(cx) {
 6768            return;
 6769        }
 6770
 6771        let clipboard_text = Cow::Borrowed(text);
 6772
 6773        self.transact(cx, |this, cx| {
 6774            if let Some(mut clipboard_selections) = clipboard_selections {
 6775                let old_selections = this.selections.all::<usize>(cx);
 6776                let all_selections_were_entire_line =
 6777                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6778                let first_selection_indent_column =
 6779                    clipboard_selections.first().map(|s| s.first_line_indent);
 6780                if clipboard_selections.len() != old_selections.len() {
 6781                    clipboard_selections.drain(..);
 6782                }
 6783                let cursor_offset = this.selections.last::<usize>(cx).head();
 6784                let mut auto_indent_on_paste = true;
 6785
 6786                this.buffer.update(cx, |buffer, cx| {
 6787                    let snapshot = buffer.read(cx);
 6788                    auto_indent_on_paste =
 6789                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6790
 6791                    let mut start_offset = 0;
 6792                    let mut edits = Vec::new();
 6793                    let mut original_indent_columns = Vec::new();
 6794                    for (ix, selection) in old_selections.iter().enumerate() {
 6795                        let to_insert;
 6796                        let entire_line;
 6797                        let original_indent_column;
 6798                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6799                            let end_offset = start_offset + clipboard_selection.len;
 6800                            to_insert = &clipboard_text[start_offset..end_offset];
 6801                            entire_line = clipboard_selection.is_entire_line;
 6802                            start_offset = end_offset + 1;
 6803                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6804                        } else {
 6805                            to_insert = clipboard_text.as_str();
 6806                            entire_line = all_selections_were_entire_line;
 6807                            original_indent_column = first_selection_indent_column
 6808                        }
 6809
 6810                        // If the corresponding selection was empty when this slice of the
 6811                        // clipboard text was written, then the entire line containing the
 6812                        // selection was copied. If this selection is also currently empty,
 6813                        // then paste the line before the current line of the buffer.
 6814                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6815                            let column = selection.start.to_point(&snapshot).column as usize;
 6816                            let line_start = selection.start - column;
 6817                            line_start..line_start
 6818                        } else {
 6819                            selection.range()
 6820                        };
 6821
 6822                        edits.push((range, to_insert));
 6823                        original_indent_columns.extend(original_indent_column);
 6824                    }
 6825                    drop(snapshot);
 6826
 6827                    buffer.edit(
 6828                        edits,
 6829                        if auto_indent_on_paste {
 6830                            Some(AutoindentMode::Block {
 6831                                original_indent_columns,
 6832                            })
 6833                        } else {
 6834                            None
 6835                        },
 6836                        cx,
 6837                    );
 6838                });
 6839
 6840                let selections = this.selections.all::<usize>(cx);
 6841                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6842            } else {
 6843                this.insert(&clipboard_text, cx);
 6844            }
 6845        });
 6846    }
 6847
 6848    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6849        if let Some(item) = cx.read_from_clipboard() {
 6850            let entries = item.entries();
 6851
 6852            match entries.first() {
 6853                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6854                // of all the pasted entries.
 6855                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6856                    .do_paste(
 6857                        clipboard_string.text(),
 6858                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6859                        true,
 6860                        cx,
 6861                    ),
 6862                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6863            }
 6864        }
 6865    }
 6866
 6867    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6868        if self.read_only(cx) {
 6869            return;
 6870        }
 6871
 6872        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6873            if let Some((selections, _)) =
 6874                self.selection_history.transaction(transaction_id).cloned()
 6875            {
 6876                self.change_selections(None, cx, |s| {
 6877                    s.select_anchors(selections.to_vec());
 6878                });
 6879            }
 6880            self.request_autoscroll(Autoscroll::fit(), cx);
 6881            self.unmark_text(cx);
 6882            self.refresh_inline_completion(true, false, cx);
 6883            cx.emit(EditorEvent::Edited { transaction_id });
 6884            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6885        }
 6886    }
 6887
 6888    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6889        if self.read_only(cx) {
 6890            return;
 6891        }
 6892
 6893        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6894            if let Some((_, Some(selections))) =
 6895                self.selection_history.transaction(transaction_id).cloned()
 6896            {
 6897                self.change_selections(None, cx, |s| {
 6898                    s.select_anchors(selections.to_vec());
 6899                });
 6900            }
 6901            self.request_autoscroll(Autoscroll::fit(), cx);
 6902            self.unmark_text(cx);
 6903            self.refresh_inline_completion(true, false, cx);
 6904            cx.emit(EditorEvent::Edited { transaction_id });
 6905        }
 6906    }
 6907
 6908    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6909        self.buffer
 6910            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6911    }
 6912
 6913    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6914        self.buffer
 6915            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6916    }
 6917
 6918    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6919        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6920            let line_mode = s.line_mode;
 6921            s.move_with(|map, selection| {
 6922                let cursor = if selection.is_empty() && !line_mode {
 6923                    movement::left(map, selection.start)
 6924                } else {
 6925                    selection.start
 6926                };
 6927                selection.collapse_to(cursor, SelectionGoal::None);
 6928            });
 6929        })
 6930    }
 6931
 6932    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6933        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6934            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6935        })
 6936    }
 6937
 6938    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6939        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6940            let line_mode = s.line_mode;
 6941            s.move_with(|map, selection| {
 6942                let cursor = if selection.is_empty() && !line_mode {
 6943                    movement::right(map, selection.end)
 6944                } else {
 6945                    selection.end
 6946                };
 6947                selection.collapse_to(cursor, SelectionGoal::None)
 6948            });
 6949        })
 6950    }
 6951
 6952    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6953        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6954            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6955        })
 6956    }
 6957
 6958    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6959        if self.take_rename(true, cx).is_some() {
 6960            return;
 6961        }
 6962
 6963        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6964            cx.propagate();
 6965            return;
 6966        }
 6967
 6968        let text_layout_details = &self.text_layout_details(cx);
 6969        let selection_count = self.selections.count();
 6970        let first_selection = self.selections.first_anchor();
 6971
 6972        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6973            let line_mode = s.line_mode;
 6974            s.move_with(|map, selection| {
 6975                if !selection.is_empty() && !line_mode {
 6976                    selection.goal = SelectionGoal::None;
 6977                }
 6978                let (cursor, goal) = movement::up(
 6979                    map,
 6980                    selection.start,
 6981                    selection.goal,
 6982                    false,
 6983                    text_layout_details,
 6984                );
 6985                selection.collapse_to(cursor, goal);
 6986            });
 6987        });
 6988
 6989        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6990        {
 6991            cx.propagate();
 6992        }
 6993    }
 6994
 6995    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6996        if self.take_rename(true, cx).is_some() {
 6997            return;
 6998        }
 6999
 7000        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7001            cx.propagate();
 7002            return;
 7003        }
 7004
 7005        let text_layout_details = &self.text_layout_details(cx);
 7006
 7007        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7008            let line_mode = s.line_mode;
 7009            s.move_with(|map, selection| {
 7010                if !selection.is_empty() && !line_mode {
 7011                    selection.goal = SelectionGoal::None;
 7012                }
 7013                let (cursor, goal) = movement::up_by_rows(
 7014                    map,
 7015                    selection.start,
 7016                    action.lines,
 7017                    selection.goal,
 7018                    false,
 7019                    text_layout_details,
 7020                );
 7021                selection.collapse_to(cursor, goal);
 7022            });
 7023        })
 7024    }
 7025
 7026    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7027        if self.take_rename(true, cx).is_some() {
 7028            return;
 7029        }
 7030
 7031        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7032            cx.propagate();
 7033            return;
 7034        }
 7035
 7036        let text_layout_details = &self.text_layout_details(cx);
 7037
 7038        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7039            let line_mode = s.line_mode;
 7040            s.move_with(|map, selection| {
 7041                if !selection.is_empty() && !line_mode {
 7042                    selection.goal = SelectionGoal::None;
 7043                }
 7044                let (cursor, goal) = movement::down_by_rows(
 7045                    map,
 7046                    selection.start,
 7047                    action.lines,
 7048                    selection.goal,
 7049                    false,
 7050                    text_layout_details,
 7051                );
 7052                selection.collapse_to(cursor, goal);
 7053            });
 7054        })
 7055    }
 7056
 7057    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7058        let text_layout_details = &self.text_layout_details(cx);
 7059        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7060            s.move_heads_with(|map, head, goal| {
 7061                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7062            })
 7063        })
 7064    }
 7065
 7066    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7067        let text_layout_details = &self.text_layout_details(cx);
 7068        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7069            s.move_heads_with(|map, head, goal| {
 7070                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7071            })
 7072        })
 7073    }
 7074
 7075    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7076        let Some(row_count) = self.visible_row_count() else {
 7077            return;
 7078        };
 7079
 7080        let text_layout_details = &self.text_layout_details(cx);
 7081
 7082        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7083            s.move_heads_with(|map, head, goal| {
 7084                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7085            })
 7086        })
 7087    }
 7088
 7089    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7090        if self.take_rename(true, cx).is_some() {
 7091            return;
 7092        }
 7093
 7094        if self
 7095            .context_menu
 7096            .write()
 7097            .as_mut()
 7098            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7099            .unwrap_or(false)
 7100        {
 7101            return;
 7102        }
 7103
 7104        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7105            cx.propagate();
 7106            return;
 7107        }
 7108
 7109        let Some(row_count) = self.visible_row_count() else {
 7110            return;
 7111        };
 7112
 7113        let autoscroll = if action.center_cursor {
 7114            Autoscroll::center()
 7115        } else {
 7116            Autoscroll::fit()
 7117        };
 7118
 7119        let text_layout_details = &self.text_layout_details(cx);
 7120
 7121        self.change_selections(Some(autoscroll), cx, |s| {
 7122            let line_mode = s.line_mode;
 7123            s.move_with(|map, selection| {
 7124                if !selection.is_empty() && !line_mode {
 7125                    selection.goal = SelectionGoal::None;
 7126                }
 7127                let (cursor, goal) = movement::up_by_rows(
 7128                    map,
 7129                    selection.end,
 7130                    row_count,
 7131                    selection.goal,
 7132                    false,
 7133                    text_layout_details,
 7134                );
 7135                selection.collapse_to(cursor, goal);
 7136            });
 7137        });
 7138    }
 7139
 7140    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7141        let text_layout_details = &self.text_layout_details(cx);
 7142        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7143            s.move_heads_with(|map, head, goal| {
 7144                movement::up(map, head, goal, false, text_layout_details)
 7145            })
 7146        })
 7147    }
 7148
 7149    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7150        self.take_rename(true, cx);
 7151
 7152        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7153            cx.propagate();
 7154            return;
 7155        }
 7156
 7157        let text_layout_details = &self.text_layout_details(cx);
 7158        let selection_count = self.selections.count();
 7159        let first_selection = self.selections.first_anchor();
 7160
 7161        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7162            let line_mode = s.line_mode;
 7163            s.move_with(|map, selection| {
 7164                if !selection.is_empty() && !line_mode {
 7165                    selection.goal = SelectionGoal::None;
 7166                }
 7167                let (cursor, goal) = movement::down(
 7168                    map,
 7169                    selection.end,
 7170                    selection.goal,
 7171                    false,
 7172                    text_layout_details,
 7173                );
 7174                selection.collapse_to(cursor, goal);
 7175            });
 7176        });
 7177
 7178        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7179        {
 7180            cx.propagate();
 7181        }
 7182    }
 7183
 7184    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7185        let Some(row_count) = self.visible_row_count() else {
 7186            return;
 7187        };
 7188
 7189        let text_layout_details = &self.text_layout_details(cx);
 7190
 7191        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7192            s.move_heads_with(|map, head, goal| {
 7193                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7194            })
 7195        })
 7196    }
 7197
 7198    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7199        if self.take_rename(true, cx).is_some() {
 7200            return;
 7201        }
 7202
 7203        if self
 7204            .context_menu
 7205            .write()
 7206            .as_mut()
 7207            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7208            .unwrap_or(false)
 7209        {
 7210            return;
 7211        }
 7212
 7213        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7214            cx.propagate();
 7215            return;
 7216        }
 7217
 7218        let Some(row_count) = self.visible_row_count() else {
 7219            return;
 7220        };
 7221
 7222        let autoscroll = if action.center_cursor {
 7223            Autoscroll::center()
 7224        } else {
 7225            Autoscroll::fit()
 7226        };
 7227
 7228        let text_layout_details = &self.text_layout_details(cx);
 7229        self.change_selections(Some(autoscroll), cx, |s| {
 7230            let line_mode = s.line_mode;
 7231            s.move_with(|map, selection| {
 7232                if !selection.is_empty() && !line_mode {
 7233                    selection.goal = SelectionGoal::None;
 7234                }
 7235                let (cursor, goal) = movement::down_by_rows(
 7236                    map,
 7237                    selection.end,
 7238                    row_count,
 7239                    selection.goal,
 7240                    false,
 7241                    text_layout_details,
 7242                );
 7243                selection.collapse_to(cursor, goal);
 7244            });
 7245        });
 7246    }
 7247
 7248    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7249        let text_layout_details = &self.text_layout_details(cx);
 7250        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7251            s.move_heads_with(|map, head, goal| {
 7252                movement::down(map, head, goal, false, text_layout_details)
 7253            })
 7254        });
 7255    }
 7256
 7257    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7258        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7259            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7260        }
 7261    }
 7262
 7263    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7264        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7265            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7266        }
 7267    }
 7268
 7269    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7270        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7271            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7272        }
 7273    }
 7274
 7275    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7276        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7277            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7278        }
 7279    }
 7280
 7281    pub fn move_to_previous_word_start(
 7282        &mut self,
 7283        _: &MoveToPreviousWordStart,
 7284        cx: &mut ViewContext<Self>,
 7285    ) {
 7286        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7287            s.move_cursors_with(|map, head, _| {
 7288                (
 7289                    movement::previous_word_start(map, head),
 7290                    SelectionGoal::None,
 7291                )
 7292            });
 7293        })
 7294    }
 7295
 7296    pub fn move_to_previous_subword_start(
 7297        &mut self,
 7298        _: &MoveToPreviousSubwordStart,
 7299        cx: &mut ViewContext<Self>,
 7300    ) {
 7301        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7302            s.move_cursors_with(|map, head, _| {
 7303                (
 7304                    movement::previous_subword_start(map, head),
 7305                    SelectionGoal::None,
 7306                )
 7307            });
 7308        })
 7309    }
 7310
 7311    pub fn select_to_previous_word_start(
 7312        &mut self,
 7313        _: &SelectToPreviousWordStart,
 7314        cx: &mut ViewContext<Self>,
 7315    ) {
 7316        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7317            s.move_heads_with(|map, head, _| {
 7318                (
 7319                    movement::previous_word_start(map, head),
 7320                    SelectionGoal::None,
 7321                )
 7322            });
 7323        })
 7324    }
 7325
 7326    pub fn select_to_previous_subword_start(
 7327        &mut self,
 7328        _: &SelectToPreviousSubwordStart,
 7329        cx: &mut ViewContext<Self>,
 7330    ) {
 7331        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7332            s.move_heads_with(|map, head, _| {
 7333                (
 7334                    movement::previous_subword_start(map, head),
 7335                    SelectionGoal::None,
 7336                )
 7337            });
 7338        })
 7339    }
 7340
 7341    pub fn delete_to_previous_word_start(
 7342        &mut self,
 7343        action: &DeleteToPreviousWordStart,
 7344        cx: &mut ViewContext<Self>,
 7345    ) {
 7346        self.transact(cx, |this, cx| {
 7347            this.select_autoclose_pair(cx);
 7348            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7349                let line_mode = s.line_mode;
 7350                s.move_with(|map, selection| {
 7351                    if selection.is_empty() && !line_mode {
 7352                        let cursor = if action.ignore_newlines {
 7353                            movement::previous_word_start(map, selection.head())
 7354                        } else {
 7355                            movement::previous_word_start_or_newline(map, selection.head())
 7356                        };
 7357                        selection.set_head(cursor, SelectionGoal::None);
 7358                    }
 7359                });
 7360            });
 7361            this.insert("", cx);
 7362        });
 7363    }
 7364
 7365    pub fn delete_to_previous_subword_start(
 7366        &mut self,
 7367        _: &DeleteToPreviousSubwordStart,
 7368        cx: &mut ViewContext<Self>,
 7369    ) {
 7370        self.transact(cx, |this, cx| {
 7371            this.select_autoclose_pair(cx);
 7372            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7373                let line_mode = s.line_mode;
 7374                s.move_with(|map, selection| {
 7375                    if selection.is_empty() && !line_mode {
 7376                        let cursor = movement::previous_subword_start(map, selection.head());
 7377                        selection.set_head(cursor, SelectionGoal::None);
 7378                    }
 7379                });
 7380            });
 7381            this.insert("", cx);
 7382        });
 7383    }
 7384
 7385    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            s.move_cursors_with(|map, head, _| {
 7388                (movement::next_word_end(map, head), SelectionGoal::None)
 7389            });
 7390        })
 7391    }
 7392
 7393    pub fn move_to_next_subword_end(
 7394        &mut self,
 7395        _: &MoveToNextSubwordEnd,
 7396        cx: &mut ViewContext<Self>,
 7397    ) {
 7398        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7399            s.move_cursors_with(|map, head, _| {
 7400                (movement::next_subword_end(map, head), SelectionGoal::None)
 7401            });
 7402        })
 7403    }
 7404
 7405    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7406        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7407            s.move_heads_with(|map, head, _| {
 7408                (movement::next_word_end(map, head), SelectionGoal::None)
 7409            });
 7410        })
 7411    }
 7412
 7413    pub fn select_to_next_subword_end(
 7414        &mut self,
 7415        _: &SelectToNextSubwordEnd,
 7416        cx: &mut ViewContext<Self>,
 7417    ) {
 7418        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7419            s.move_heads_with(|map, head, _| {
 7420                (movement::next_subword_end(map, head), SelectionGoal::None)
 7421            });
 7422        })
 7423    }
 7424
 7425    pub fn delete_to_next_word_end(
 7426        &mut self,
 7427        action: &DeleteToNextWordEnd,
 7428        cx: &mut ViewContext<Self>,
 7429    ) {
 7430        self.transact(cx, |this, cx| {
 7431            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7432                let line_mode = s.line_mode;
 7433                s.move_with(|map, selection| {
 7434                    if selection.is_empty() && !line_mode {
 7435                        let cursor = if action.ignore_newlines {
 7436                            movement::next_word_end(map, selection.head())
 7437                        } else {
 7438                            movement::next_word_end_or_newline(map, selection.head())
 7439                        };
 7440                        selection.set_head(cursor, SelectionGoal::None);
 7441                    }
 7442                });
 7443            });
 7444            this.insert("", cx);
 7445        });
 7446    }
 7447
 7448    pub fn delete_to_next_subword_end(
 7449        &mut self,
 7450        _: &DeleteToNextSubwordEnd,
 7451        cx: &mut ViewContext<Self>,
 7452    ) {
 7453        self.transact(cx, |this, cx| {
 7454            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7455                s.move_with(|map, selection| {
 7456                    if selection.is_empty() {
 7457                        let cursor = movement::next_subword_end(map, selection.head());
 7458                        selection.set_head(cursor, SelectionGoal::None);
 7459                    }
 7460                });
 7461            });
 7462            this.insert("", cx);
 7463        });
 7464    }
 7465
 7466    pub fn move_to_beginning_of_line(
 7467        &mut self,
 7468        action: &MoveToBeginningOfLine,
 7469        cx: &mut ViewContext<Self>,
 7470    ) {
 7471        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7472            s.move_cursors_with(|map, head, _| {
 7473                (
 7474                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7475                    SelectionGoal::None,
 7476                )
 7477            });
 7478        })
 7479    }
 7480
 7481    pub fn select_to_beginning_of_line(
 7482        &mut self,
 7483        action: &SelectToBeginningOfLine,
 7484        cx: &mut ViewContext<Self>,
 7485    ) {
 7486        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7487            s.move_heads_with(|map, head, _| {
 7488                (
 7489                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7490                    SelectionGoal::None,
 7491                )
 7492            });
 7493        });
 7494    }
 7495
 7496    pub fn delete_to_beginning_of_line(
 7497        &mut self,
 7498        _: &DeleteToBeginningOfLine,
 7499        cx: &mut ViewContext<Self>,
 7500    ) {
 7501        self.transact(cx, |this, cx| {
 7502            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7503                s.move_with(|_, selection| {
 7504                    selection.reversed = true;
 7505                });
 7506            });
 7507
 7508            this.select_to_beginning_of_line(
 7509                &SelectToBeginningOfLine {
 7510                    stop_at_soft_wraps: false,
 7511                },
 7512                cx,
 7513            );
 7514            this.backspace(&Backspace, cx);
 7515        });
 7516    }
 7517
 7518    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7519        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7520            s.move_cursors_with(|map, head, _| {
 7521                (
 7522                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7523                    SelectionGoal::None,
 7524                )
 7525            });
 7526        })
 7527    }
 7528
 7529    pub fn select_to_end_of_line(
 7530        &mut self,
 7531        action: &SelectToEndOfLine,
 7532        cx: &mut ViewContext<Self>,
 7533    ) {
 7534        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7535            s.move_heads_with(|map, head, _| {
 7536                (
 7537                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7538                    SelectionGoal::None,
 7539                )
 7540            });
 7541        })
 7542    }
 7543
 7544    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7545        self.transact(cx, |this, cx| {
 7546            this.select_to_end_of_line(
 7547                &SelectToEndOfLine {
 7548                    stop_at_soft_wraps: false,
 7549                },
 7550                cx,
 7551            );
 7552            this.delete(&Delete, cx);
 7553        });
 7554    }
 7555
 7556    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7557        self.transact(cx, |this, cx| {
 7558            this.select_to_end_of_line(
 7559                &SelectToEndOfLine {
 7560                    stop_at_soft_wraps: false,
 7561                },
 7562                cx,
 7563            );
 7564            this.cut(&Cut, cx);
 7565        });
 7566    }
 7567
 7568    pub fn move_to_start_of_paragraph(
 7569        &mut self,
 7570        _: &MoveToStartOfParagraph,
 7571        cx: &mut ViewContext<Self>,
 7572    ) {
 7573        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7574            cx.propagate();
 7575            return;
 7576        }
 7577
 7578        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579            s.move_with(|map, selection| {
 7580                selection.collapse_to(
 7581                    movement::start_of_paragraph(map, selection.head(), 1),
 7582                    SelectionGoal::None,
 7583                )
 7584            });
 7585        })
 7586    }
 7587
 7588    pub fn move_to_end_of_paragraph(
 7589        &mut self,
 7590        _: &MoveToEndOfParagraph,
 7591        cx: &mut ViewContext<Self>,
 7592    ) {
 7593        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7594            cx.propagate();
 7595            return;
 7596        }
 7597
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.move_with(|map, selection| {
 7600                selection.collapse_to(
 7601                    movement::end_of_paragraph(map, selection.head(), 1),
 7602                    SelectionGoal::None,
 7603                )
 7604            });
 7605        })
 7606    }
 7607
 7608    pub fn select_to_start_of_paragraph(
 7609        &mut self,
 7610        _: &SelectToStartOfParagraph,
 7611        cx: &mut ViewContext<Self>,
 7612    ) {
 7613        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7614            cx.propagate();
 7615            return;
 7616        }
 7617
 7618        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619            s.move_heads_with(|map, head, _| {
 7620                (
 7621                    movement::start_of_paragraph(map, head, 1),
 7622                    SelectionGoal::None,
 7623                )
 7624            });
 7625        })
 7626    }
 7627
 7628    pub fn select_to_end_of_paragraph(
 7629        &mut self,
 7630        _: &SelectToEndOfParagraph,
 7631        cx: &mut ViewContext<Self>,
 7632    ) {
 7633        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7634            cx.propagate();
 7635            return;
 7636        }
 7637
 7638        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7639            s.move_heads_with(|map, head, _| {
 7640                (
 7641                    movement::end_of_paragraph(map, head, 1),
 7642                    SelectionGoal::None,
 7643                )
 7644            });
 7645        })
 7646    }
 7647
 7648    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7649        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7650            cx.propagate();
 7651            return;
 7652        }
 7653
 7654        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7655            s.select_ranges(vec![0..0]);
 7656        });
 7657    }
 7658
 7659    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7660        let mut selection = self.selections.last::<Point>(cx);
 7661        selection.set_head(Point::zero(), SelectionGoal::None);
 7662
 7663        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7664            s.select(vec![selection]);
 7665        });
 7666    }
 7667
 7668    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7669        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7670            cx.propagate();
 7671            return;
 7672        }
 7673
 7674        let cursor = self.buffer.read(cx).read(cx).len();
 7675        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7676            s.select_ranges(vec![cursor..cursor])
 7677        });
 7678    }
 7679
 7680    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7681        self.nav_history = nav_history;
 7682    }
 7683
 7684    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7685        self.nav_history.as_ref()
 7686    }
 7687
 7688    fn push_to_nav_history(
 7689        &mut self,
 7690        cursor_anchor: Anchor,
 7691        new_position: Option<Point>,
 7692        cx: &mut ViewContext<Self>,
 7693    ) {
 7694        if let Some(nav_history) = self.nav_history.as_mut() {
 7695            let buffer = self.buffer.read(cx).read(cx);
 7696            let cursor_position = cursor_anchor.to_point(&buffer);
 7697            let scroll_state = self.scroll_manager.anchor();
 7698            let scroll_top_row = scroll_state.top_row(&buffer);
 7699            drop(buffer);
 7700
 7701            if let Some(new_position) = new_position {
 7702                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7703                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7704                    return;
 7705                }
 7706            }
 7707
 7708            nav_history.push(
 7709                Some(NavigationData {
 7710                    cursor_anchor,
 7711                    cursor_position,
 7712                    scroll_anchor: scroll_state,
 7713                    scroll_top_row,
 7714                }),
 7715                cx,
 7716            );
 7717        }
 7718    }
 7719
 7720    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7721        let buffer = self.buffer.read(cx).snapshot(cx);
 7722        let mut selection = self.selections.first::<usize>(cx);
 7723        selection.set_head(buffer.len(), SelectionGoal::None);
 7724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7725            s.select(vec![selection]);
 7726        });
 7727    }
 7728
 7729    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7730        let end = self.buffer.read(cx).read(cx).len();
 7731        self.change_selections(None, cx, |s| {
 7732            s.select_ranges(vec![0..end]);
 7733        });
 7734    }
 7735
 7736    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7737        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7738        let mut selections = self.selections.all::<Point>(cx);
 7739        let max_point = display_map.buffer_snapshot.max_point();
 7740        for selection in &mut selections {
 7741            let rows = selection.spanned_rows(true, &display_map);
 7742            selection.start = Point::new(rows.start.0, 0);
 7743            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7744            selection.reversed = false;
 7745        }
 7746        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7747            s.select(selections);
 7748        });
 7749    }
 7750
 7751    pub fn split_selection_into_lines(
 7752        &mut self,
 7753        _: &SplitSelectionIntoLines,
 7754        cx: &mut ViewContext<Self>,
 7755    ) {
 7756        let mut to_unfold = Vec::new();
 7757        let mut new_selection_ranges = Vec::new();
 7758        {
 7759            let selections = self.selections.all::<Point>(cx);
 7760            let buffer = self.buffer.read(cx).read(cx);
 7761            for selection in selections {
 7762                for row in selection.start.row..selection.end.row {
 7763                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7764                    new_selection_ranges.push(cursor..cursor);
 7765                }
 7766                new_selection_ranges.push(selection.end..selection.end);
 7767                to_unfold.push(selection.start..selection.end);
 7768            }
 7769        }
 7770        self.unfold_ranges(&to_unfold, true, true, cx);
 7771        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7772            s.select_ranges(new_selection_ranges);
 7773        });
 7774    }
 7775
 7776    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7777        self.add_selection(true, cx);
 7778    }
 7779
 7780    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7781        self.add_selection(false, cx);
 7782    }
 7783
 7784    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7785        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7786        let mut selections = self.selections.all::<Point>(cx);
 7787        let text_layout_details = self.text_layout_details(cx);
 7788        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7789            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7790            let range = oldest_selection.display_range(&display_map).sorted();
 7791
 7792            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7793            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7794            let positions = start_x.min(end_x)..start_x.max(end_x);
 7795
 7796            selections.clear();
 7797            let mut stack = Vec::new();
 7798            for row in range.start.row().0..=range.end.row().0 {
 7799                if let Some(selection) = self.selections.build_columnar_selection(
 7800                    &display_map,
 7801                    DisplayRow(row),
 7802                    &positions,
 7803                    oldest_selection.reversed,
 7804                    &text_layout_details,
 7805                ) {
 7806                    stack.push(selection.id);
 7807                    selections.push(selection);
 7808                }
 7809            }
 7810
 7811            if above {
 7812                stack.reverse();
 7813            }
 7814
 7815            AddSelectionsState { above, stack }
 7816        });
 7817
 7818        let last_added_selection = *state.stack.last().unwrap();
 7819        let mut new_selections = Vec::new();
 7820        if above == state.above {
 7821            let end_row = if above {
 7822                DisplayRow(0)
 7823            } else {
 7824                display_map.max_point().row()
 7825            };
 7826
 7827            'outer: for selection in selections {
 7828                if selection.id == last_added_selection {
 7829                    let range = selection.display_range(&display_map).sorted();
 7830                    debug_assert_eq!(range.start.row(), range.end.row());
 7831                    let mut row = range.start.row();
 7832                    let positions =
 7833                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7834                            px(start)..px(end)
 7835                        } else {
 7836                            let start_x =
 7837                                display_map.x_for_display_point(range.start, &text_layout_details);
 7838                            let end_x =
 7839                                display_map.x_for_display_point(range.end, &text_layout_details);
 7840                            start_x.min(end_x)..start_x.max(end_x)
 7841                        };
 7842
 7843                    while row != end_row {
 7844                        if above {
 7845                            row.0 -= 1;
 7846                        } else {
 7847                            row.0 += 1;
 7848                        }
 7849
 7850                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7851                            &display_map,
 7852                            row,
 7853                            &positions,
 7854                            selection.reversed,
 7855                            &text_layout_details,
 7856                        ) {
 7857                            state.stack.push(new_selection.id);
 7858                            if above {
 7859                                new_selections.push(new_selection);
 7860                                new_selections.push(selection);
 7861                            } else {
 7862                                new_selections.push(selection);
 7863                                new_selections.push(new_selection);
 7864                            }
 7865
 7866                            continue 'outer;
 7867                        }
 7868                    }
 7869                }
 7870
 7871                new_selections.push(selection);
 7872            }
 7873        } else {
 7874            new_selections = selections;
 7875            new_selections.retain(|s| s.id != last_added_selection);
 7876            state.stack.pop();
 7877        }
 7878
 7879        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7880            s.select(new_selections);
 7881        });
 7882        if state.stack.len() > 1 {
 7883            self.add_selections_state = Some(state);
 7884        }
 7885    }
 7886
 7887    pub fn select_next_match_internal(
 7888        &mut self,
 7889        display_map: &DisplaySnapshot,
 7890        replace_newest: bool,
 7891        autoscroll: Option<Autoscroll>,
 7892        cx: &mut ViewContext<Self>,
 7893    ) -> Result<()> {
 7894        fn select_next_match_ranges(
 7895            this: &mut Editor,
 7896            range: Range<usize>,
 7897            replace_newest: bool,
 7898            auto_scroll: Option<Autoscroll>,
 7899            cx: &mut ViewContext<Editor>,
 7900        ) {
 7901            this.unfold_ranges(&[range.clone()], false, true, cx);
 7902            this.change_selections(auto_scroll, cx, |s| {
 7903                if replace_newest {
 7904                    s.delete(s.newest_anchor().id);
 7905                }
 7906                s.insert_range(range.clone());
 7907            });
 7908        }
 7909
 7910        let buffer = &display_map.buffer_snapshot;
 7911        let mut selections = self.selections.all::<usize>(cx);
 7912        if let Some(mut select_next_state) = self.select_next_state.take() {
 7913            let query = &select_next_state.query;
 7914            if !select_next_state.done {
 7915                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7916                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7917                let mut next_selected_range = None;
 7918
 7919                let bytes_after_last_selection =
 7920                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7921                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7922                let query_matches = query
 7923                    .stream_find_iter(bytes_after_last_selection)
 7924                    .map(|result| (last_selection.end, result))
 7925                    .chain(
 7926                        query
 7927                            .stream_find_iter(bytes_before_first_selection)
 7928                            .map(|result| (0, result)),
 7929                    );
 7930
 7931                for (start_offset, query_match) in query_matches {
 7932                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7933                    let offset_range =
 7934                        start_offset + query_match.start()..start_offset + query_match.end();
 7935                    let display_range = offset_range.start.to_display_point(display_map)
 7936                        ..offset_range.end.to_display_point(display_map);
 7937
 7938                    if !select_next_state.wordwise
 7939                        || (!movement::is_inside_word(display_map, display_range.start)
 7940                            && !movement::is_inside_word(display_map, display_range.end))
 7941                    {
 7942                        // TODO: This is n^2, because we might check all the selections
 7943                        if !selections
 7944                            .iter()
 7945                            .any(|selection| selection.range().overlaps(&offset_range))
 7946                        {
 7947                            next_selected_range = Some(offset_range);
 7948                            break;
 7949                        }
 7950                    }
 7951                }
 7952
 7953                if let Some(next_selected_range) = next_selected_range {
 7954                    select_next_match_ranges(
 7955                        self,
 7956                        next_selected_range,
 7957                        replace_newest,
 7958                        autoscroll,
 7959                        cx,
 7960                    );
 7961                } else {
 7962                    select_next_state.done = true;
 7963                }
 7964            }
 7965
 7966            self.select_next_state = Some(select_next_state);
 7967        } else {
 7968            let mut only_carets = true;
 7969            let mut same_text_selected = true;
 7970            let mut selected_text = None;
 7971
 7972            let mut selections_iter = selections.iter().peekable();
 7973            while let Some(selection) = selections_iter.next() {
 7974                if selection.start != selection.end {
 7975                    only_carets = false;
 7976                }
 7977
 7978                if same_text_selected {
 7979                    if selected_text.is_none() {
 7980                        selected_text =
 7981                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7982                    }
 7983
 7984                    if let Some(next_selection) = selections_iter.peek() {
 7985                        if next_selection.range().len() == selection.range().len() {
 7986                            let next_selected_text = buffer
 7987                                .text_for_range(next_selection.range())
 7988                                .collect::<String>();
 7989                            if Some(next_selected_text) != selected_text {
 7990                                same_text_selected = false;
 7991                                selected_text = None;
 7992                            }
 7993                        } else {
 7994                            same_text_selected = false;
 7995                            selected_text = None;
 7996                        }
 7997                    }
 7998                }
 7999            }
 8000
 8001            if only_carets {
 8002                for selection in &mut selections {
 8003                    let word_range = movement::surrounding_word(
 8004                        display_map,
 8005                        selection.start.to_display_point(display_map),
 8006                    );
 8007                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8008                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8009                    selection.goal = SelectionGoal::None;
 8010                    selection.reversed = false;
 8011                    select_next_match_ranges(
 8012                        self,
 8013                        selection.start..selection.end,
 8014                        replace_newest,
 8015                        autoscroll,
 8016                        cx,
 8017                    );
 8018                }
 8019
 8020                if selections.len() == 1 {
 8021                    let selection = selections
 8022                        .last()
 8023                        .expect("ensured that there's only one selection");
 8024                    let query = buffer
 8025                        .text_for_range(selection.start..selection.end)
 8026                        .collect::<String>();
 8027                    let is_empty = query.is_empty();
 8028                    let select_state = SelectNextState {
 8029                        query: AhoCorasick::new(&[query])?,
 8030                        wordwise: true,
 8031                        done: is_empty,
 8032                    };
 8033                    self.select_next_state = Some(select_state);
 8034                } else {
 8035                    self.select_next_state = None;
 8036                }
 8037            } else if let Some(selected_text) = selected_text {
 8038                self.select_next_state = Some(SelectNextState {
 8039                    query: AhoCorasick::new(&[selected_text])?,
 8040                    wordwise: false,
 8041                    done: false,
 8042                });
 8043                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8044            }
 8045        }
 8046        Ok(())
 8047    }
 8048
 8049    pub fn select_all_matches(
 8050        &mut self,
 8051        _action: &SelectAllMatches,
 8052        cx: &mut ViewContext<Self>,
 8053    ) -> Result<()> {
 8054        self.push_to_selection_history();
 8055        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8056
 8057        self.select_next_match_internal(&display_map, false, None, cx)?;
 8058        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8059            return Ok(());
 8060        };
 8061        if select_next_state.done {
 8062            return Ok(());
 8063        }
 8064
 8065        let mut new_selections = self.selections.all::<usize>(cx);
 8066
 8067        let buffer = &display_map.buffer_snapshot;
 8068        let query_matches = select_next_state
 8069            .query
 8070            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8071
 8072        for query_match in query_matches {
 8073            let query_match = query_match.unwrap(); // can only fail due to I/O
 8074            let offset_range = query_match.start()..query_match.end();
 8075            let display_range = offset_range.start.to_display_point(&display_map)
 8076                ..offset_range.end.to_display_point(&display_map);
 8077
 8078            if !select_next_state.wordwise
 8079                || (!movement::is_inside_word(&display_map, display_range.start)
 8080                    && !movement::is_inside_word(&display_map, display_range.end))
 8081            {
 8082                self.selections.change_with(cx, |selections| {
 8083                    new_selections.push(Selection {
 8084                        id: selections.new_selection_id(),
 8085                        start: offset_range.start,
 8086                        end: offset_range.end,
 8087                        reversed: false,
 8088                        goal: SelectionGoal::None,
 8089                    });
 8090                });
 8091            }
 8092        }
 8093
 8094        new_selections.sort_by_key(|selection| selection.start);
 8095        let mut ix = 0;
 8096        while ix + 1 < new_selections.len() {
 8097            let current_selection = &new_selections[ix];
 8098            let next_selection = &new_selections[ix + 1];
 8099            if current_selection.range().overlaps(&next_selection.range()) {
 8100                if current_selection.id < next_selection.id {
 8101                    new_selections.remove(ix + 1);
 8102                } else {
 8103                    new_selections.remove(ix);
 8104                }
 8105            } else {
 8106                ix += 1;
 8107            }
 8108        }
 8109
 8110        select_next_state.done = true;
 8111        self.unfold_ranges(
 8112            &new_selections
 8113                .iter()
 8114                .map(|selection| selection.range())
 8115                .collect::<Vec<_>>(),
 8116            false,
 8117            false,
 8118            cx,
 8119        );
 8120        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8121            selections.select(new_selections)
 8122        });
 8123
 8124        Ok(())
 8125    }
 8126
 8127    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8128        self.push_to_selection_history();
 8129        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8130        self.select_next_match_internal(
 8131            &display_map,
 8132            action.replace_newest,
 8133            Some(Autoscroll::newest()),
 8134            cx,
 8135        )?;
 8136        Ok(())
 8137    }
 8138
 8139    pub fn select_previous(
 8140        &mut self,
 8141        action: &SelectPrevious,
 8142        cx: &mut ViewContext<Self>,
 8143    ) -> Result<()> {
 8144        self.push_to_selection_history();
 8145        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8146        let buffer = &display_map.buffer_snapshot;
 8147        let mut selections = self.selections.all::<usize>(cx);
 8148        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8149            let query = &select_prev_state.query;
 8150            if !select_prev_state.done {
 8151                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8152                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8153                let mut next_selected_range = None;
 8154                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8155                let bytes_before_last_selection =
 8156                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8157                let bytes_after_first_selection =
 8158                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8159                let query_matches = query
 8160                    .stream_find_iter(bytes_before_last_selection)
 8161                    .map(|result| (last_selection.start, result))
 8162                    .chain(
 8163                        query
 8164                            .stream_find_iter(bytes_after_first_selection)
 8165                            .map(|result| (buffer.len(), result)),
 8166                    );
 8167                for (end_offset, query_match) in query_matches {
 8168                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8169                    let offset_range =
 8170                        end_offset - query_match.end()..end_offset - query_match.start();
 8171                    let display_range = offset_range.start.to_display_point(&display_map)
 8172                        ..offset_range.end.to_display_point(&display_map);
 8173
 8174                    if !select_prev_state.wordwise
 8175                        || (!movement::is_inside_word(&display_map, display_range.start)
 8176                            && !movement::is_inside_word(&display_map, display_range.end))
 8177                    {
 8178                        next_selected_range = Some(offset_range);
 8179                        break;
 8180                    }
 8181                }
 8182
 8183                if let Some(next_selected_range) = next_selected_range {
 8184                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8185                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8186                        if action.replace_newest {
 8187                            s.delete(s.newest_anchor().id);
 8188                        }
 8189                        s.insert_range(next_selected_range);
 8190                    });
 8191                } else {
 8192                    select_prev_state.done = true;
 8193                }
 8194            }
 8195
 8196            self.select_prev_state = Some(select_prev_state);
 8197        } else {
 8198            let mut only_carets = true;
 8199            let mut same_text_selected = true;
 8200            let mut selected_text = None;
 8201
 8202            let mut selections_iter = selections.iter().peekable();
 8203            while let Some(selection) = selections_iter.next() {
 8204                if selection.start != selection.end {
 8205                    only_carets = false;
 8206                }
 8207
 8208                if same_text_selected {
 8209                    if selected_text.is_none() {
 8210                        selected_text =
 8211                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8212                    }
 8213
 8214                    if let Some(next_selection) = selections_iter.peek() {
 8215                        if next_selection.range().len() == selection.range().len() {
 8216                            let next_selected_text = buffer
 8217                                .text_for_range(next_selection.range())
 8218                                .collect::<String>();
 8219                            if Some(next_selected_text) != selected_text {
 8220                                same_text_selected = false;
 8221                                selected_text = None;
 8222                            }
 8223                        } else {
 8224                            same_text_selected = false;
 8225                            selected_text = None;
 8226                        }
 8227                    }
 8228                }
 8229            }
 8230
 8231            if only_carets {
 8232                for selection in &mut selections {
 8233                    let word_range = movement::surrounding_word(
 8234                        &display_map,
 8235                        selection.start.to_display_point(&display_map),
 8236                    );
 8237                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8238                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8239                    selection.goal = SelectionGoal::None;
 8240                    selection.reversed = false;
 8241                }
 8242                if selections.len() == 1 {
 8243                    let selection = selections
 8244                        .last()
 8245                        .expect("ensured that there's only one selection");
 8246                    let query = buffer
 8247                        .text_for_range(selection.start..selection.end)
 8248                        .collect::<String>();
 8249                    let is_empty = query.is_empty();
 8250                    let select_state = SelectNextState {
 8251                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8252                        wordwise: true,
 8253                        done: is_empty,
 8254                    };
 8255                    self.select_prev_state = Some(select_state);
 8256                } else {
 8257                    self.select_prev_state = None;
 8258                }
 8259
 8260                self.unfold_ranges(
 8261                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8262                    false,
 8263                    true,
 8264                    cx,
 8265                );
 8266                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8267                    s.select(selections);
 8268                });
 8269            } else if let Some(selected_text) = selected_text {
 8270                self.select_prev_state = Some(SelectNextState {
 8271                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8272                    wordwise: false,
 8273                    done: false,
 8274                });
 8275                self.select_previous(action, cx)?;
 8276            }
 8277        }
 8278        Ok(())
 8279    }
 8280
 8281    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8282        if self.read_only(cx) {
 8283            return;
 8284        }
 8285        let text_layout_details = &self.text_layout_details(cx);
 8286        self.transact(cx, |this, cx| {
 8287            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8288            let mut edits = Vec::new();
 8289            let mut selection_edit_ranges = Vec::new();
 8290            let mut last_toggled_row = None;
 8291            let snapshot = this.buffer.read(cx).read(cx);
 8292            let empty_str: Arc<str> = Arc::default();
 8293            let mut suffixes_inserted = Vec::new();
 8294            let ignore_indent = action.ignore_indent;
 8295
 8296            fn comment_prefix_range(
 8297                snapshot: &MultiBufferSnapshot,
 8298                row: MultiBufferRow,
 8299                comment_prefix: &str,
 8300                comment_prefix_whitespace: &str,
 8301                ignore_indent: bool,
 8302            ) -> Range<Point> {
 8303                let indent_size = if ignore_indent {
 8304                    0
 8305                } else {
 8306                    snapshot.indent_size_for_line(row).len
 8307                };
 8308
 8309                let start = Point::new(row.0, indent_size);
 8310
 8311                let mut line_bytes = snapshot
 8312                    .bytes_in_range(start..snapshot.max_point())
 8313                    .flatten()
 8314                    .copied();
 8315
 8316                // If this line currently begins with the line comment prefix, then record
 8317                // the range containing the prefix.
 8318                if line_bytes
 8319                    .by_ref()
 8320                    .take(comment_prefix.len())
 8321                    .eq(comment_prefix.bytes())
 8322                {
 8323                    // Include any whitespace that matches the comment prefix.
 8324                    let matching_whitespace_len = line_bytes
 8325                        .zip(comment_prefix_whitespace.bytes())
 8326                        .take_while(|(a, b)| a == b)
 8327                        .count() as u32;
 8328                    let end = Point::new(
 8329                        start.row,
 8330                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8331                    );
 8332                    start..end
 8333                } else {
 8334                    start..start
 8335                }
 8336            }
 8337
 8338            fn comment_suffix_range(
 8339                snapshot: &MultiBufferSnapshot,
 8340                row: MultiBufferRow,
 8341                comment_suffix: &str,
 8342                comment_suffix_has_leading_space: bool,
 8343            ) -> Range<Point> {
 8344                let end = Point::new(row.0, snapshot.line_len(row));
 8345                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8346
 8347                let mut line_end_bytes = snapshot
 8348                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8349                    .flatten()
 8350                    .copied();
 8351
 8352                let leading_space_len = if suffix_start_column > 0
 8353                    && line_end_bytes.next() == Some(b' ')
 8354                    && comment_suffix_has_leading_space
 8355                {
 8356                    1
 8357                } else {
 8358                    0
 8359                };
 8360
 8361                // If this line currently begins with the line comment prefix, then record
 8362                // the range containing the prefix.
 8363                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8364                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8365                    start..end
 8366                } else {
 8367                    end..end
 8368                }
 8369            }
 8370
 8371            // TODO: Handle selections that cross excerpts
 8372            for selection in &mut selections {
 8373                let start_column = snapshot
 8374                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8375                    .len;
 8376                let language = if let Some(language) =
 8377                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8378                {
 8379                    language
 8380                } else {
 8381                    continue;
 8382                };
 8383
 8384                selection_edit_ranges.clear();
 8385
 8386                // If multiple selections contain a given row, avoid processing that
 8387                // row more than once.
 8388                let mut start_row = MultiBufferRow(selection.start.row);
 8389                if last_toggled_row == Some(start_row) {
 8390                    start_row = start_row.next_row();
 8391                }
 8392                let end_row =
 8393                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8394                        MultiBufferRow(selection.end.row - 1)
 8395                    } else {
 8396                        MultiBufferRow(selection.end.row)
 8397                    };
 8398                last_toggled_row = Some(end_row);
 8399
 8400                if start_row > end_row {
 8401                    continue;
 8402                }
 8403
 8404                // If the language has line comments, toggle those.
 8405                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8406
 8407                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8408                if ignore_indent {
 8409                    full_comment_prefixes = full_comment_prefixes
 8410                        .into_iter()
 8411                        .map(|s| Arc::from(s.trim_end()))
 8412                        .collect();
 8413                }
 8414
 8415                if !full_comment_prefixes.is_empty() {
 8416                    let first_prefix = full_comment_prefixes
 8417                        .first()
 8418                        .expect("prefixes is non-empty");
 8419                    let prefix_trimmed_lengths = full_comment_prefixes
 8420                        .iter()
 8421                        .map(|p| p.trim_end_matches(' ').len())
 8422                        .collect::<SmallVec<[usize; 4]>>();
 8423
 8424                    let mut all_selection_lines_are_comments = true;
 8425
 8426                    for row in start_row.0..=end_row.0 {
 8427                        let row = MultiBufferRow(row);
 8428                        if start_row < end_row && snapshot.is_line_blank(row) {
 8429                            continue;
 8430                        }
 8431
 8432                        let prefix_range = full_comment_prefixes
 8433                            .iter()
 8434                            .zip(prefix_trimmed_lengths.iter().copied())
 8435                            .map(|(prefix, trimmed_prefix_len)| {
 8436                                comment_prefix_range(
 8437                                    snapshot.deref(),
 8438                                    row,
 8439                                    &prefix[..trimmed_prefix_len],
 8440                                    &prefix[trimmed_prefix_len..],
 8441                                    ignore_indent,
 8442                                )
 8443                            })
 8444                            .max_by_key(|range| range.end.column - range.start.column)
 8445                            .expect("prefixes is non-empty");
 8446
 8447                        if prefix_range.is_empty() {
 8448                            all_selection_lines_are_comments = false;
 8449                        }
 8450
 8451                        selection_edit_ranges.push(prefix_range);
 8452                    }
 8453
 8454                    if all_selection_lines_are_comments {
 8455                        edits.extend(
 8456                            selection_edit_ranges
 8457                                .iter()
 8458                                .cloned()
 8459                                .map(|range| (range, empty_str.clone())),
 8460                        );
 8461                    } else {
 8462                        let min_column = selection_edit_ranges
 8463                            .iter()
 8464                            .map(|range| range.start.column)
 8465                            .min()
 8466                            .unwrap_or(0);
 8467                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8468                            let position = Point::new(range.start.row, min_column);
 8469                            (position..position, first_prefix.clone())
 8470                        }));
 8471                    }
 8472                } else if let Some((full_comment_prefix, comment_suffix)) =
 8473                    language.block_comment_delimiters()
 8474                {
 8475                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8476                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8477                    let prefix_range = comment_prefix_range(
 8478                        snapshot.deref(),
 8479                        start_row,
 8480                        comment_prefix,
 8481                        comment_prefix_whitespace,
 8482                        ignore_indent,
 8483                    );
 8484                    let suffix_range = comment_suffix_range(
 8485                        snapshot.deref(),
 8486                        end_row,
 8487                        comment_suffix.trim_start_matches(' '),
 8488                        comment_suffix.starts_with(' '),
 8489                    );
 8490
 8491                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8492                        edits.push((
 8493                            prefix_range.start..prefix_range.start,
 8494                            full_comment_prefix.clone(),
 8495                        ));
 8496                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8497                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8498                    } else {
 8499                        edits.push((prefix_range, empty_str.clone()));
 8500                        edits.push((suffix_range, empty_str.clone()));
 8501                    }
 8502                } else {
 8503                    continue;
 8504                }
 8505            }
 8506
 8507            drop(snapshot);
 8508            this.buffer.update(cx, |buffer, cx| {
 8509                buffer.edit(edits, None, cx);
 8510            });
 8511
 8512            // Adjust selections so that they end before any comment suffixes that
 8513            // were inserted.
 8514            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8515            let mut selections = this.selections.all::<Point>(cx);
 8516            let snapshot = this.buffer.read(cx).read(cx);
 8517            for selection in &mut selections {
 8518                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8519                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8520                        Ordering::Less => {
 8521                            suffixes_inserted.next();
 8522                            continue;
 8523                        }
 8524                        Ordering::Greater => break,
 8525                        Ordering::Equal => {
 8526                            if selection.end.column == snapshot.line_len(row) {
 8527                                if selection.is_empty() {
 8528                                    selection.start.column -= suffix_len as u32;
 8529                                }
 8530                                selection.end.column -= suffix_len as u32;
 8531                            }
 8532                            break;
 8533                        }
 8534                    }
 8535                }
 8536            }
 8537
 8538            drop(snapshot);
 8539            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8540
 8541            let selections = this.selections.all::<Point>(cx);
 8542            let selections_on_single_row = selections.windows(2).all(|selections| {
 8543                selections[0].start.row == selections[1].start.row
 8544                    && selections[0].end.row == selections[1].end.row
 8545                    && selections[0].start.row == selections[0].end.row
 8546            });
 8547            let selections_selecting = selections
 8548                .iter()
 8549                .any(|selection| selection.start != selection.end);
 8550            let advance_downwards = action.advance_downwards
 8551                && selections_on_single_row
 8552                && !selections_selecting
 8553                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8554
 8555            if advance_downwards {
 8556                let snapshot = this.buffer.read(cx).snapshot(cx);
 8557
 8558                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8559                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8560                        let mut point = display_point.to_point(display_snapshot);
 8561                        point.row += 1;
 8562                        point = snapshot.clip_point(point, Bias::Left);
 8563                        let display_point = point.to_display_point(display_snapshot);
 8564                        let goal = SelectionGoal::HorizontalPosition(
 8565                            display_snapshot
 8566                                .x_for_display_point(display_point, text_layout_details)
 8567                                .into(),
 8568                        );
 8569                        (display_point, goal)
 8570                    })
 8571                });
 8572            }
 8573        });
 8574    }
 8575
 8576    pub fn select_enclosing_symbol(
 8577        &mut self,
 8578        _: &SelectEnclosingSymbol,
 8579        cx: &mut ViewContext<Self>,
 8580    ) {
 8581        let buffer = self.buffer.read(cx).snapshot(cx);
 8582        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8583
 8584        fn update_selection(
 8585            selection: &Selection<usize>,
 8586            buffer_snap: &MultiBufferSnapshot,
 8587        ) -> Option<Selection<usize>> {
 8588            let cursor = selection.head();
 8589            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8590            for symbol in symbols.iter().rev() {
 8591                let start = symbol.range.start.to_offset(buffer_snap);
 8592                let end = symbol.range.end.to_offset(buffer_snap);
 8593                let new_range = start..end;
 8594                if start < selection.start || end > selection.end {
 8595                    return Some(Selection {
 8596                        id: selection.id,
 8597                        start: new_range.start,
 8598                        end: new_range.end,
 8599                        goal: SelectionGoal::None,
 8600                        reversed: selection.reversed,
 8601                    });
 8602                }
 8603            }
 8604            None
 8605        }
 8606
 8607        let mut selected_larger_symbol = false;
 8608        let new_selections = old_selections
 8609            .iter()
 8610            .map(|selection| match update_selection(selection, &buffer) {
 8611                Some(new_selection) => {
 8612                    if new_selection.range() != selection.range() {
 8613                        selected_larger_symbol = true;
 8614                    }
 8615                    new_selection
 8616                }
 8617                None => selection.clone(),
 8618            })
 8619            .collect::<Vec<_>>();
 8620
 8621        if selected_larger_symbol {
 8622            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8623                s.select(new_selections);
 8624            });
 8625        }
 8626    }
 8627
 8628    pub fn select_larger_syntax_node(
 8629        &mut self,
 8630        _: &SelectLargerSyntaxNode,
 8631        cx: &mut ViewContext<Self>,
 8632    ) {
 8633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8634        let buffer = self.buffer.read(cx).snapshot(cx);
 8635        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8636
 8637        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8638        let mut selected_larger_node = false;
 8639        let new_selections = old_selections
 8640            .iter()
 8641            .map(|selection| {
 8642                let old_range = selection.start..selection.end;
 8643                let mut new_range = old_range.clone();
 8644                while let Some(containing_range) =
 8645                    buffer.range_for_syntax_ancestor(new_range.clone())
 8646                {
 8647                    new_range = containing_range;
 8648                    if !display_map.intersects_fold(new_range.start)
 8649                        && !display_map.intersects_fold(new_range.end)
 8650                    {
 8651                        break;
 8652                    }
 8653                }
 8654
 8655                selected_larger_node |= new_range != old_range;
 8656                Selection {
 8657                    id: selection.id,
 8658                    start: new_range.start,
 8659                    end: new_range.end,
 8660                    goal: SelectionGoal::None,
 8661                    reversed: selection.reversed,
 8662                }
 8663            })
 8664            .collect::<Vec<_>>();
 8665
 8666        if selected_larger_node {
 8667            stack.push(old_selections);
 8668            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8669                s.select(new_selections);
 8670            });
 8671        }
 8672        self.select_larger_syntax_node_stack = stack;
 8673    }
 8674
 8675    pub fn select_smaller_syntax_node(
 8676        &mut self,
 8677        _: &SelectSmallerSyntaxNode,
 8678        cx: &mut ViewContext<Self>,
 8679    ) {
 8680        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8681        if let Some(selections) = stack.pop() {
 8682            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8683                s.select(selections.to_vec());
 8684            });
 8685        }
 8686        self.select_larger_syntax_node_stack = stack;
 8687    }
 8688
 8689    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8690        if !EditorSettings::get_global(cx).gutter.runnables {
 8691            self.clear_tasks();
 8692            return Task::ready(());
 8693        }
 8694        let project = self.project.as_ref().map(Model::downgrade);
 8695        cx.spawn(|this, mut cx| async move {
 8696            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8697            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8698                return;
 8699            };
 8700            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8701                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8702            }) else {
 8703                return;
 8704            };
 8705
 8706            let hide_runnables = project
 8707                .update(&mut cx, |project, cx| {
 8708                    // Do not display any test indicators in non-dev server remote projects.
 8709                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8710                })
 8711                .unwrap_or(true);
 8712            if hide_runnables {
 8713                return;
 8714            }
 8715            let new_rows =
 8716                cx.background_executor()
 8717                    .spawn({
 8718                        let snapshot = display_snapshot.clone();
 8719                        async move {
 8720                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8721                        }
 8722                    })
 8723                    .await;
 8724            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8725
 8726            this.update(&mut cx, |this, _| {
 8727                this.clear_tasks();
 8728                for (key, value) in rows {
 8729                    this.insert_tasks(key, value);
 8730                }
 8731            })
 8732            .ok();
 8733        })
 8734    }
 8735    fn fetch_runnable_ranges(
 8736        snapshot: &DisplaySnapshot,
 8737        range: Range<Anchor>,
 8738    ) -> Vec<language::RunnableRange> {
 8739        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8740    }
 8741
 8742    fn runnable_rows(
 8743        project: Model<Project>,
 8744        snapshot: DisplaySnapshot,
 8745        runnable_ranges: Vec<RunnableRange>,
 8746        mut cx: AsyncWindowContext,
 8747    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8748        runnable_ranges
 8749            .into_iter()
 8750            .filter_map(|mut runnable| {
 8751                let tasks = cx
 8752                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8753                    .ok()?;
 8754                if tasks.is_empty() {
 8755                    return None;
 8756                }
 8757
 8758                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8759
 8760                let row = snapshot
 8761                    .buffer_snapshot
 8762                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8763                    .1
 8764                    .start
 8765                    .row;
 8766
 8767                let context_range =
 8768                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8769                Some((
 8770                    (runnable.buffer_id, row),
 8771                    RunnableTasks {
 8772                        templates: tasks,
 8773                        offset: MultiBufferOffset(runnable.run_range.start),
 8774                        context_range,
 8775                        column: point.column,
 8776                        extra_variables: runnable.extra_captures,
 8777                    },
 8778                ))
 8779            })
 8780            .collect()
 8781    }
 8782
 8783    fn templates_with_tags(
 8784        project: &Model<Project>,
 8785        runnable: &mut Runnable,
 8786        cx: &WindowContext<'_>,
 8787    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8788        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8789            let (worktree_id, file) = project
 8790                .buffer_for_id(runnable.buffer, cx)
 8791                .and_then(|buffer| buffer.read(cx).file())
 8792                .map(|file| (file.worktree_id(cx), file.clone()))
 8793                .unzip();
 8794
 8795            (
 8796                project.task_store().read(cx).task_inventory().cloned(),
 8797                worktree_id,
 8798                file,
 8799            )
 8800        });
 8801
 8802        let tags = mem::take(&mut runnable.tags);
 8803        let mut tags: Vec<_> = tags
 8804            .into_iter()
 8805            .flat_map(|tag| {
 8806                let tag = tag.0.clone();
 8807                inventory
 8808                    .as_ref()
 8809                    .into_iter()
 8810                    .flat_map(|inventory| {
 8811                        inventory.read(cx).list_tasks(
 8812                            file.clone(),
 8813                            Some(runnable.language.clone()),
 8814                            worktree_id,
 8815                            cx,
 8816                        )
 8817                    })
 8818                    .filter(move |(_, template)| {
 8819                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8820                    })
 8821            })
 8822            .sorted_by_key(|(kind, _)| kind.to_owned())
 8823            .collect();
 8824        if let Some((leading_tag_source, _)) = tags.first() {
 8825            // Strongest source wins; if we have worktree tag binding, prefer that to
 8826            // global and language bindings;
 8827            // if we have a global binding, prefer that to language binding.
 8828            let first_mismatch = tags
 8829                .iter()
 8830                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8831            if let Some(index) = first_mismatch {
 8832                tags.truncate(index);
 8833            }
 8834        }
 8835
 8836        tags
 8837    }
 8838
 8839    pub fn move_to_enclosing_bracket(
 8840        &mut self,
 8841        _: &MoveToEnclosingBracket,
 8842        cx: &mut ViewContext<Self>,
 8843    ) {
 8844        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8845            s.move_offsets_with(|snapshot, selection| {
 8846                let Some(enclosing_bracket_ranges) =
 8847                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8848                else {
 8849                    return;
 8850                };
 8851
 8852                let mut best_length = usize::MAX;
 8853                let mut best_inside = false;
 8854                let mut best_in_bracket_range = false;
 8855                let mut best_destination = None;
 8856                for (open, close) in enclosing_bracket_ranges {
 8857                    let close = close.to_inclusive();
 8858                    let length = close.end() - open.start;
 8859                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8860                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8861                        || close.contains(&selection.head());
 8862
 8863                    // If best is next to a bracket and current isn't, skip
 8864                    if !in_bracket_range && best_in_bracket_range {
 8865                        continue;
 8866                    }
 8867
 8868                    // Prefer smaller lengths unless best is inside and current isn't
 8869                    if length > best_length && (best_inside || !inside) {
 8870                        continue;
 8871                    }
 8872
 8873                    best_length = length;
 8874                    best_inside = inside;
 8875                    best_in_bracket_range = in_bracket_range;
 8876                    best_destination = Some(
 8877                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8878                            if inside {
 8879                                open.end
 8880                            } else {
 8881                                open.start
 8882                            }
 8883                        } else if inside {
 8884                            *close.start()
 8885                        } else {
 8886                            *close.end()
 8887                        },
 8888                    );
 8889                }
 8890
 8891                if let Some(destination) = best_destination {
 8892                    selection.collapse_to(destination, SelectionGoal::None);
 8893                }
 8894            })
 8895        });
 8896    }
 8897
 8898    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8899        self.end_selection(cx);
 8900        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8901        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8902            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8903            self.select_next_state = entry.select_next_state;
 8904            self.select_prev_state = entry.select_prev_state;
 8905            self.add_selections_state = entry.add_selections_state;
 8906            self.request_autoscroll(Autoscroll::newest(), cx);
 8907        }
 8908        self.selection_history.mode = SelectionHistoryMode::Normal;
 8909    }
 8910
 8911    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8912        self.end_selection(cx);
 8913        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8914        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8915            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8916            self.select_next_state = entry.select_next_state;
 8917            self.select_prev_state = entry.select_prev_state;
 8918            self.add_selections_state = entry.add_selections_state;
 8919            self.request_autoscroll(Autoscroll::newest(), cx);
 8920        }
 8921        self.selection_history.mode = SelectionHistoryMode::Normal;
 8922    }
 8923
 8924    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8925        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8926    }
 8927
 8928    pub fn expand_excerpts_down(
 8929        &mut self,
 8930        action: &ExpandExcerptsDown,
 8931        cx: &mut ViewContext<Self>,
 8932    ) {
 8933        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8934    }
 8935
 8936    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8937        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8938    }
 8939
 8940    pub fn expand_excerpts_for_direction(
 8941        &mut self,
 8942        lines: u32,
 8943        direction: ExpandExcerptDirection,
 8944        cx: &mut ViewContext<Self>,
 8945    ) {
 8946        let selections = self.selections.disjoint_anchors();
 8947
 8948        let lines = if lines == 0 {
 8949            EditorSettings::get_global(cx).expand_excerpt_lines
 8950        } else {
 8951            lines
 8952        };
 8953
 8954        self.buffer.update(cx, |buffer, cx| {
 8955            buffer.expand_excerpts(
 8956                selections
 8957                    .iter()
 8958                    .map(|selection| selection.head().excerpt_id)
 8959                    .dedup(),
 8960                lines,
 8961                direction,
 8962                cx,
 8963            )
 8964        })
 8965    }
 8966
 8967    pub fn expand_excerpt(
 8968        &mut self,
 8969        excerpt: ExcerptId,
 8970        direction: ExpandExcerptDirection,
 8971        cx: &mut ViewContext<Self>,
 8972    ) {
 8973        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8974        self.buffer.update(cx, |buffer, cx| {
 8975            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8976        })
 8977    }
 8978
 8979    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8980        self.go_to_diagnostic_impl(Direction::Next, cx)
 8981    }
 8982
 8983    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8984        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8985    }
 8986
 8987    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8988        let buffer = self.buffer.read(cx).snapshot(cx);
 8989        let selection = self.selections.newest::<usize>(cx);
 8990
 8991        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8992        if direction == Direction::Next {
 8993            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8994                let (group_id, jump_to) = popover.activation_info();
 8995                if self.activate_diagnostics(group_id, cx) {
 8996                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8997                        let mut new_selection = s.newest_anchor().clone();
 8998                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8999                        s.select_anchors(vec![new_selection.clone()]);
 9000                    });
 9001                }
 9002                return;
 9003            }
 9004        }
 9005
 9006        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9007            active_diagnostics
 9008                .primary_range
 9009                .to_offset(&buffer)
 9010                .to_inclusive()
 9011        });
 9012        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9013            if active_primary_range.contains(&selection.head()) {
 9014                *active_primary_range.start()
 9015            } else {
 9016                selection.head()
 9017            }
 9018        } else {
 9019            selection.head()
 9020        };
 9021        let snapshot = self.snapshot(cx);
 9022        loop {
 9023            let diagnostics = if direction == Direction::Prev {
 9024                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9025            } else {
 9026                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9027            }
 9028            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9029            let group = diagnostics
 9030                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9031                // be sorted in a stable way
 9032                // skip until we are at current active diagnostic, if it exists
 9033                .skip_while(|entry| {
 9034                    (match direction {
 9035                        Direction::Prev => entry.range.start >= search_start,
 9036                        Direction::Next => entry.range.start <= search_start,
 9037                    }) && self
 9038                        .active_diagnostics
 9039                        .as_ref()
 9040                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9041                })
 9042                .find_map(|entry| {
 9043                    if entry.diagnostic.is_primary
 9044                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9045                        && !entry.range.is_empty()
 9046                        // if we match with the active diagnostic, skip it
 9047                        && Some(entry.diagnostic.group_id)
 9048                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9049                    {
 9050                        Some((entry.range, entry.diagnostic.group_id))
 9051                    } else {
 9052                        None
 9053                    }
 9054                });
 9055
 9056            if let Some((primary_range, group_id)) = group {
 9057                if self.activate_diagnostics(group_id, cx) {
 9058                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9059                        s.select(vec![Selection {
 9060                            id: selection.id,
 9061                            start: primary_range.start,
 9062                            end: primary_range.start,
 9063                            reversed: false,
 9064                            goal: SelectionGoal::None,
 9065                        }]);
 9066                    });
 9067                }
 9068                break;
 9069            } else {
 9070                // Cycle around to the start of the buffer, potentially moving back to the start of
 9071                // the currently active diagnostic.
 9072                active_primary_range.take();
 9073                if direction == Direction::Prev {
 9074                    if search_start == buffer.len() {
 9075                        break;
 9076                    } else {
 9077                        search_start = buffer.len();
 9078                    }
 9079                } else if search_start == 0 {
 9080                    break;
 9081                } else {
 9082                    search_start = 0;
 9083                }
 9084            }
 9085        }
 9086    }
 9087
 9088    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9089        let snapshot = self.snapshot(cx);
 9090        let selection = self.selections.newest::<Point>(cx);
 9091        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9092    }
 9093
 9094    fn go_to_hunk_after_position(
 9095        &mut self,
 9096        snapshot: &EditorSnapshot,
 9097        position: Point,
 9098        cx: &mut ViewContext<'_, Editor>,
 9099    ) -> Option<MultiBufferDiffHunk> {
 9100        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9101            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9102                snapshot,
 9103                position,
 9104                ix > 0,
 9105                snapshot.diff_map.diff_hunks_in_range(
 9106                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9107                    &snapshot.buffer_snapshot,
 9108                ),
 9109                cx,
 9110            ) {
 9111                return Some(hunk);
 9112            }
 9113        }
 9114        None
 9115    }
 9116
 9117    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9118        let snapshot = self.snapshot(cx);
 9119        let selection = self.selections.newest::<Point>(cx);
 9120        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9121    }
 9122
 9123    fn go_to_hunk_before_position(
 9124        &mut self,
 9125        snapshot: &EditorSnapshot,
 9126        position: Point,
 9127        cx: &mut ViewContext<'_, Editor>,
 9128    ) -> Option<MultiBufferDiffHunk> {
 9129        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9130            .into_iter()
 9131            .enumerate()
 9132        {
 9133            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9134                snapshot,
 9135                position,
 9136                ix > 0,
 9137                snapshot
 9138                    .diff_map
 9139                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9140                cx,
 9141            ) {
 9142                return Some(hunk);
 9143            }
 9144        }
 9145        None
 9146    }
 9147
 9148    fn go_to_next_hunk_in_direction(
 9149        &mut self,
 9150        snapshot: &DisplaySnapshot,
 9151        initial_point: Point,
 9152        is_wrapped: bool,
 9153        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9154        cx: &mut ViewContext<Editor>,
 9155    ) -> Option<MultiBufferDiffHunk> {
 9156        let display_point = initial_point.to_display_point(snapshot);
 9157        let mut hunks = hunks
 9158            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9159            .filter(|(display_hunk, _)| {
 9160                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9161            })
 9162            .dedup();
 9163
 9164        if let Some((display_hunk, hunk)) = hunks.next() {
 9165            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9166                let row = display_hunk.start_display_row();
 9167                let point = DisplayPoint::new(row, 0);
 9168                s.select_display_ranges([point..point]);
 9169            });
 9170
 9171            Some(hunk)
 9172        } else {
 9173            None
 9174        }
 9175    }
 9176
 9177    pub fn go_to_definition(
 9178        &mut self,
 9179        _: &GoToDefinition,
 9180        cx: &mut ViewContext<Self>,
 9181    ) -> Task<Result<Navigated>> {
 9182        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9183        cx.spawn(|editor, mut cx| async move {
 9184            if definition.await? == Navigated::Yes {
 9185                return Ok(Navigated::Yes);
 9186            }
 9187            match editor.update(&mut cx, |editor, cx| {
 9188                editor.find_all_references(&FindAllReferences, cx)
 9189            })? {
 9190                Some(references) => references.await,
 9191                None => Ok(Navigated::No),
 9192            }
 9193        })
 9194    }
 9195
 9196    pub fn go_to_declaration(
 9197        &mut self,
 9198        _: &GoToDeclaration,
 9199        cx: &mut ViewContext<Self>,
 9200    ) -> Task<Result<Navigated>> {
 9201        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9202    }
 9203
 9204    pub fn go_to_declaration_split(
 9205        &mut self,
 9206        _: &GoToDeclaration,
 9207        cx: &mut ViewContext<Self>,
 9208    ) -> Task<Result<Navigated>> {
 9209        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9210    }
 9211
 9212    pub fn go_to_implementation(
 9213        &mut self,
 9214        _: &GoToImplementation,
 9215        cx: &mut ViewContext<Self>,
 9216    ) -> Task<Result<Navigated>> {
 9217        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9218    }
 9219
 9220    pub fn go_to_implementation_split(
 9221        &mut self,
 9222        _: &GoToImplementationSplit,
 9223        cx: &mut ViewContext<Self>,
 9224    ) -> Task<Result<Navigated>> {
 9225        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9226    }
 9227
 9228    pub fn go_to_type_definition(
 9229        &mut self,
 9230        _: &GoToTypeDefinition,
 9231        cx: &mut ViewContext<Self>,
 9232    ) -> Task<Result<Navigated>> {
 9233        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9234    }
 9235
 9236    pub fn go_to_definition_split(
 9237        &mut self,
 9238        _: &GoToDefinitionSplit,
 9239        cx: &mut ViewContext<Self>,
 9240    ) -> Task<Result<Navigated>> {
 9241        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9242    }
 9243
 9244    pub fn go_to_type_definition_split(
 9245        &mut self,
 9246        _: &GoToTypeDefinitionSplit,
 9247        cx: &mut ViewContext<Self>,
 9248    ) -> Task<Result<Navigated>> {
 9249        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9250    }
 9251
 9252    fn go_to_definition_of_kind(
 9253        &mut self,
 9254        kind: GotoDefinitionKind,
 9255        split: bool,
 9256        cx: &mut ViewContext<Self>,
 9257    ) -> Task<Result<Navigated>> {
 9258        let Some(provider) = self.semantics_provider.clone() else {
 9259            return Task::ready(Ok(Navigated::No));
 9260        };
 9261        let head = self.selections.newest::<usize>(cx).head();
 9262        let buffer = self.buffer.read(cx);
 9263        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9264            text_anchor
 9265        } else {
 9266            return Task::ready(Ok(Navigated::No));
 9267        };
 9268
 9269        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9270            return Task::ready(Ok(Navigated::No));
 9271        };
 9272
 9273        cx.spawn(|editor, mut cx| async move {
 9274            let definitions = definitions.await?;
 9275            let navigated = editor
 9276                .update(&mut cx, |editor, cx| {
 9277                    editor.navigate_to_hover_links(
 9278                        Some(kind),
 9279                        definitions
 9280                            .into_iter()
 9281                            .filter(|location| {
 9282                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9283                            })
 9284                            .map(HoverLink::Text)
 9285                            .collect::<Vec<_>>(),
 9286                        split,
 9287                        cx,
 9288                    )
 9289                })?
 9290                .await?;
 9291            anyhow::Ok(navigated)
 9292        })
 9293    }
 9294
 9295    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9296        let selection = self.selections.newest_anchor();
 9297        let head = selection.head();
 9298        let tail = selection.tail();
 9299
 9300        let Some((buffer, start_position)) =
 9301            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9302        else {
 9303            return;
 9304        };
 9305
 9306        let end_position = if head != tail {
 9307            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9308                return;
 9309            };
 9310            Some(pos)
 9311        } else {
 9312            None
 9313        };
 9314
 9315        let url_finder = cx.spawn(|editor, mut cx| async move {
 9316            let url = if let Some(end_pos) = end_position {
 9317                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9318            } else {
 9319                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9320            };
 9321
 9322            if let Some(url) = url {
 9323                editor.update(&mut cx, |_, cx| {
 9324                    cx.open_url(&url);
 9325                })
 9326            } else {
 9327                Ok(())
 9328            }
 9329        });
 9330
 9331        url_finder.detach();
 9332    }
 9333
 9334    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9335        let Some(workspace) = self.workspace() else {
 9336            return;
 9337        };
 9338
 9339        let position = self.selections.newest_anchor().head();
 9340
 9341        let Some((buffer, buffer_position)) =
 9342            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9343        else {
 9344            return;
 9345        };
 9346
 9347        let project = self.project.clone();
 9348
 9349        cx.spawn(|_, mut cx| async move {
 9350            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9351
 9352            if let Some((_, path)) = result {
 9353                workspace
 9354                    .update(&mut cx, |workspace, cx| {
 9355                        workspace.open_resolved_path(path, cx)
 9356                    })?
 9357                    .await?;
 9358            }
 9359            anyhow::Ok(())
 9360        })
 9361        .detach();
 9362    }
 9363
 9364    pub(crate) fn navigate_to_hover_links(
 9365        &mut self,
 9366        kind: Option<GotoDefinitionKind>,
 9367        mut definitions: Vec<HoverLink>,
 9368        split: bool,
 9369        cx: &mut ViewContext<Editor>,
 9370    ) -> Task<Result<Navigated>> {
 9371        // If there is one definition, just open it directly
 9372        if definitions.len() == 1 {
 9373            let definition = definitions.pop().unwrap();
 9374
 9375            enum TargetTaskResult {
 9376                Location(Option<Location>),
 9377                AlreadyNavigated,
 9378            }
 9379
 9380            let target_task = match definition {
 9381                HoverLink::Text(link) => {
 9382                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9383                }
 9384                HoverLink::InlayHint(lsp_location, server_id) => {
 9385                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9386                    cx.background_executor().spawn(async move {
 9387                        let location = computation.await?;
 9388                        Ok(TargetTaskResult::Location(location))
 9389                    })
 9390                }
 9391                HoverLink::Url(url) => {
 9392                    cx.open_url(&url);
 9393                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9394                }
 9395                HoverLink::File(path) => {
 9396                    if let Some(workspace) = self.workspace() {
 9397                        cx.spawn(|_, mut cx| async move {
 9398                            workspace
 9399                                .update(&mut cx, |workspace, cx| {
 9400                                    workspace.open_resolved_path(path, cx)
 9401                                })?
 9402                                .await
 9403                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9404                        })
 9405                    } else {
 9406                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9407                    }
 9408                }
 9409            };
 9410            cx.spawn(|editor, mut cx| async move {
 9411                let target = match target_task.await.context("target resolution task")? {
 9412                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9413                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9414                    TargetTaskResult::Location(Some(target)) => target,
 9415                };
 9416
 9417                editor.update(&mut cx, |editor, cx| {
 9418                    let Some(workspace) = editor.workspace() else {
 9419                        return Navigated::No;
 9420                    };
 9421                    let pane = workspace.read(cx).active_pane().clone();
 9422
 9423                    let range = target.range.to_offset(target.buffer.read(cx));
 9424                    let range = editor.range_for_match(&range);
 9425
 9426                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9427                        let buffer = target.buffer.read(cx);
 9428                        let range = check_multiline_range(buffer, range);
 9429                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9430                            s.select_ranges([range]);
 9431                        });
 9432                    } else {
 9433                        cx.window_context().defer(move |cx| {
 9434                            let target_editor: View<Self> =
 9435                                workspace.update(cx, |workspace, cx| {
 9436                                    let pane = if split {
 9437                                        workspace.adjacent_pane(cx)
 9438                                    } else {
 9439                                        workspace.active_pane().clone()
 9440                                    };
 9441
 9442                                    workspace.open_project_item(
 9443                                        pane,
 9444                                        target.buffer.clone(),
 9445                                        true,
 9446                                        true,
 9447                                        cx,
 9448                                    )
 9449                                });
 9450                            target_editor.update(cx, |target_editor, cx| {
 9451                                // When selecting a definition in a different buffer, disable the nav history
 9452                                // to avoid creating a history entry at the previous cursor location.
 9453                                pane.update(cx, |pane, _| pane.disable_history());
 9454                                let buffer = target.buffer.read(cx);
 9455                                let range = check_multiline_range(buffer, range);
 9456                                target_editor.change_selections(
 9457                                    Some(Autoscroll::focused()),
 9458                                    cx,
 9459                                    |s| {
 9460                                        s.select_ranges([range]);
 9461                                    },
 9462                                );
 9463                                pane.update(cx, |pane, _| pane.enable_history());
 9464                            });
 9465                        });
 9466                    }
 9467                    Navigated::Yes
 9468                })
 9469            })
 9470        } else if !definitions.is_empty() {
 9471            cx.spawn(|editor, mut cx| async move {
 9472                let (title, location_tasks, workspace) = editor
 9473                    .update(&mut cx, |editor, cx| {
 9474                        let tab_kind = match kind {
 9475                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9476                            _ => "Definitions",
 9477                        };
 9478                        let title = definitions
 9479                            .iter()
 9480                            .find_map(|definition| match definition {
 9481                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9482                                    let buffer = origin.buffer.read(cx);
 9483                                    format!(
 9484                                        "{} for {}",
 9485                                        tab_kind,
 9486                                        buffer
 9487                                            .text_for_range(origin.range.clone())
 9488                                            .collect::<String>()
 9489                                    )
 9490                                }),
 9491                                HoverLink::InlayHint(_, _) => None,
 9492                                HoverLink::Url(_) => None,
 9493                                HoverLink::File(_) => None,
 9494                            })
 9495                            .unwrap_or(tab_kind.to_string());
 9496                        let location_tasks = definitions
 9497                            .into_iter()
 9498                            .map(|definition| match definition {
 9499                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9500                                HoverLink::InlayHint(lsp_location, server_id) => {
 9501                                    editor.compute_target_location(lsp_location, server_id, cx)
 9502                                }
 9503                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9504                                HoverLink::File(_) => Task::ready(Ok(None)),
 9505                            })
 9506                            .collect::<Vec<_>>();
 9507                        (title, location_tasks, editor.workspace().clone())
 9508                    })
 9509                    .context("location tasks preparation")?;
 9510
 9511                let locations = future::join_all(location_tasks)
 9512                    .await
 9513                    .into_iter()
 9514                    .filter_map(|location| location.transpose())
 9515                    .collect::<Result<_>>()
 9516                    .context("location tasks")?;
 9517
 9518                let Some(workspace) = workspace else {
 9519                    return Ok(Navigated::No);
 9520                };
 9521                let opened = workspace
 9522                    .update(&mut cx, |workspace, cx| {
 9523                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9524                    })
 9525                    .ok();
 9526
 9527                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9528            })
 9529        } else {
 9530            Task::ready(Ok(Navigated::No))
 9531        }
 9532    }
 9533
 9534    fn compute_target_location(
 9535        &self,
 9536        lsp_location: lsp::Location,
 9537        server_id: LanguageServerId,
 9538        cx: &mut ViewContext<Self>,
 9539    ) -> Task<anyhow::Result<Option<Location>>> {
 9540        let Some(project) = self.project.clone() else {
 9541            return Task::Ready(Some(Ok(None)));
 9542        };
 9543
 9544        cx.spawn(move |editor, mut cx| async move {
 9545            let location_task = editor.update(&mut cx, |_, cx| {
 9546                project.update(cx, |project, cx| {
 9547                    let language_server_name = project
 9548                        .language_server_statuses(cx)
 9549                        .find(|(id, _)| server_id == *id)
 9550                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9551                    language_server_name.map(|language_server_name| {
 9552                        project.open_local_buffer_via_lsp(
 9553                            lsp_location.uri.clone(),
 9554                            server_id,
 9555                            language_server_name,
 9556                            cx,
 9557                        )
 9558                    })
 9559                })
 9560            })?;
 9561            let location = match location_task {
 9562                Some(task) => Some({
 9563                    let target_buffer_handle = task.await.context("open local buffer")?;
 9564                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9565                        let target_start = target_buffer
 9566                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9567                        let target_end = target_buffer
 9568                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9569                        target_buffer.anchor_after(target_start)
 9570                            ..target_buffer.anchor_before(target_end)
 9571                    })?;
 9572                    Location {
 9573                        buffer: target_buffer_handle,
 9574                        range,
 9575                    }
 9576                }),
 9577                None => None,
 9578            };
 9579            Ok(location)
 9580        })
 9581    }
 9582
 9583    pub fn find_all_references(
 9584        &mut self,
 9585        _: &FindAllReferences,
 9586        cx: &mut ViewContext<Self>,
 9587    ) -> Option<Task<Result<Navigated>>> {
 9588        let selection = self.selections.newest::<usize>(cx);
 9589        let multi_buffer = self.buffer.read(cx);
 9590        let head = selection.head();
 9591
 9592        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9593        let head_anchor = multi_buffer_snapshot.anchor_at(
 9594            head,
 9595            if head < selection.tail() {
 9596                Bias::Right
 9597            } else {
 9598                Bias::Left
 9599            },
 9600        );
 9601
 9602        match self
 9603            .find_all_references_task_sources
 9604            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9605        {
 9606            Ok(_) => {
 9607                log::info!(
 9608                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9609                );
 9610                return None;
 9611            }
 9612            Err(i) => {
 9613                self.find_all_references_task_sources.insert(i, head_anchor);
 9614            }
 9615        }
 9616
 9617        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9618        let workspace = self.workspace()?;
 9619        let project = workspace.read(cx).project().clone();
 9620        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9621        Some(cx.spawn(|editor, mut cx| async move {
 9622            let _cleanup = defer({
 9623                let mut cx = cx.clone();
 9624                move || {
 9625                    let _ = editor.update(&mut cx, |editor, _| {
 9626                        if let Ok(i) =
 9627                            editor
 9628                                .find_all_references_task_sources
 9629                                .binary_search_by(|anchor| {
 9630                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9631                                })
 9632                        {
 9633                            editor.find_all_references_task_sources.remove(i);
 9634                        }
 9635                    });
 9636                }
 9637            });
 9638
 9639            let locations = references.await?;
 9640            if locations.is_empty() {
 9641                return anyhow::Ok(Navigated::No);
 9642            }
 9643
 9644            workspace.update(&mut cx, |workspace, cx| {
 9645                let title = locations
 9646                    .first()
 9647                    .as_ref()
 9648                    .map(|location| {
 9649                        let buffer = location.buffer.read(cx);
 9650                        format!(
 9651                            "References to `{}`",
 9652                            buffer
 9653                                .text_for_range(location.range.clone())
 9654                                .collect::<String>()
 9655                        )
 9656                    })
 9657                    .unwrap();
 9658                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9659                Navigated::Yes
 9660            })
 9661        }))
 9662    }
 9663
 9664    /// Opens a multibuffer with the given project locations in it
 9665    pub fn open_locations_in_multibuffer(
 9666        workspace: &mut Workspace,
 9667        mut locations: Vec<Location>,
 9668        title: String,
 9669        split: bool,
 9670        cx: &mut ViewContext<Workspace>,
 9671    ) {
 9672        // If there are multiple definitions, open them in a multibuffer
 9673        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9674        let mut locations = locations.into_iter().peekable();
 9675        let mut ranges_to_highlight = Vec::new();
 9676        let capability = workspace.project().read(cx).capability();
 9677
 9678        let excerpt_buffer = cx.new_model(|cx| {
 9679            let mut multibuffer = MultiBuffer::new(capability);
 9680            while let Some(location) = locations.next() {
 9681                let buffer = location.buffer.read(cx);
 9682                let mut ranges_for_buffer = Vec::new();
 9683                let range = location.range.to_offset(buffer);
 9684                ranges_for_buffer.push(range.clone());
 9685
 9686                while let Some(next_location) = locations.peek() {
 9687                    if next_location.buffer == location.buffer {
 9688                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9689                        locations.next();
 9690                    } else {
 9691                        break;
 9692                    }
 9693                }
 9694
 9695                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9696                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9697                    location.buffer.clone(),
 9698                    ranges_for_buffer,
 9699                    DEFAULT_MULTIBUFFER_CONTEXT,
 9700                    cx,
 9701                ))
 9702            }
 9703
 9704            multibuffer.with_title(title)
 9705        });
 9706
 9707        let editor = cx.new_view(|cx| {
 9708            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9709        });
 9710        editor.update(cx, |editor, cx| {
 9711            if let Some(first_range) = ranges_to_highlight.first() {
 9712                editor.change_selections(None, cx, |selections| {
 9713                    selections.clear_disjoint();
 9714                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9715                });
 9716            }
 9717            editor.highlight_background::<Self>(
 9718                &ranges_to_highlight,
 9719                |theme| theme.editor_highlighted_line_background,
 9720                cx,
 9721            );
 9722            editor.register_buffers_with_language_servers(cx);
 9723        });
 9724
 9725        let item = Box::new(editor);
 9726        let item_id = item.item_id();
 9727
 9728        if split {
 9729            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9730        } else {
 9731            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9732                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9733                    pane.close_current_preview_item(cx)
 9734                } else {
 9735                    None
 9736                }
 9737            });
 9738            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9739        }
 9740        workspace.active_pane().update(cx, |pane, cx| {
 9741            pane.set_preview_item_id(Some(item_id), cx);
 9742        });
 9743    }
 9744
 9745    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9746        use language::ToOffset as _;
 9747
 9748        let provider = self.semantics_provider.clone()?;
 9749        let selection = self.selections.newest_anchor().clone();
 9750        let (cursor_buffer, cursor_buffer_position) = self
 9751            .buffer
 9752            .read(cx)
 9753            .text_anchor_for_position(selection.head(), cx)?;
 9754        let (tail_buffer, cursor_buffer_position_end) = self
 9755            .buffer
 9756            .read(cx)
 9757            .text_anchor_for_position(selection.tail(), cx)?;
 9758        if tail_buffer != cursor_buffer {
 9759            return None;
 9760        }
 9761
 9762        let snapshot = cursor_buffer.read(cx).snapshot();
 9763        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9764        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9765        let prepare_rename = provider
 9766            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9767            .unwrap_or_else(|| Task::ready(Ok(None)));
 9768        drop(snapshot);
 9769
 9770        Some(cx.spawn(|this, mut cx| async move {
 9771            let rename_range = if let Some(range) = prepare_rename.await? {
 9772                Some(range)
 9773            } else {
 9774                this.update(&mut cx, |this, cx| {
 9775                    let buffer = this.buffer.read(cx).snapshot(cx);
 9776                    let mut buffer_highlights = this
 9777                        .document_highlights_for_position(selection.head(), &buffer)
 9778                        .filter(|highlight| {
 9779                            highlight.start.excerpt_id == selection.head().excerpt_id
 9780                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9781                        });
 9782                    buffer_highlights
 9783                        .next()
 9784                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9785                })?
 9786            };
 9787            if let Some(rename_range) = rename_range {
 9788                this.update(&mut cx, |this, cx| {
 9789                    let snapshot = cursor_buffer.read(cx).snapshot();
 9790                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9791                    let cursor_offset_in_rename_range =
 9792                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9793                    let cursor_offset_in_rename_range_end =
 9794                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9795
 9796                    this.take_rename(false, cx);
 9797                    let buffer = this.buffer.read(cx).read(cx);
 9798                    let cursor_offset = selection.head().to_offset(&buffer);
 9799                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9800                    let rename_end = rename_start + rename_buffer_range.len();
 9801                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9802                    let mut old_highlight_id = None;
 9803                    let old_name: Arc<str> = buffer
 9804                        .chunks(rename_start..rename_end, true)
 9805                        .map(|chunk| {
 9806                            if old_highlight_id.is_none() {
 9807                                old_highlight_id = chunk.syntax_highlight_id;
 9808                            }
 9809                            chunk.text
 9810                        })
 9811                        .collect::<String>()
 9812                        .into();
 9813
 9814                    drop(buffer);
 9815
 9816                    // Position the selection in the rename editor so that it matches the current selection.
 9817                    this.show_local_selections = false;
 9818                    let rename_editor = cx.new_view(|cx| {
 9819                        let mut editor = Editor::single_line(cx);
 9820                        editor.buffer.update(cx, |buffer, cx| {
 9821                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9822                        });
 9823                        let rename_selection_range = match cursor_offset_in_rename_range
 9824                            .cmp(&cursor_offset_in_rename_range_end)
 9825                        {
 9826                            Ordering::Equal => {
 9827                                editor.select_all(&SelectAll, cx);
 9828                                return editor;
 9829                            }
 9830                            Ordering::Less => {
 9831                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9832                            }
 9833                            Ordering::Greater => {
 9834                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9835                            }
 9836                        };
 9837                        if rename_selection_range.end > old_name.len() {
 9838                            editor.select_all(&SelectAll, cx);
 9839                        } else {
 9840                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9841                                s.select_ranges([rename_selection_range]);
 9842                            });
 9843                        }
 9844                        editor
 9845                    });
 9846                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9847                        if e == &EditorEvent::Focused {
 9848                            cx.emit(EditorEvent::FocusedIn)
 9849                        }
 9850                    })
 9851                    .detach();
 9852
 9853                    let write_highlights =
 9854                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9855                    let read_highlights =
 9856                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9857                    let ranges = write_highlights
 9858                        .iter()
 9859                        .flat_map(|(_, ranges)| ranges.iter())
 9860                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9861                        .cloned()
 9862                        .collect();
 9863
 9864                    this.highlight_text::<Rename>(
 9865                        ranges,
 9866                        HighlightStyle {
 9867                            fade_out: Some(0.6),
 9868                            ..Default::default()
 9869                        },
 9870                        cx,
 9871                    );
 9872                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9873                    cx.focus(&rename_focus_handle);
 9874                    let block_id = this.insert_blocks(
 9875                        [BlockProperties {
 9876                            style: BlockStyle::Flex,
 9877                            placement: BlockPlacement::Below(range.start),
 9878                            height: 1,
 9879                            render: Arc::new({
 9880                                let rename_editor = rename_editor.clone();
 9881                                move |cx: &mut BlockContext| {
 9882                                    let mut text_style = cx.editor_style.text.clone();
 9883                                    if let Some(highlight_style) = old_highlight_id
 9884                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9885                                    {
 9886                                        text_style = text_style.highlight(highlight_style);
 9887                                    }
 9888                                    div()
 9889                                        .block_mouse_down()
 9890                                        .pl(cx.anchor_x)
 9891                                        .child(EditorElement::new(
 9892                                            &rename_editor,
 9893                                            EditorStyle {
 9894                                                background: cx.theme().system().transparent,
 9895                                                local_player: cx.editor_style.local_player,
 9896                                                text: text_style,
 9897                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9898                                                syntax: cx.editor_style.syntax.clone(),
 9899                                                status: cx.editor_style.status.clone(),
 9900                                                inlay_hints_style: HighlightStyle {
 9901                                                    font_weight: Some(FontWeight::BOLD),
 9902                                                    ..make_inlay_hints_style(cx)
 9903                                                },
 9904                                                suggestions_style: HighlightStyle {
 9905                                                    color: Some(cx.theme().status().predictive),
 9906                                                    ..HighlightStyle::default()
 9907                                                },
 9908                                                ..EditorStyle::default()
 9909                                            },
 9910                                        ))
 9911                                        .into_any_element()
 9912                                }
 9913                            }),
 9914                            priority: 0,
 9915                        }],
 9916                        Some(Autoscroll::fit()),
 9917                        cx,
 9918                    )[0];
 9919                    this.pending_rename = Some(RenameState {
 9920                        range,
 9921                        old_name,
 9922                        editor: rename_editor,
 9923                        block_id,
 9924                    });
 9925                })?;
 9926            }
 9927
 9928            Ok(())
 9929        }))
 9930    }
 9931
 9932    pub fn confirm_rename(
 9933        &mut self,
 9934        _: &ConfirmRename,
 9935        cx: &mut ViewContext<Self>,
 9936    ) -> Option<Task<Result<()>>> {
 9937        let rename = self.take_rename(false, cx)?;
 9938        let workspace = self.workspace()?.downgrade();
 9939        let (buffer, start) = self
 9940            .buffer
 9941            .read(cx)
 9942            .text_anchor_for_position(rename.range.start, cx)?;
 9943        let (end_buffer, _) = self
 9944            .buffer
 9945            .read(cx)
 9946            .text_anchor_for_position(rename.range.end, cx)?;
 9947        if buffer != end_buffer {
 9948            return None;
 9949        }
 9950
 9951        let old_name = rename.old_name;
 9952        let new_name = rename.editor.read(cx).text(cx);
 9953
 9954        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9955            &buffer,
 9956            start,
 9957            new_name.clone(),
 9958            cx,
 9959        )?;
 9960
 9961        Some(cx.spawn(|editor, mut cx| async move {
 9962            let project_transaction = rename.await?;
 9963            Self::open_project_transaction(
 9964                &editor,
 9965                workspace,
 9966                project_transaction,
 9967                format!("Rename: {}{}", old_name, new_name),
 9968                cx.clone(),
 9969            )
 9970            .await?;
 9971
 9972            editor.update(&mut cx, |editor, cx| {
 9973                editor.refresh_document_highlights(cx);
 9974            })?;
 9975            Ok(())
 9976        }))
 9977    }
 9978
 9979    fn take_rename(
 9980        &mut self,
 9981        moving_cursor: bool,
 9982        cx: &mut ViewContext<Self>,
 9983    ) -> Option<RenameState> {
 9984        let rename = self.pending_rename.take()?;
 9985        if rename.editor.focus_handle(cx).is_focused(cx) {
 9986            cx.focus(&self.focus_handle);
 9987        }
 9988
 9989        self.remove_blocks(
 9990            [rename.block_id].into_iter().collect(),
 9991            Some(Autoscroll::fit()),
 9992            cx,
 9993        );
 9994        self.clear_highlights::<Rename>(cx);
 9995        self.show_local_selections = true;
 9996
 9997        if moving_cursor {
 9998            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
 9999                editor.selections.newest::<usize>(cx).head()
10000            });
10001
10002            // Update the selection to match the position of the selection inside
10003            // the rename editor.
10004            let snapshot = self.buffer.read(cx).read(cx);
10005            let rename_range = rename.range.to_offset(&snapshot);
10006            let cursor_in_editor = snapshot
10007                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10008                .min(rename_range.end);
10009            drop(snapshot);
10010
10011            self.change_selections(None, cx, |s| {
10012                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10013            });
10014        } else {
10015            self.refresh_document_highlights(cx);
10016        }
10017
10018        Some(rename)
10019    }
10020
10021    pub fn pending_rename(&self) -> Option<&RenameState> {
10022        self.pending_rename.as_ref()
10023    }
10024
10025    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10026        let project = match &self.project {
10027            Some(project) => project.clone(),
10028            None => return None,
10029        };
10030
10031        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10032    }
10033
10034    fn format_selections(
10035        &mut self,
10036        _: &FormatSelections,
10037        cx: &mut ViewContext<Self>,
10038    ) -> Option<Task<Result<()>>> {
10039        let project = match &self.project {
10040            Some(project) => project.clone(),
10041            None => return None,
10042        };
10043
10044        let selections = self
10045            .selections
10046            .all_adjusted(cx)
10047            .into_iter()
10048            .filter(|s| !s.is_empty())
10049            .collect_vec();
10050
10051        Some(self.perform_format(
10052            project,
10053            FormatTrigger::Manual,
10054            FormatTarget::Ranges(selections),
10055            cx,
10056        ))
10057    }
10058
10059    fn perform_format(
10060        &mut self,
10061        project: Model<Project>,
10062        trigger: FormatTrigger,
10063        target: FormatTarget,
10064        cx: &mut ViewContext<Self>,
10065    ) -> Task<Result<()>> {
10066        let buffer = self.buffer().clone();
10067        let mut buffers = buffer.read(cx).all_buffers();
10068        if trigger == FormatTrigger::Save {
10069            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10070        }
10071
10072        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10073        let format = project.update(cx, |project, cx| {
10074            project.format(buffers, true, trigger, target, cx)
10075        });
10076
10077        cx.spawn(|_, mut cx| async move {
10078            let transaction = futures::select_biased! {
10079                () = timeout => {
10080                    log::warn!("timed out waiting for formatting");
10081                    None
10082                }
10083                transaction = format.log_err().fuse() => transaction,
10084            };
10085
10086            buffer
10087                .update(&mut cx, |buffer, cx| {
10088                    if let Some(transaction) = transaction {
10089                        if !buffer.is_singleton() {
10090                            buffer.push_transaction(&transaction.0, cx);
10091                        }
10092                    }
10093
10094                    cx.notify();
10095                })
10096                .ok();
10097
10098            Ok(())
10099        })
10100    }
10101
10102    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10103        if let Some(project) = self.project.clone() {
10104            self.buffer.update(cx, |multi_buffer, cx| {
10105                project.update(cx, |project, cx| {
10106                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10107                });
10108            })
10109        }
10110    }
10111
10112    fn cancel_language_server_work(
10113        &mut self,
10114        _: &actions::CancelLanguageServerWork,
10115        cx: &mut ViewContext<Self>,
10116    ) {
10117        if let Some(project) = self.project.clone() {
10118            self.buffer.update(cx, |multi_buffer, cx| {
10119                project.update(cx, |project, cx| {
10120                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10121                });
10122            })
10123        }
10124    }
10125
10126    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10127        cx.show_character_palette();
10128    }
10129
10130    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10131        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10132            let buffer = self.buffer.read(cx).snapshot(cx);
10133            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10134            let is_valid = buffer
10135                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10136                .any(|entry| {
10137                    entry.diagnostic.is_primary
10138                        && !entry.range.is_empty()
10139                        && entry.range.start == primary_range_start
10140                        && entry.diagnostic.message == active_diagnostics.primary_message
10141                });
10142
10143            if is_valid != active_diagnostics.is_valid {
10144                active_diagnostics.is_valid = is_valid;
10145                let mut new_styles = HashMap::default();
10146                for (block_id, diagnostic) in &active_diagnostics.blocks {
10147                    new_styles.insert(
10148                        *block_id,
10149                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10150                    );
10151                }
10152                self.display_map.update(cx, |display_map, _cx| {
10153                    display_map.replace_blocks(new_styles)
10154                });
10155            }
10156        }
10157    }
10158
10159    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10160        self.dismiss_diagnostics(cx);
10161        let snapshot = self.snapshot(cx);
10162        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10163            let buffer = self.buffer.read(cx).snapshot(cx);
10164
10165            let mut primary_range = None;
10166            let mut primary_message = None;
10167            let mut group_end = Point::zero();
10168            let diagnostic_group = buffer
10169                .diagnostic_group::<MultiBufferPoint>(group_id)
10170                .filter_map(|entry| {
10171                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10172                        && (entry.range.start.row == entry.range.end.row
10173                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10174                    {
10175                        return None;
10176                    }
10177                    if entry.range.end > group_end {
10178                        group_end = entry.range.end;
10179                    }
10180                    if entry.diagnostic.is_primary {
10181                        primary_range = Some(entry.range.clone());
10182                        primary_message = Some(entry.diagnostic.message.clone());
10183                    }
10184                    Some(entry)
10185                })
10186                .collect::<Vec<_>>();
10187            let primary_range = primary_range?;
10188            let primary_message = primary_message?;
10189            let primary_range =
10190                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10191
10192            let blocks = display_map
10193                .insert_blocks(
10194                    diagnostic_group.iter().map(|entry| {
10195                        let diagnostic = entry.diagnostic.clone();
10196                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10197                        BlockProperties {
10198                            style: BlockStyle::Fixed,
10199                            placement: BlockPlacement::Below(
10200                                buffer.anchor_after(entry.range.start),
10201                            ),
10202                            height: message_height,
10203                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10204                            priority: 0,
10205                        }
10206                    }),
10207                    cx,
10208                )
10209                .into_iter()
10210                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10211                .collect();
10212
10213            Some(ActiveDiagnosticGroup {
10214                primary_range,
10215                primary_message,
10216                group_id,
10217                blocks,
10218                is_valid: true,
10219            })
10220        });
10221        self.active_diagnostics.is_some()
10222    }
10223
10224    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10225        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10226            self.display_map.update(cx, |display_map, cx| {
10227                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10228            });
10229            cx.notify();
10230        }
10231    }
10232
10233    pub fn set_selections_from_remote(
10234        &mut self,
10235        selections: Vec<Selection<Anchor>>,
10236        pending_selection: Option<Selection<Anchor>>,
10237        cx: &mut ViewContext<Self>,
10238    ) {
10239        let old_cursor_position = self.selections.newest_anchor().head();
10240        self.selections.change_with(cx, |s| {
10241            s.select_anchors(selections);
10242            if let Some(pending_selection) = pending_selection {
10243                s.set_pending(pending_selection, SelectMode::Character);
10244            } else {
10245                s.clear_pending();
10246            }
10247        });
10248        self.selections_did_change(false, &old_cursor_position, true, cx);
10249    }
10250
10251    fn push_to_selection_history(&mut self) {
10252        self.selection_history.push(SelectionHistoryEntry {
10253            selections: self.selections.disjoint_anchors(),
10254            select_next_state: self.select_next_state.clone(),
10255            select_prev_state: self.select_prev_state.clone(),
10256            add_selections_state: self.add_selections_state.clone(),
10257        });
10258    }
10259
10260    pub fn transact(
10261        &mut self,
10262        cx: &mut ViewContext<Self>,
10263        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10264    ) -> Option<TransactionId> {
10265        self.start_transaction_at(Instant::now(), cx);
10266        update(self, cx);
10267        self.end_transaction_at(Instant::now(), cx)
10268    }
10269
10270    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10271        self.end_selection(cx);
10272        if let Some(tx_id) = self
10273            .buffer
10274            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10275        {
10276            self.selection_history
10277                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10278            cx.emit(EditorEvent::TransactionBegun {
10279                transaction_id: tx_id,
10280            })
10281        }
10282    }
10283
10284    fn end_transaction_at(
10285        &mut self,
10286        now: Instant,
10287        cx: &mut ViewContext<Self>,
10288    ) -> Option<TransactionId> {
10289        if let Some(transaction_id) = self
10290            .buffer
10291            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10292        {
10293            if let Some((_, end_selections)) =
10294                self.selection_history.transaction_mut(transaction_id)
10295            {
10296                *end_selections = Some(self.selections.disjoint_anchors());
10297            } else {
10298                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10299            }
10300
10301            cx.emit(EditorEvent::Edited { transaction_id });
10302            Some(transaction_id)
10303        } else {
10304            None
10305        }
10306    }
10307
10308    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10309        let selection = self.selections.newest::<Point>(cx);
10310
10311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10312        let range = if selection.is_empty() {
10313            let point = selection.head().to_display_point(&display_map);
10314            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10315            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10316                .to_point(&display_map);
10317            start..end
10318        } else {
10319            selection.range()
10320        };
10321        if display_map.folds_in_range(range).next().is_some() {
10322            self.unfold_lines(&Default::default(), cx)
10323        } else {
10324            self.fold(&Default::default(), cx)
10325        }
10326    }
10327
10328    pub fn toggle_fold_recursive(
10329        &mut self,
10330        _: &actions::ToggleFoldRecursive,
10331        cx: &mut ViewContext<Self>,
10332    ) {
10333        let selection = self.selections.newest::<Point>(cx);
10334
10335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10336        let range = if selection.is_empty() {
10337            let point = selection.head().to_display_point(&display_map);
10338            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10339            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10340                .to_point(&display_map);
10341            start..end
10342        } else {
10343            selection.range()
10344        };
10345        if display_map.folds_in_range(range).next().is_some() {
10346            self.unfold_recursive(&Default::default(), cx)
10347        } else {
10348            self.fold_recursive(&Default::default(), cx)
10349        }
10350    }
10351
10352    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10353        let mut to_fold = Vec::new();
10354        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10355        let selections = self.selections.all_adjusted(cx);
10356
10357        for selection in selections {
10358            let range = selection.range().sorted();
10359            let buffer_start_row = range.start.row;
10360
10361            if range.start.row != range.end.row {
10362                let mut found = false;
10363                let mut row = range.start.row;
10364                while row <= range.end.row {
10365                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10366                        found = true;
10367                        row = crease.range().end.row + 1;
10368                        to_fold.push(crease);
10369                    } else {
10370                        row += 1
10371                    }
10372                }
10373                if found {
10374                    continue;
10375                }
10376            }
10377
10378            for row in (0..=range.start.row).rev() {
10379                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10380                    if crease.range().end.row >= buffer_start_row {
10381                        to_fold.push(crease);
10382                        if row <= range.start.row {
10383                            break;
10384                        }
10385                    }
10386                }
10387            }
10388        }
10389
10390        self.fold_creases(to_fold, true, cx);
10391    }
10392
10393    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10394        if !self.buffer.read(cx).is_singleton() {
10395            return;
10396        }
10397
10398        let fold_at_level = fold_at.level;
10399        let snapshot = self.buffer.read(cx).snapshot(cx);
10400        let mut to_fold = Vec::new();
10401        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10402
10403        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10404            while start_row < end_row {
10405                match self
10406                    .snapshot(cx)
10407                    .crease_for_buffer_row(MultiBufferRow(start_row))
10408                {
10409                    Some(crease) => {
10410                        let nested_start_row = crease.range().start.row + 1;
10411                        let nested_end_row = crease.range().end.row;
10412
10413                        if current_level < fold_at_level {
10414                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10415                        } else if current_level == fold_at_level {
10416                            to_fold.push(crease);
10417                        }
10418
10419                        start_row = nested_end_row + 1;
10420                    }
10421                    None => start_row += 1,
10422                }
10423            }
10424        }
10425
10426        self.fold_creases(to_fold, true, cx);
10427    }
10428
10429    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10430        if !self.buffer.read(cx).is_singleton() {
10431            return;
10432        }
10433
10434        let mut fold_ranges = Vec::new();
10435        let snapshot = self.buffer.read(cx).snapshot(cx);
10436
10437        for row in 0..snapshot.max_row().0 {
10438            if let Some(foldable_range) =
10439                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10440            {
10441                fold_ranges.push(foldable_range);
10442            }
10443        }
10444
10445        self.fold_creases(fold_ranges, true, cx);
10446    }
10447
10448    pub fn fold_function_bodies(
10449        &mut self,
10450        _: &actions::FoldFunctionBodies,
10451        cx: &mut ViewContext<Self>,
10452    ) {
10453        let snapshot = self.buffer.read(cx).snapshot(cx);
10454        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10455            return;
10456        };
10457        let creases = buffer
10458            .function_body_fold_ranges(0..buffer.len())
10459            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10460            .collect();
10461
10462        self.fold_creases(creases, true, cx);
10463    }
10464
10465    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10466        let mut to_fold = Vec::new();
10467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10468        let selections = self.selections.all_adjusted(cx);
10469
10470        for selection in selections {
10471            let range = selection.range().sorted();
10472            let buffer_start_row = range.start.row;
10473
10474            if range.start.row != range.end.row {
10475                let mut found = false;
10476                for row in range.start.row..=range.end.row {
10477                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10478                        found = true;
10479                        to_fold.push(crease);
10480                    }
10481                }
10482                if found {
10483                    continue;
10484                }
10485            }
10486
10487            for row in (0..=range.start.row).rev() {
10488                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10489                    if crease.range().end.row >= buffer_start_row {
10490                        to_fold.push(crease);
10491                    } else {
10492                        break;
10493                    }
10494                }
10495            }
10496        }
10497
10498        self.fold_creases(to_fold, true, cx);
10499    }
10500
10501    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10502        let buffer_row = fold_at.buffer_row;
10503        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10504
10505        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10506            let autoscroll = self
10507                .selections
10508                .all::<Point>(cx)
10509                .iter()
10510                .any(|selection| crease.range().overlaps(&selection.range()));
10511
10512            self.fold_creases(vec![crease], autoscroll, cx);
10513        }
10514    }
10515
10516    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10517        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10518        let buffer = &display_map.buffer_snapshot;
10519        let selections = self.selections.all::<Point>(cx);
10520        let ranges = selections
10521            .iter()
10522            .map(|s| {
10523                let range = s.display_range(&display_map).sorted();
10524                let mut start = range.start.to_point(&display_map);
10525                let mut end = range.end.to_point(&display_map);
10526                start.column = 0;
10527                end.column = buffer.line_len(MultiBufferRow(end.row));
10528                start..end
10529            })
10530            .collect::<Vec<_>>();
10531
10532        self.unfold_ranges(&ranges, true, true, cx);
10533    }
10534
10535    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10536        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10537        let selections = self.selections.all::<Point>(cx);
10538        let ranges = selections
10539            .iter()
10540            .map(|s| {
10541                let mut range = s.display_range(&display_map).sorted();
10542                *range.start.column_mut() = 0;
10543                *range.end.column_mut() = display_map.line_len(range.end.row());
10544                let start = range.start.to_point(&display_map);
10545                let end = range.end.to_point(&display_map);
10546                start..end
10547            })
10548            .collect::<Vec<_>>();
10549
10550        self.unfold_ranges(&ranges, true, true, cx);
10551    }
10552
10553    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10555
10556        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10557            ..Point::new(
10558                unfold_at.buffer_row.0,
10559                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10560            );
10561
10562        let autoscroll = self
10563            .selections
10564            .all::<Point>(cx)
10565            .iter()
10566            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10567
10568        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10569    }
10570
10571    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10572        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10573        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10574    }
10575
10576    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10577        let selections = self.selections.all::<Point>(cx);
10578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10579        let line_mode = self.selections.line_mode;
10580        let ranges = selections
10581            .into_iter()
10582            .map(|s| {
10583                if line_mode {
10584                    let start = Point::new(s.start.row, 0);
10585                    let end = Point::new(
10586                        s.end.row,
10587                        display_map
10588                            .buffer_snapshot
10589                            .line_len(MultiBufferRow(s.end.row)),
10590                    );
10591                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10592                } else {
10593                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10594                }
10595            })
10596            .collect::<Vec<_>>();
10597        self.fold_creases(ranges, true, cx);
10598    }
10599
10600    pub fn fold_creases<T: ToOffset + Clone>(
10601        &mut self,
10602        creases: Vec<Crease<T>>,
10603        auto_scroll: bool,
10604        cx: &mut ViewContext<Self>,
10605    ) {
10606        if creases.is_empty() {
10607            return;
10608        }
10609
10610        let mut buffers_affected = HashSet::default();
10611        let multi_buffer = self.buffer().read(cx);
10612        for crease in &creases {
10613            if let Some((_, buffer, _)) =
10614                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10615            {
10616                buffers_affected.insert(buffer.read(cx).remote_id());
10617            };
10618        }
10619
10620        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10621
10622        if auto_scroll {
10623            self.request_autoscroll(Autoscroll::fit(), cx);
10624        }
10625
10626        for buffer_id in buffers_affected {
10627            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10628        }
10629
10630        cx.notify();
10631
10632        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10633            // Clear diagnostics block when folding a range that contains it.
10634            let snapshot = self.snapshot(cx);
10635            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10636                drop(snapshot);
10637                self.active_diagnostics = Some(active_diagnostics);
10638                self.dismiss_diagnostics(cx);
10639            } else {
10640                self.active_diagnostics = Some(active_diagnostics);
10641            }
10642        }
10643
10644        self.scrollbar_marker_state.dirty = true;
10645    }
10646
10647    /// Removes any folds whose ranges intersect any of the given ranges.
10648    pub fn unfold_ranges<T: ToOffset + Clone>(
10649        &mut self,
10650        ranges: &[Range<T>],
10651        inclusive: bool,
10652        auto_scroll: bool,
10653        cx: &mut ViewContext<Self>,
10654    ) {
10655        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10656            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10657        });
10658    }
10659
10660    /// Removes any folds with the given ranges.
10661    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10662        &mut self,
10663        ranges: &[Range<T>],
10664        type_id: TypeId,
10665        auto_scroll: bool,
10666        cx: &mut ViewContext<Self>,
10667    ) {
10668        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10669            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10670        });
10671    }
10672
10673    fn remove_folds_with<T: ToOffset + Clone>(
10674        &mut self,
10675        ranges: &[Range<T>],
10676        auto_scroll: bool,
10677        cx: &mut ViewContext<Self>,
10678        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10679    ) {
10680        if ranges.is_empty() {
10681            return;
10682        }
10683
10684        let mut buffers_affected = HashSet::default();
10685        let multi_buffer = self.buffer().read(cx);
10686        for range in ranges {
10687            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10688                buffers_affected.insert(buffer.read(cx).remote_id());
10689            };
10690        }
10691
10692        self.display_map.update(cx, update);
10693
10694        if auto_scroll {
10695            self.request_autoscroll(Autoscroll::fit(), cx);
10696        }
10697
10698        for buffer_id in buffers_affected {
10699            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10700        }
10701
10702        cx.notify();
10703        self.scrollbar_marker_state.dirty = true;
10704        self.active_indent_guides_state.dirty = true;
10705    }
10706
10707    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10708        self.display_map.read(cx).fold_placeholder.clone()
10709    }
10710
10711    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10712        if hovered != self.gutter_hovered {
10713            self.gutter_hovered = hovered;
10714            cx.notify();
10715        }
10716    }
10717
10718    pub fn insert_blocks(
10719        &mut self,
10720        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10721        autoscroll: Option<Autoscroll>,
10722        cx: &mut ViewContext<Self>,
10723    ) -> Vec<CustomBlockId> {
10724        let blocks = self
10725            .display_map
10726            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10727        if let Some(autoscroll) = autoscroll {
10728            self.request_autoscroll(autoscroll, cx);
10729        }
10730        cx.notify();
10731        blocks
10732    }
10733
10734    pub fn resize_blocks(
10735        &mut self,
10736        heights: HashMap<CustomBlockId, u32>,
10737        autoscroll: Option<Autoscroll>,
10738        cx: &mut ViewContext<Self>,
10739    ) {
10740        self.display_map
10741            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10742        if let Some(autoscroll) = autoscroll {
10743            self.request_autoscroll(autoscroll, cx);
10744        }
10745        cx.notify();
10746    }
10747
10748    pub fn replace_blocks(
10749        &mut self,
10750        renderers: HashMap<CustomBlockId, RenderBlock>,
10751        autoscroll: Option<Autoscroll>,
10752        cx: &mut ViewContext<Self>,
10753    ) {
10754        self.display_map
10755            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10756        if let Some(autoscroll) = autoscroll {
10757            self.request_autoscroll(autoscroll, cx);
10758        }
10759        cx.notify();
10760    }
10761
10762    pub fn remove_blocks(
10763        &mut self,
10764        block_ids: HashSet<CustomBlockId>,
10765        autoscroll: Option<Autoscroll>,
10766        cx: &mut ViewContext<Self>,
10767    ) {
10768        self.display_map.update(cx, |display_map, cx| {
10769            display_map.remove_blocks(block_ids, cx)
10770        });
10771        if let Some(autoscroll) = autoscroll {
10772            self.request_autoscroll(autoscroll, cx);
10773        }
10774        cx.notify();
10775    }
10776
10777    pub fn row_for_block(
10778        &self,
10779        block_id: CustomBlockId,
10780        cx: &mut ViewContext<Self>,
10781    ) -> Option<DisplayRow> {
10782        self.display_map
10783            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10784    }
10785
10786    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10787        self.focused_block = Some(focused_block);
10788    }
10789
10790    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10791        self.focused_block.take()
10792    }
10793
10794    pub fn insert_creases(
10795        &mut self,
10796        creases: impl IntoIterator<Item = Crease<Anchor>>,
10797        cx: &mut ViewContext<Self>,
10798    ) -> Vec<CreaseId> {
10799        self.display_map
10800            .update(cx, |map, cx| map.insert_creases(creases, cx))
10801    }
10802
10803    pub fn remove_creases(
10804        &mut self,
10805        ids: impl IntoIterator<Item = CreaseId>,
10806        cx: &mut ViewContext<Self>,
10807    ) {
10808        self.display_map
10809            .update(cx, |map, cx| map.remove_creases(ids, cx));
10810    }
10811
10812    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10813        self.display_map
10814            .update(cx, |map, cx| map.snapshot(cx))
10815            .longest_row()
10816    }
10817
10818    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10819        self.display_map
10820            .update(cx, |map, cx| map.snapshot(cx))
10821            .max_point()
10822    }
10823
10824    pub fn text(&self, cx: &AppContext) -> String {
10825        self.buffer.read(cx).read(cx).text()
10826    }
10827
10828    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10829        let text = self.text(cx);
10830        let text = text.trim();
10831
10832        if text.is_empty() {
10833            return None;
10834        }
10835
10836        Some(text.to_string())
10837    }
10838
10839    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10840        self.transact(cx, |this, cx| {
10841            this.buffer
10842                .read(cx)
10843                .as_singleton()
10844                .expect("you can only call set_text on editors for singleton buffers")
10845                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10846        });
10847    }
10848
10849    pub fn display_text(&self, cx: &mut AppContext) -> String {
10850        self.display_map
10851            .update(cx, |map, cx| map.snapshot(cx))
10852            .text()
10853    }
10854
10855    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10856        let mut wrap_guides = smallvec::smallvec![];
10857
10858        if self.show_wrap_guides == Some(false) {
10859            return wrap_guides;
10860        }
10861
10862        let settings = self.buffer.read(cx).settings_at(0, cx);
10863        if settings.show_wrap_guides {
10864            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10865                wrap_guides.push((soft_wrap as usize, true));
10866            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10867                wrap_guides.push((soft_wrap as usize, true));
10868            }
10869            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10870        }
10871
10872        wrap_guides
10873    }
10874
10875    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10876        let settings = self.buffer.read(cx).settings_at(0, cx);
10877        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10878        match mode {
10879            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10880                SoftWrap::None
10881            }
10882            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10883            language_settings::SoftWrap::PreferredLineLength => {
10884                SoftWrap::Column(settings.preferred_line_length)
10885            }
10886            language_settings::SoftWrap::Bounded => {
10887                SoftWrap::Bounded(settings.preferred_line_length)
10888            }
10889        }
10890    }
10891
10892    pub fn set_soft_wrap_mode(
10893        &mut self,
10894        mode: language_settings::SoftWrap,
10895        cx: &mut ViewContext<Self>,
10896    ) {
10897        self.soft_wrap_mode_override = Some(mode);
10898        cx.notify();
10899    }
10900
10901    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10902        self.text_style_refinement = Some(style);
10903    }
10904
10905    /// called by the Element so we know what style we were most recently rendered with.
10906    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10907        let rem_size = cx.rem_size();
10908        self.display_map.update(cx, |map, cx| {
10909            map.set_font(
10910                style.text.font(),
10911                style.text.font_size.to_pixels(rem_size),
10912                cx,
10913            )
10914        });
10915        self.style = Some(style);
10916    }
10917
10918    pub fn style(&self) -> Option<&EditorStyle> {
10919        self.style.as_ref()
10920    }
10921
10922    // Called by the element. This method is not designed to be called outside of the editor
10923    // element's layout code because it does not notify when rewrapping is computed synchronously.
10924    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10925        self.display_map
10926            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10927    }
10928
10929    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10930        if self.soft_wrap_mode_override.is_some() {
10931            self.soft_wrap_mode_override.take();
10932        } else {
10933            let soft_wrap = match self.soft_wrap_mode(cx) {
10934                SoftWrap::GitDiff => return,
10935                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10936                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10937                    language_settings::SoftWrap::None
10938                }
10939            };
10940            self.soft_wrap_mode_override = Some(soft_wrap);
10941        }
10942        cx.notify();
10943    }
10944
10945    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10946        let Some(workspace) = self.workspace() else {
10947            return;
10948        };
10949        let fs = workspace.read(cx).app_state().fs.clone();
10950        let current_show = TabBarSettings::get_global(cx).show;
10951        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10952            setting.show = Some(!current_show);
10953        });
10954    }
10955
10956    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10957        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10958            self.buffer
10959                .read(cx)
10960                .settings_at(0, cx)
10961                .indent_guides
10962                .enabled
10963        });
10964        self.show_indent_guides = Some(!currently_enabled);
10965        cx.notify();
10966    }
10967
10968    fn should_show_indent_guides(&self) -> Option<bool> {
10969        self.show_indent_guides
10970    }
10971
10972    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10973        let mut editor_settings = EditorSettings::get_global(cx).clone();
10974        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10975        EditorSettings::override_global(editor_settings, cx);
10976    }
10977
10978    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10979        self.use_relative_line_numbers
10980            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10981    }
10982
10983    pub fn toggle_relative_line_numbers(
10984        &mut self,
10985        _: &ToggleRelativeLineNumbers,
10986        cx: &mut ViewContext<Self>,
10987    ) {
10988        let is_relative = self.should_use_relative_line_numbers(cx);
10989        self.set_relative_line_number(Some(!is_relative), cx)
10990    }
10991
10992    pub fn set_relative_line_number(
10993        &mut self,
10994        is_relative: Option<bool>,
10995        cx: &mut ViewContext<Self>,
10996    ) {
10997        self.use_relative_line_numbers = is_relative;
10998        cx.notify();
10999    }
11000
11001    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11002        self.show_gutter = show_gutter;
11003        cx.notify();
11004    }
11005
11006    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11007        self.show_line_numbers = Some(show_line_numbers);
11008        cx.notify();
11009    }
11010
11011    pub fn set_show_git_diff_gutter(
11012        &mut self,
11013        show_git_diff_gutter: bool,
11014        cx: &mut ViewContext<Self>,
11015    ) {
11016        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11017        cx.notify();
11018    }
11019
11020    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11021        self.show_code_actions = Some(show_code_actions);
11022        cx.notify();
11023    }
11024
11025    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11026        self.show_runnables = Some(show_runnables);
11027        cx.notify();
11028    }
11029
11030    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11031        if self.display_map.read(cx).masked != masked {
11032            self.display_map.update(cx, |map, _| map.masked = masked);
11033        }
11034        cx.notify()
11035    }
11036
11037    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11038        self.show_wrap_guides = Some(show_wrap_guides);
11039        cx.notify();
11040    }
11041
11042    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11043        self.show_indent_guides = Some(show_indent_guides);
11044        cx.notify();
11045    }
11046
11047    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11048        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11049            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11050                if let Some(dir) = file.abs_path(cx).parent() {
11051                    return Some(dir.to_owned());
11052                }
11053            }
11054
11055            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11056                return Some(project_path.path.to_path_buf());
11057            }
11058        }
11059
11060        None
11061    }
11062
11063    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11064        self.active_excerpt(cx)?
11065            .1
11066            .read(cx)
11067            .file()
11068            .and_then(|f| f.as_local())
11069    }
11070
11071    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11072        if let Some(target) = self.target_file(cx) {
11073            cx.reveal_path(&target.abs_path(cx));
11074        }
11075    }
11076
11077    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11078        if let Some(file) = self.target_file(cx) {
11079            if let Some(path) = file.abs_path(cx).to_str() {
11080                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11081            }
11082        }
11083    }
11084
11085    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11086        if let Some(file) = self.target_file(cx) {
11087            if let Some(path) = file.path().to_str() {
11088                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11089            }
11090        }
11091    }
11092
11093    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11094        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11095
11096        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11097            self.start_git_blame(true, cx);
11098        }
11099
11100        cx.notify();
11101    }
11102
11103    pub fn toggle_git_blame_inline(
11104        &mut self,
11105        _: &ToggleGitBlameInline,
11106        cx: &mut ViewContext<Self>,
11107    ) {
11108        self.toggle_git_blame_inline_internal(true, cx);
11109        cx.notify();
11110    }
11111
11112    pub fn git_blame_inline_enabled(&self) -> bool {
11113        self.git_blame_inline_enabled
11114    }
11115
11116    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11117        self.show_selection_menu = self
11118            .show_selection_menu
11119            .map(|show_selections_menu| !show_selections_menu)
11120            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11121
11122        cx.notify();
11123    }
11124
11125    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11126        self.show_selection_menu
11127            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11128    }
11129
11130    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11131        if let Some(project) = self.project.as_ref() {
11132            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11133                return;
11134            };
11135
11136            if buffer.read(cx).file().is_none() {
11137                return;
11138            }
11139
11140            let focused = self.focus_handle(cx).contains_focused(cx);
11141
11142            let project = project.clone();
11143            let blame =
11144                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11145            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11146            self.blame = Some(blame);
11147        }
11148    }
11149
11150    fn toggle_git_blame_inline_internal(
11151        &mut self,
11152        user_triggered: bool,
11153        cx: &mut ViewContext<Self>,
11154    ) {
11155        if self.git_blame_inline_enabled {
11156            self.git_blame_inline_enabled = false;
11157            self.show_git_blame_inline = false;
11158            self.show_git_blame_inline_delay_task.take();
11159        } else {
11160            self.git_blame_inline_enabled = true;
11161            self.start_git_blame_inline(user_triggered, cx);
11162        }
11163
11164        cx.notify();
11165    }
11166
11167    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11168        self.start_git_blame(user_triggered, cx);
11169
11170        if ProjectSettings::get_global(cx)
11171            .git
11172            .inline_blame_delay()
11173            .is_some()
11174        {
11175            self.start_inline_blame_timer(cx);
11176        } else {
11177            self.show_git_blame_inline = true
11178        }
11179    }
11180
11181    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11182        self.blame.as_ref()
11183    }
11184
11185    pub fn show_git_blame_gutter(&self) -> bool {
11186        self.show_git_blame_gutter
11187    }
11188
11189    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11190        self.show_git_blame_gutter && self.has_blame_entries(cx)
11191    }
11192
11193    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11194        self.show_git_blame_inline
11195            && self.focus_handle.is_focused(cx)
11196            && !self.newest_selection_head_on_empty_line(cx)
11197            && self.has_blame_entries(cx)
11198    }
11199
11200    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11201        self.blame()
11202            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11203    }
11204
11205    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11206        let cursor_anchor = self.selections.newest_anchor().head();
11207
11208        let snapshot = self.buffer.read(cx).snapshot(cx);
11209        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11210
11211        snapshot.line_len(buffer_row) == 0
11212    }
11213
11214    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11215        let buffer_and_selection = maybe!({
11216            let selection = self.selections.newest::<Point>(cx);
11217            let selection_range = selection.range();
11218
11219            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11220                (buffer, selection_range.start.row..selection_range.end.row)
11221            } else {
11222                let buffer_ranges = self
11223                    .buffer()
11224                    .read(cx)
11225                    .range_to_buffer_ranges(selection_range, cx);
11226
11227                let (buffer, range, _) = if selection.reversed {
11228                    buffer_ranges.first()
11229                } else {
11230                    buffer_ranges.last()
11231                }?;
11232
11233                let snapshot = buffer.read(cx).snapshot();
11234                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11235                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11236                (buffer.clone(), selection)
11237            };
11238
11239            Some((buffer, selection))
11240        });
11241
11242        let Some((buffer, selection)) = buffer_and_selection else {
11243            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11244        };
11245
11246        let Some(project) = self.project.as_ref() else {
11247            return Task::ready(Err(anyhow!("editor does not have project")));
11248        };
11249
11250        project.update(cx, |project, cx| {
11251            project.get_permalink_to_line(&buffer, selection, cx)
11252        })
11253    }
11254
11255    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11256        let permalink_task = self.get_permalink_to_line(cx);
11257        let workspace = self.workspace();
11258
11259        cx.spawn(|_, mut cx| async move {
11260            match permalink_task.await {
11261                Ok(permalink) => {
11262                    cx.update(|cx| {
11263                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11264                    })
11265                    .ok();
11266                }
11267                Err(err) => {
11268                    let message = format!("Failed to copy permalink: {err}");
11269
11270                    Err::<(), anyhow::Error>(err).log_err();
11271
11272                    if let Some(workspace) = workspace {
11273                        workspace
11274                            .update(&mut cx, |workspace, cx| {
11275                                struct CopyPermalinkToLine;
11276
11277                                workspace.show_toast(
11278                                    Toast::new(
11279                                        NotificationId::unique::<CopyPermalinkToLine>(),
11280                                        message,
11281                                    ),
11282                                    cx,
11283                                )
11284                            })
11285                            .ok();
11286                    }
11287                }
11288            }
11289        })
11290        .detach();
11291    }
11292
11293    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11294        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11295        if let Some(file) = self.target_file(cx) {
11296            if let Some(path) = file.path().to_str() {
11297                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11298            }
11299        }
11300    }
11301
11302    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11303        let permalink_task = self.get_permalink_to_line(cx);
11304        let workspace = self.workspace();
11305
11306        cx.spawn(|_, mut cx| async move {
11307            match permalink_task.await {
11308                Ok(permalink) => {
11309                    cx.update(|cx| {
11310                        cx.open_url(permalink.as_ref());
11311                    })
11312                    .ok();
11313                }
11314                Err(err) => {
11315                    let message = format!("Failed to open permalink: {err}");
11316
11317                    Err::<(), anyhow::Error>(err).log_err();
11318
11319                    if let Some(workspace) = workspace {
11320                        workspace
11321                            .update(&mut cx, |workspace, cx| {
11322                                struct OpenPermalinkToLine;
11323
11324                                workspace.show_toast(
11325                                    Toast::new(
11326                                        NotificationId::unique::<OpenPermalinkToLine>(),
11327                                        message,
11328                                    ),
11329                                    cx,
11330                                )
11331                            })
11332                            .ok();
11333                    }
11334                }
11335            }
11336        })
11337        .detach();
11338    }
11339
11340    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11341        self.insert_uuid(UuidVersion::V4, cx);
11342    }
11343
11344    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11345        self.insert_uuid(UuidVersion::V7, cx);
11346    }
11347
11348    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11349        self.transact(cx, |this, cx| {
11350            let edits = this
11351                .selections
11352                .all::<Point>(cx)
11353                .into_iter()
11354                .map(|selection| {
11355                    let uuid = match version {
11356                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11357                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11358                    };
11359
11360                    (selection.range(), uuid.to_string())
11361                });
11362            this.edit(edits, cx);
11363            this.refresh_inline_completion(true, false, cx);
11364        });
11365    }
11366
11367    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11368    /// last highlight added will be used.
11369    ///
11370    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11371    pub fn highlight_rows<T: 'static>(
11372        &mut self,
11373        range: Range<Anchor>,
11374        color: Hsla,
11375        should_autoscroll: bool,
11376        cx: &mut ViewContext<Self>,
11377    ) {
11378        let snapshot = self.buffer().read(cx).snapshot(cx);
11379        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11380        let ix = row_highlights.binary_search_by(|highlight| {
11381            Ordering::Equal
11382                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11383                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11384        });
11385
11386        if let Err(mut ix) = ix {
11387            let index = post_inc(&mut self.highlight_order);
11388
11389            // If this range intersects with the preceding highlight, then merge it with
11390            // the preceding highlight. Otherwise insert a new highlight.
11391            let mut merged = false;
11392            if ix > 0 {
11393                let prev_highlight = &mut row_highlights[ix - 1];
11394                if prev_highlight
11395                    .range
11396                    .end
11397                    .cmp(&range.start, &snapshot)
11398                    .is_ge()
11399                {
11400                    ix -= 1;
11401                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11402                        prev_highlight.range.end = range.end;
11403                    }
11404                    merged = true;
11405                    prev_highlight.index = index;
11406                    prev_highlight.color = color;
11407                    prev_highlight.should_autoscroll = should_autoscroll;
11408                }
11409            }
11410
11411            if !merged {
11412                row_highlights.insert(
11413                    ix,
11414                    RowHighlight {
11415                        range: range.clone(),
11416                        index,
11417                        color,
11418                        should_autoscroll,
11419                    },
11420                );
11421            }
11422
11423            // If any of the following highlights intersect with this one, merge them.
11424            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11425                let highlight = &row_highlights[ix];
11426                if next_highlight
11427                    .range
11428                    .start
11429                    .cmp(&highlight.range.end, &snapshot)
11430                    .is_le()
11431                {
11432                    if next_highlight
11433                        .range
11434                        .end
11435                        .cmp(&highlight.range.end, &snapshot)
11436                        .is_gt()
11437                    {
11438                        row_highlights[ix].range.end = next_highlight.range.end;
11439                    }
11440                    row_highlights.remove(ix + 1);
11441                } else {
11442                    break;
11443                }
11444            }
11445        }
11446    }
11447
11448    /// Remove any highlighted row ranges of the given type that intersect the
11449    /// given ranges.
11450    pub fn remove_highlighted_rows<T: 'static>(
11451        &mut self,
11452        ranges_to_remove: Vec<Range<Anchor>>,
11453        cx: &mut ViewContext<Self>,
11454    ) {
11455        let snapshot = self.buffer().read(cx).snapshot(cx);
11456        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11457        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11458        row_highlights.retain(|highlight| {
11459            while let Some(range_to_remove) = ranges_to_remove.peek() {
11460                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11461                    Ordering::Less | Ordering::Equal => {
11462                        ranges_to_remove.next();
11463                    }
11464                    Ordering::Greater => {
11465                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11466                            Ordering::Less | Ordering::Equal => {
11467                                return false;
11468                            }
11469                            Ordering::Greater => break,
11470                        }
11471                    }
11472                }
11473            }
11474
11475            true
11476        })
11477    }
11478
11479    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11480    pub fn clear_row_highlights<T: 'static>(&mut self) {
11481        self.highlighted_rows.remove(&TypeId::of::<T>());
11482    }
11483
11484    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11485    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11486        self.highlighted_rows
11487            .get(&TypeId::of::<T>())
11488            .map_or(&[] as &[_], |vec| vec.as_slice())
11489            .iter()
11490            .map(|highlight| (highlight.range.clone(), highlight.color))
11491    }
11492
11493    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11494    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11495    /// Allows to ignore certain kinds of highlights.
11496    pub fn highlighted_display_rows(
11497        &mut self,
11498        cx: &mut WindowContext,
11499    ) -> BTreeMap<DisplayRow, Hsla> {
11500        let snapshot = self.snapshot(cx);
11501        let mut used_highlight_orders = HashMap::default();
11502        self.highlighted_rows
11503            .iter()
11504            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11505            .fold(
11506                BTreeMap::<DisplayRow, Hsla>::new(),
11507                |mut unique_rows, highlight| {
11508                    let start = highlight.range.start.to_display_point(&snapshot);
11509                    let end = highlight.range.end.to_display_point(&snapshot);
11510                    let start_row = start.row().0;
11511                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11512                        && end.column() == 0
11513                    {
11514                        end.row().0.saturating_sub(1)
11515                    } else {
11516                        end.row().0
11517                    };
11518                    for row in start_row..=end_row {
11519                        let used_index =
11520                            used_highlight_orders.entry(row).or_insert(highlight.index);
11521                        if highlight.index >= *used_index {
11522                            *used_index = highlight.index;
11523                            unique_rows.insert(DisplayRow(row), highlight.color);
11524                        }
11525                    }
11526                    unique_rows
11527                },
11528            )
11529    }
11530
11531    pub fn highlighted_display_row_for_autoscroll(
11532        &self,
11533        snapshot: &DisplaySnapshot,
11534    ) -> Option<DisplayRow> {
11535        self.highlighted_rows
11536            .values()
11537            .flat_map(|highlighted_rows| highlighted_rows.iter())
11538            .filter_map(|highlight| {
11539                if highlight.should_autoscroll {
11540                    Some(highlight.range.start.to_display_point(snapshot).row())
11541                } else {
11542                    None
11543                }
11544            })
11545            .min()
11546    }
11547
11548    pub fn set_search_within_ranges(
11549        &mut self,
11550        ranges: &[Range<Anchor>],
11551        cx: &mut ViewContext<Self>,
11552    ) {
11553        self.highlight_background::<SearchWithinRange>(
11554            ranges,
11555            |colors| colors.editor_document_highlight_read_background,
11556            cx,
11557        )
11558    }
11559
11560    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11561        self.breadcrumb_header = Some(new_header);
11562    }
11563
11564    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11565        self.clear_background_highlights::<SearchWithinRange>(cx);
11566    }
11567
11568    pub fn highlight_background<T: 'static>(
11569        &mut self,
11570        ranges: &[Range<Anchor>],
11571        color_fetcher: fn(&ThemeColors) -> Hsla,
11572        cx: &mut ViewContext<Self>,
11573    ) {
11574        self.background_highlights
11575            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11576        self.scrollbar_marker_state.dirty = true;
11577        cx.notify();
11578    }
11579
11580    pub fn clear_background_highlights<T: 'static>(
11581        &mut self,
11582        cx: &mut ViewContext<Self>,
11583    ) -> Option<BackgroundHighlight> {
11584        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11585        if !text_highlights.1.is_empty() {
11586            self.scrollbar_marker_state.dirty = true;
11587            cx.notify();
11588        }
11589        Some(text_highlights)
11590    }
11591
11592    pub fn highlight_gutter<T: 'static>(
11593        &mut self,
11594        ranges: &[Range<Anchor>],
11595        color_fetcher: fn(&AppContext) -> Hsla,
11596        cx: &mut ViewContext<Self>,
11597    ) {
11598        self.gutter_highlights
11599            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11600        cx.notify();
11601    }
11602
11603    pub fn clear_gutter_highlights<T: 'static>(
11604        &mut self,
11605        cx: &mut ViewContext<Self>,
11606    ) -> Option<GutterHighlight> {
11607        cx.notify();
11608        self.gutter_highlights.remove(&TypeId::of::<T>())
11609    }
11610
11611    #[cfg(feature = "test-support")]
11612    pub fn all_text_background_highlights(
11613        &mut self,
11614        cx: &mut ViewContext<Self>,
11615    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11616        let snapshot = self.snapshot(cx);
11617        let buffer = &snapshot.buffer_snapshot;
11618        let start = buffer.anchor_before(0);
11619        let end = buffer.anchor_after(buffer.len());
11620        let theme = cx.theme().colors();
11621        self.background_highlights_in_range(start..end, &snapshot, theme)
11622    }
11623
11624    #[cfg(feature = "test-support")]
11625    pub fn search_background_highlights(
11626        &mut self,
11627        cx: &mut ViewContext<Self>,
11628    ) -> Vec<Range<Point>> {
11629        let snapshot = self.buffer().read(cx).snapshot(cx);
11630
11631        let highlights = self
11632            .background_highlights
11633            .get(&TypeId::of::<items::BufferSearchHighlights>());
11634
11635        if let Some((_color, ranges)) = highlights {
11636            ranges
11637                .iter()
11638                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11639                .collect_vec()
11640        } else {
11641            vec![]
11642        }
11643    }
11644
11645    fn document_highlights_for_position<'a>(
11646        &'a self,
11647        position: Anchor,
11648        buffer: &'a MultiBufferSnapshot,
11649    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11650        let read_highlights = self
11651            .background_highlights
11652            .get(&TypeId::of::<DocumentHighlightRead>())
11653            .map(|h| &h.1);
11654        let write_highlights = self
11655            .background_highlights
11656            .get(&TypeId::of::<DocumentHighlightWrite>())
11657            .map(|h| &h.1);
11658        let left_position = position.bias_left(buffer);
11659        let right_position = position.bias_right(buffer);
11660        read_highlights
11661            .into_iter()
11662            .chain(write_highlights)
11663            .flat_map(move |ranges| {
11664                let start_ix = match ranges.binary_search_by(|probe| {
11665                    let cmp = probe.end.cmp(&left_position, buffer);
11666                    if cmp.is_ge() {
11667                        Ordering::Greater
11668                    } else {
11669                        Ordering::Less
11670                    }
11671                }) {
11672                    Ok(i) | Err(i) => i,
11673                };
11674
11675                ranges[start_ix..]
11676                    .iter()
11677                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11678            })
11679    }
11680
11681    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11682        self.background_highlights
11683            .get(&TypeId::of::<T>())
11684            .map_or(false, |(_, highlights)| !highlights.is_empty())
11685    }
11686
11687    pub fn background_highlights_in_range(
11688        &self,
11689        search_range: Range<Anchor>,
11690        display_snapshot: &DisplaySnapshot,
11691        theme: &ThemeColors,
11692    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11693        let mut results = Vec::new();
11694        for (color_fetcher, ranges) in self.background_highlights.values() {
11695            let color = color_fetcher(theme);
11696            let start_ix = match ranges.binary_search_by(|probe| {
11697                let cmp = probe
11698                    .end
11699                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11700                if cmp.is_gt() {
11701                    Ordering::Greater
11702                } else {
11703                    Ordering::Less
11704                }
11705            }) {
11706                Ok(i) | Err(i) => i,
11707            };
11708            for range in &ranges[start_ix..] {
11709                if range
11710                    .start
11711                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11712                    .is_ge()
11713                {
11714                    break;
11715                }
11716
11717                let start = range.start.to_display_point(display_snapshot);
11718                let end = range.end.to_display_point(display_snapshot);
11719                results.push((start..end, color))
11720            }
11721        }
11722        results
11723    }
11724
11725    pub fn background_highlight_row_ranges<T: 'static>(
11726        &self,
11727        search_range: Range<Anchor>,
11728        display_snapshot: &DisplaySnapshot,
11729        count: usize,
11730    ) -> Vec<RangeInclusive<DisplayPoint>> {
11731        let mut results = Vec::new();
11732        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11733            return vec![];
11734        };
11735
11736        let start_ix = match ranges.binary_search_by(|probe| {
11737            let cmp = probe
11738                .end
11739                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11740            if cmp.is_gt() {
11741                Ordering::Greater
11742            } else {
11743                Ordering::Less
11744            }
11745        }) {
11746            Ok(i) | Err(i) => i,
11747        };
11748        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11749            if let (Some(start_display), Some(end_display)) = (start, end) {
11750                results.push(
11751                    start_display.to_display_point(display_snapshot)
11752                        ..=end_display.to_display_point(display_snapshot),
11753                );
11754            }
11755        };
11756        let mut start_row: Option<Point> = None;
11757        let mut end_row: Option<Point> = None;
11758        if ranges.len() > count {
11759            return Vec::new();
11760        }
11761        for range in &ranges[start_ix..] {
11762            if range
11763                .start
11764                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11765                .is_ge()
11766            {
11767                break;
11768            }
11769            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11770            if let Some(current_row) = &end_row {
11771                if end.row == current_row.row {
11772                    continue;
11773                }
11774            }
11775            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11776            if start_row.is_none() {
11777                assert_eq!(end_row, None);
11778                start_row = Some(start);
11779                end_row = Some(end);
11780                continue;
11781            }
11782            if let Some(current_end) = end_row.as_mut() {
11783                if start.row > current_end.row + 1 {
11784                    push_region(start_row, end_row);
11785                    start_row = Some(start);
11786                    end_row = Some(end);
11787                } else {
11788                    // Merge two hunks.
11789                    *current_end = end;
11790                }
11791            } else {
11792                unreachable!();
11793            }
11794        }
11795        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11796        push_region(start_row, end_row);
11797        results
11798    }
11799
11800    pub fn gutter_highlights_in_range(
11801        &self,
11802        search_range: Range<Anchor>,
11803        display_snapshot: &DisplaySnapshot,
11804        cx: &AppContext,
11805    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11806        let mut results = Vec::new();
11807        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11808            let color = color_fetcher(cx);
11809            let start_ix = match ranges.binary_search_by(|probe| {
11810                let cmp = probe
11811                    .end
11812                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11813                if cmp.is_gt() {
11814                    Ordering::Greater
11815                } else {
11816                    Ordering::Less
11817                }
11818            }) {
11819                Ok(i) | Err(i) => i,
11820            };
11821            for range in &ranges[start_ix..] {
11822                if range
11823                    .start
11824                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11825                    .is_ge()
11826                {
11827                    break;
11828                }
11829
11830                let start = range.start.to_display_point(display_snapshot);
11831                let end = range.end.to_display_point(display_snapshot);
11832                results.push((start..end, color))
11833            }
11834        }
11835        results
11836    }
11837
11838    /// Get the text ranges corresponding to the redaction query
11839    pub fn redacted_ranges(
11840        &self,
11841        search_range: Range<Anchor>,
11842        display_snapshot: &DisplaySnapshot,
11843        cx: &WindowContext,
11844    ) -> Vec<Range<DisplayPoint>> {
11845        display_snapshot
11846            .buffer_snapshot
11847            .redacted_ranges(search_range, |file| {
11848                if let Some(file) = file {
11849                    file.is_private()
11850                        && EditorSettings::get(
11851                            Some(SettingsLocation {
11852                                worktree_id: file.worktree_id(cx),
11853                                path: file.path().as_ref(),
11854                            }),
11855                            cx,
11856                        )
11857                        .redact_private_values
11858                } else {
11859                    false
11860                }
11861            })
11862            .map(|range| {
11863                range.start.to_display_point(display_snapshot)
11864                    ..range.end.to_display_point(display_snapshot)
11865            })
11866            .collect()
11867    }
11868
11869    pub fn highlight_text<T: 'static>(
11870        &mut self,
11871        ranges: Vec<Range<Anchor>>,
11872        style: HighlightStyle,
11873        cx: &mut ViewContext<Self>,
11874    ) {
11875        self.display_map.update(cx, |map, _| {
11876            map.highlight_text(TypeId::of::<T>(), ranges, style)
11877        });
11878        cx.notify();
11879    }
11880
11881    pub(crate) fn highlight_inlays<T: 'static>(
11882        &mut self,
11883        highlights: Vec<InlayHighlight>,
11884        style: HighlightStyle,
11885        cx: &mut ViewContext<Self>,
11886    ) {
11887        self.display_map.update(cx, |map, _| {
11888            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11889        });
11890        cx.notify();
11891    }
11892
11893    pub fn text_highlights<'a, T: 'static>(
11894        &'a self,
11895        cx: &'a AppContext,
11896    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11897        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11898    }
11899
11900    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11901        let cleared = self
11902            .display_map
11903            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11904        if cleared {
11905            cx.notify();
11906        }
11907    }
11908
11909    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11910        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11911            && self.focus_handle.is_focused(cx)
11912    }
11913
11914    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11915        self.show_cursor_when_unfocused = is_enabled;
11916        cx.notify();
11917    }
11918
11919    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
11920        self.project
11921            .as_ref()
11922            .map(|project| project.read(cx).lsp_store())
11923    }
11924
11925    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11926        cx.notify();
11927    }
11928
11929    fn on_buffer_event(
11930        &mut self,
11931        multibuffer: Model<MultiBuffer>,
11932        event: &multi_buffer::Event,
11933        cx: &mut ViewContext<Self>,
11934    ) {
11935        match event {
11936            multi_buffer::Event::Edited {
11937                singleton_buffer_edited,
11938                edited_buffer: buffer_edited,
11939            } => {
11940                self.scrollbar_marker_state.dirty = true;
11941                self.active_indent_guides_state.dirty = true;
11942                self.refresh_active_diagnostics(cx);
11943                self.refresh_code_actions(cx);
11944                if self.has_active_inline_completion() {
11945                    self.update_visible_inline_completion(cx);
11946                }
11947                if let Some(buffer) = buffer_edited {
11948                    let buffer_id = buffer.read(cx).remote_id();
11949                    if !self.registered_buffers.contains_key(&buffer_id) {
11950                        if let Some(lsp_store) = self.lsp_store(cx) {
11951                            lsp_store.update(cx, |lsp_store, cx| {
11952                                self.registered_buffers.insert(
11953                                    buffer_id,
11954                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
11955                                );
11956                            })
11957                        }
11958                    }
11959                }
11960                cx.emit(EditorEvent::BufferEdited);
11961                cx.emit(SearchEvent::MatchesInvalidated);
11962                if *singleton_buffer_edited {
11963                    if let Some(project) = &self.project {
11964                        let project = project.read(cx);
11965                        #[allow(clippy::mutable_key_type)]
11966                        let languages_affected = multibuffer
11967                            .read(cx)
11968                            .all_buffers()
11969                            .into_iter()
11970                            .filter_map(|buffer| {
11971                                let buffer = buffer.read(cx);
11972                                let language = buffer.language()?;
11973                                if project.is_local()
11974                                    && project
11975                                        .language_servers_for_local_buffer(buffer, cx)
11976                                        .count()
11977                                        == 0
11978                                {
11979                                    None
11980                                } else {
11981                                    Some(language)
11982                                }
11983                            })
11984                            .cloned()
11985                            .collect::<HashSet<_>>();
11986                        if !languages_affected.is_empty() {
11987                            self.refresh_inlay_hints(
11988                                InlayHintRefreshReason::BufferEdited(languages_affected),
11989                                cx,
11990                            );
11991                        }
11992                    }
11993                }
11994
11995                let Some(project) = &self.project else { return };
11996                let (telemetry, is_via_ssh) = {
11997                    let project = project.read(cx);
11998                    let telemetry = project.client().telemetry().clone();
11999                    let is_via_ssh = project.is_via_ssh();
12000                    (telemetry, is_via_ssh)
12001                };
12002                refresh_linked_ranges(self, cx);
12003                telemetry.log_edit_event("editor", is_via_ssh);
12004            }
12005            multi_buffer::Event::ExcerptsAdded {
12006                buffer,
12007                predecessor,
12008                excerpts,
12009            } => {
12010                self.tasks_update_task = Some(self.refresh_runnables(cx));
12011                let buffer_id = buffer.read(cx).remote_id();
12012                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12013                    if let Some(project) = &self.project {
12014                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12015                    }
12016                }
12017                cx.emit(EditorEvent::ExcerptsAdded {
12018                    buffer: buffer.clone(),
12019                    predecessor: *predecessor,
12020                    excerpts: excerpts.clone(),
12021                });
12022                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12023            }
12024            multi_buffer::Event::ExcerptsRemoved { ids } => {
12025                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12026                let buffer = self.buffer.read(cx);
12027                self.registered_buffers
12028                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12029                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12030            }
12031            multi_buffer::Event::ExcerptsEdited { ids } => {
12032                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12033            }
12034            multi_buffer::Event::ExcerptsExpanded { ids } => {
12035                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12036            }
12037            multi_buffer::Event::Reparsed(buffer_id) => {
12038                self.tasks_update_task = Some(self.refresh_runnables(cx));
12039
12040                cx.emit(EditorEvent::Reparsed(*buffer_id));
12041            }
12042            multi_buffer::Event::LanguageChanged(buffer_id) => {
12043                linked_editing_ranges::refresh_linked_ranges(self, cx);
12044                cx.emit(EditorEvent::Reparsed(*buffer_id));
12045                cx.notify();
12046            }
12047            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12048            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12049            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12050                cx.emit(EditorEvent::TitleChanged)
12051            }
12052            // multi_buffer::Event::DiffBaseChanged => {
12053            //     self.scrollbar_marker_state.dirty = true;
12054            //     cx.emit(EditorEvent::DiffBaseChanged);
12055            //     cx.notify();
12056            // }
12057            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12058            multi_buffer::Event::DiagnosticsUpdated => {
12059                self.refresh_active_diagnostics(cx);
12060                self.scrollbar_marker_state.dirty = true;
12061                cx.notify();
12062            }
12063            _ => {}
12064        };
12065    }
12066
12067    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12068        cx.notify();
12069    }
12070
12071    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12072        self.tasks_update_task = Some(self.refresh_runnables(cx));
12073        self.refresh_inline_completion(true, false, cx);
12074        self.refresh_inlay_hints(
12075            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12076                self.selections.newest_anchor().head(),
12077                &self.buffer.read(cx).snapshot(cx),
12078                cx,
12079            )),
12080            cx,
12081        );
12082
12083        let old_cursor_shape = self.cursor_shape;
12084
12085        {
12086            let editor_settings = EditorSettings::get_global(cx);
12087            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12088            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12089            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12090        }
12091
12092        if old_cursor_shape != self.cursor_shape {
12093            cx.emit(EditorEvent::CursorShapeChanged);
12094        }
12095
12096        let project_settings = ProjectSettings::get_global(cx);
12097        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12098
12099        if self.mode == EditorMode::Full {
12100            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12101            if self.git_blame_inline_enabled != inline_blame_enabled {
12102                self.toggle_git_blame_inline_internal(false, cx);
12103            }
12104        }
12105
12106        cx.notify();
12107    }
12108
12109    pub fn set_searchable(&mut self, searchable: bool) {
12110        self.searchable = searchable;
12111    }
12112
12113    pub fn searchable(&self) -> bool {
12114        self.searchable
12115    }
12116
12117    fn open_proposed_changes_editor(
12118        &mut self,
12119        _: &OpenProposedChangesEditor,
12120        cx: &mut ViewContext<Self>,
12121    ) {
12122        let Some(workspace) = self.workspace() else {
12123            cx.propagate();
12124            return;
12125        };
12126
12127        let selections = self.selections.all::<usize>(cx);
12128        let buffer = self.buffer.read(cx);
12129        let mut new_selections_by_buffer = HashMap::default();
12130        for selection in selections {
12131            for (buffer, range, _) in
12132                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12133            {
12134                let mut range = range.to_point(buffer.read(cx));
12135                range.start.column = 0;
12136                range.end.column = buffer.read(cx).line_len(range.end.row);
12137                new_selections_by_buffer
12138                    .entry(buffer)
12139                    .or_insert(Vec::new())
12140                    .push(range)
12141            }
12142        }
12143
12144        let proposed_changes_buffers = new_selections_by_buffer
12145            .into_iter()
12146            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12147            .collect::<Vec<_>>();
12148        let proposed_changes_editor = cx.new_view(|cx| {
12149            ProposedChangesEditor::new(
12150                "Proposed changes",
12151                proposed_changes_buffers,
12152                self.project.clone(),
12153                cx,
12154            )
12155        });
12156
12157        cx.window_context().defer(move |cx| {
12158            workspace.update(cx, |workspace, cx| {
12159                workspace.active_pane().update(cx, |pane, cx| {
12160                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12161                });
12162            });
12163        });
12164    }
12165
12166    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12167        self.open_excerpts_common(None, true, cx)
12168    }
12169
12170    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12171        self.open_excerpts_common(None, false, cx)
12172    }
12173
12174    fn open_excerpts_common(
12175        &mut self,
12176        jump_data: Option<JumpData>,
12177        split: bool,
12178        cx: &mut ViewContext<Self>,
12179    ) {
12180        let Some(workspace) = self.workspace() else {
12181            cx.propagate();
12182            return;
12183        };
12184
12185        if self.buffer.read(cx).is_singleton() {
12186            cx.propagate();
12187            return;
12188        }
12189
12190        let mut new_selections_by_buffer = HashMap::default();
12191        match &jump_data {
12192            Some(jump_data) => {
12193                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12194                if let Some(buffer) = multi_buffer_snapshot
12195                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12196                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12197                {
12198                    let buffer_snapshot = buffer.read(cx).snapshot();
12199                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12200                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12201                    } else {
12202                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12203                    };
12204                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12205                    new_selections_by_buffer.insert(
12206                        buffer,
12207                        (
12208                            vec![jump_to_offset..jump_to_offset],
12209                            Some(jump_data.line_offset_from_top),
12210                        ),
12211                    );
12212                }
12213            }
12214            None => {
12215                let selections = self.selections.all::<usize>(cx);
12216                let buffer = self.buffer.read(cx);
12217                for selection in selections {
12218                    for (mut buffer_handle, mut range, _) in
12219                        buffer.range_to_buffer_ranges(selection.range(), cx)
12220                    {
12221                        // When editing branch buffers, jump to the corresponding location
12222                        // in their base buffer.
12223                        let buffer = buffer_handle.read(cx);
12224                        if let Some(base_buffer) = buffer.base_buffer() {
12225                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12226                            buffer_handle = base_buffer;
12227                        }
12228
12229                        if selection.reversed {
12230                            mem::swap(&mut range.start, &mut range.end);
12231                        }
12232                        new_selections_by_buffer
12233                            .entry(buffer_handle)
12234                            .or_insert((Vec::new(), None))
12235                            .0
12236                            .push(range)
12237                    }
12238                }
12239            }
12240        }
12241
12242        if new_selections_by_buffer.is_empty() {
12243            return;
12244        }
12245
12246        // We defer the pane interaction because we ourselves are a workspace item
12247        // and activating a new item causes the pane to call a method on us reentrantly,
12248        // which panics if we're on the stack.
12249        cx.window_context().defer(move |cx| {
12250            workspace.update(cx, |workspace, cx| {
12251                let pane = if split {
12252                    workspace.adjacent_pane(cx)
12253                } else {
12254                    workspace.active_pane().clone()
12255                };
12256
12257                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12258                    let editor = buffer
12259                        .read(cx)
12260                        .file()
12261                        .is_none()
12262                        .then(|| {
12263                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12264                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12265                            // Instead, we try to activate the existing editor in the pane first.
12266                            let (editor, pane_item_index) =
12267                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12268                                    let editor = item.downcast::<Editor>()?;
12269                                    let singleton_buffer =
12270                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12271                                    if singleton_buffer == buffer {
12272                                        Some((editor, i))
12273                                    } else {
12274                                        None
12275                                    }
12276                                })?;
12277                            pane.update(cx, |pane, cx| {
12278                                pane.activate_item(pane_item_index, true, true, cx)
12279                            });
12280                            Some(editor)
12281                        })
12282                        .flatten()
12283                        .unwrap_or_else(|| {
12284                            workspace.open_project_item::<Self>(
12285                                pane.clone(),
12286                                buffer,
12287                                true,
12288                                true,
12289                                cx,
12290                            )
12291                        });
12292
12293                    editor.update(cx, |editor, cx| {
12294                        let autoscroll = match scroll_offset {
12295                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12296                            None => Autoscroll::newest(),
12297                        };
12298                        let nav_history = editor.nav_history.take();
12299                        editor.change_selections(Some(autoscroll), cx, |s| {
12300                            s.select_ranges(ranges);
12301                        });
12302                        editor.nav_history = nav_history;
12303                    });
12304                }
12305            })
12306        });
12307    }
12308
12309    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12310        let snapshot = self.buffer.read(cx).read(cx);
12311        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12312        Some(
12313            ranges
12314                .iter()
12315                .map(move |range| {
12316                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12317                })
12318                .collect(),
12319        )
12320    }
12321
12322    fn selection_replacement_ranges(
12323        &self,
12324        range: Range<OffsetUtf16>,
12325        cx: &mut AppContext,
12326    ) -> Vec<Range<OffsetUtf16>> {
12327        let selections = self.selections.all::<OffsetUtf16>(cx);
12328        let newest_selection = selections
12329            .iter()
12330            .max_by_key(|selection| selection.id)
12331            .unwrap();
12332        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12333        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12334        let snapshot = self.buffer.read(cx).read(cx);
12335        selections
12336            .into_iter()
12337            .map(|mut selection| {
12338                selection.start.0 =
12339                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12340                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12341                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12342                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12343            })
12344            .collect()
12345    }
12346
12347    fn report_editor_event(
12348        &self,
12349        operation: &'static str,
12350        file_extension: Option<String>,
12351        cx: &AppContext,
12352    ) {
12353        if cfg!(any(test, feature = "test-support")) {
12354            return;
12355        }
12356
12357        let Some(project) = &self.project else { return };
12358
12359        // If None, we are in a file without an extension
12360        let file = self
12361            .buffer
12362            .read(cx)
12363            .as_singleton()
12364            .and_then(|b| b.read(cx).file());
12365        let file_extension = file_extension.or(file
12366            .as_ref()
12367            .and_then(|file| Path::new(file.file_name(cx)).extension())
12368            .and_then(|e| e.to_str())
12369            .map(|a| a.to_string()));
12370
12371        let vim_mode = cx
12372            .global::<SettingsStore>()
12373            .raw_user_settings()
12374            .get("vim_mode")
12375            == Some(&serde_json::Value::Bool(true));
12376
12377        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12378            == language::language_settings::InlineCompletionProvider::Copilot;
12379        let copilot_enabled_for_language = self
12380            .buffer
12381            .read(cx)
12382            .settings_at(0, cx)
12383            .show_inline_completions;
12384
12385        let project = project.read(cx);
12386        let telemetry = project.client().telemetry().clone();
12387        telemetry.report_editor_event(
12388            file_extension,
12389            vim_mode,
12390            operation,
12391            copilot_enabled,
12392            copilot_enabled_for_language,
12393            project.is_via_ssh(),
12394        )
12395    }
12396
12397    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12398    /// with each line being an array of {text, highlight} objects.
12399    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12400        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12401            return;
12402        };
12403
12404        #[derive(Serialize)]
12405        struct Chunk<'a> {
12406            text: String,
12407            highlight: Option<&'a str>,
12408        }
12409
12410        let snapshot = buffer.read(cx).snapshot();
12411        let range = self
12412            .selected_text_range(false, cx)
12413            .and_then(|selection| {
12414                if selection.range.is_empty() {
12415                    None
12416                } else {
12417                    Some(selection.range)
12418                }
12419            })
12420            .unwrap_or_else(|| 0..snapshot.len());
12421
12422        let chunks = snapshot.chunks(range, true);
12423        let mut lines = Vec::new();
12424        let mut line: VecDeque<Chunk> = VecDeque::new();
12425
12426        let Some(style) = self.style.as_ref() else {
12427            return;
12428        };
12429
12430        for chunk in chunks {
12431            let highlight = chunk
12432                .syntax_highlight_id
12433                .and_then(|id| id.name(&style.syntax));
12434            let mut chunk_lines = chunk.text.split('\n').peekable();
12435            while let Some(text) = chunk_lines.next() {
12436                let mut merged_with_last_token = false;
12437                if let Some(last_token) = line.back_mut() {
12438                    if last_token.highlight == highlight {
12439                        last_token.text.push_str(text);
12440                        merged_with_last_token = true;
12441                    }
12442                }
12443
12444                if !merged_with_last_token {
12445                    line.push_back(Chunk {
12446                        text: text.into(),
12447                        highlight,
12448                    });
12449                }
12450
12451                if chunk_lines.peek().is_some() {
12452                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12453                        line.pop_front();
12454                    }
12455                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12456                        line.pop_back();
12457                    }
12458
12459                    lines.push(mem::take(&mut line));
12460                }
12461            }
12462        }
12463
12464        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12465            return;
12466        };
12467        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12468    }
12469
12470    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12471        self.request_autoscroll(Autoscroll::newest(), cx);
12472        let position = self.selections.newest_display(cx).start;
12473        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12474    }
12475
12476    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12477        &self.inlay_hint_cache
12478    }
12479
12480    pub fn replay_insert_event(
12481        &mut self,
12482        text: &str,
12483        relative_utf16_range: Option<Range<isize>>,
12484        cx: &mut ViewContext<Self>,
12485    ) {
12486        if !self.input_enabled {
12487            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12488            return;
12489        }
12490        if let Some(relative_utf16_range) = relative_utf16_range {
12491            let selections = self.selections.all::<OffsetUtf16>(cx);
12492            self.change_selections(None, cx, |s| {
12493                let new_ranges = selections.into_iter().map(|range| {
12494                    let start = OffsetUtf16(
12495                        range
12496                            .head()
12497                            .0
12498                            .saturating_add_signed(relative_utf16_range.start),
12499                    );
12500                    let end = OffsetUtf16(
12501                        range
12502                            .head()
12503                            .0
12504                            .saturating_add_signed(relative_utf16_range.end),
12505                    );
12506                    start..end
12507                });
12508                s.select_ranges(new_ranges);
12509            });
12510        }
12511
12512        self.handle_input(text, cx);
12513    }
12514
12515    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12516        let Some(provider) = self.semantics_provider.as_ref() else {
12517            return false;
12518        };
12519
12520        let mut supports = false;
12521        self.buffer().read(cx).for_each_buffer(|buffer| {
12522            supports |= provider.supports_inlay_hints(buffer, cx);
12523        });
12524        supports
12525    }
12526
12527    pub fn focus(&self, cx: &mut WindowContext) {
12528        cx.focus(&self.focus_handle)
12529    }
12530
12531    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12532        self.focus_handle.is_focused(cx)
12533    }
12534
12535    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12536        cx.emit(EditorEvent::Focused);
12537
12538        if let Some(descendant) = self
12539            .last_focused_descendant
12540            .take()
12541            .and_then(|descendant| descendant.upgrade())
12542        {
12543            cx.focus(&descendant);
12544        } else {
12545            if let Some(blame) = self.blame.as_ref() {
12546                blame.update(cx, GitBlame::focus)
12547            }
12548
12549            self.blink_manager.update(cx, BlinkManager::enable);
12550            self.show_cursor_names(cx);
12551            self.buffer.update(cx, |buffer, cx| {
12552                buffer.finalize_last_transaction(cx);
12553                if self.leader_peer_id.is_none() {
12554                    buffer.set_active_selections(
12555                        &self.selections.disjoint_anchors(),
12556                        self.selections.line_mode,
12557                        self.cursor_shape,
12558                        cx,
12559                    );
12560                }
12561            });
12562        }
12563    }
12564
12565    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12566        cx.emit(EditorEvent::FocusedIn)
12567    }
12568
12569    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12570        if event.blurred != self.focus_handle {
12571            self.last_focused_descendant = Some(event.blurred);
12572        }
12573    }
12574
12575    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12576        self.blink_manager.update(cx, BlinkManager::disable);
12577        self.buffer
12578            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12579
12580        if let Some(blame) = self.blame.as_ref() {
12581            blame.update(cx, GitBlame::blur)
12582        }
12583        if !self.hover_state.focused(cx) {
12584            hide_hover(self, cx);
12585        }
12586
12587        self.hide_context_menu(cx);
12588        cx.emit(EditorEvent::Blurred);
12589        cx.notify();
12590    }
12591
12592    pub fn register_action<A: Action>(
12593        &mut self,
12594        listener: impl Fn(&A, &mut WindowContext) + 'static,
12595    ) -> Subscription {
12596        let id = self.next_editor_action_id.post_inc();
12597        let listener = Arc::new(listener);
12598        self.editor_actions.borrow_mut().insert(
12599            id,
12600            Box::new(move |cx| {
12601                let cx = cx.window_context();
12602                let listener = listener.clone();
12603                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12604                    let action = action.downcast_ref().unwrap();
12605                    if phase == DispatchPhase::Bubble {
12606                        listener(action, cx)
12607                    }
12608                })
12609            }),
12610        );
12611
12612        let editor_actions = self.editor_actions.clone();
12613        Subscription::new(move || {
12614            editor_actions.borrow_mut().remove(&id);
12615        })
12616    }
12617
12618    pub fn file_header_size(&self) -> u32 {
12619        FILE_HEADER_HEIGHT
12620    }
12621
12622    pub fn revert(
12623        &mut self,
12624        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12625        cx: &mut ViewContext<Self>,
12626    ) {
12627        self.buffer().update(cx, |multi_buffer, cx| {
12628            for (buffer_id, changes) in revert_changes {
12629                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12630                    buffer.update(cx, |buffer, cx| {
12631                        buffer.edit(
12632                            changes.into_iter().map(|(range, text)| {
12633                                (range, text.to_string().map(Arc::<str>::from))
12634                            }),
12635                            None,
12636                            cx,
12637                        );
12638                    });
12639                }
12640            }
12641        });
12642        self.change_selections(None, cx, |selections| selections.refresh());
12643    }
12644
12645    pub fn to_pixel_point(
12646        &mut self,
12647        source: multi_buffer::Anchor,
12648        editor_snapshot: &EditorSnapshot,
12649        cx: &mut ViewContext<Self>,
12650    ) -> Option<gpui::Point<Pixels>> {
12651        let source_point = source.to_display_point(editor_snapshot);
12652        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12653    }
12654
12655    pub fn display_to_pixel_point(
12656        &self,
12657        source: DisplayPoint,
12658        editor_snapshot: &EditorSnapshot,
12659        cx: &WindowContext,
12660    ) -> Option<gpui::Point<Pixels>> {
12661        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12662        let text_layout_details = self.text_layout_details(cx);
12663        let scroll_top = text_layout_details
12664            .scroll_anchor
12665            .scroll_position(editor_snapshot)
12666            .y;
12667
12668        if source.row().as_f32() < scroll_top.floor() {
12669            return None;
12670        }
12671        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12672        let source_y = line_height * (source.row().as_f32() - scroll_top);
12673        Some(gpui::Point::new(source_x, source_y))
12674    }
12675
12676    pub fn has_active_completions_menu(&self) -> bool {
12677        self.context_menu.read().as_ref().map_or(false, |menu| {
12678            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12679        })
12680    }
12681
12682    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12683        self.addons
12684            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12685    }
12686
12687    pub fn unregister_addon<T: Addon>(&mut self) {
12688        self.addons.remove(&std::any::TypeId::of::<T>());
12689    }
12690
12691    pub fn addon<T: Addon>(&self) -> Option<&T> {
12692        let type_id = std::any::TypeId::of::<T>();
12693        self.addons
12694            .get(&type_id)
12695            .and_then(|item| item.to_any().downcast_ref::<T>())
12696    }
12697
12698    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12699        let text_layout_details = self.text_layout_details(cx);
12700        let style = &text_layout_details.editor_style;
12701        let font_id = cx.text_system().resolve_font(&style.text.font());
12702        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12703        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12704
12705        let em_width = cx
12706            .text_system()
12707            .typographic_bounds(font_id, font_size, 'm')
12708            .unwrap()
12709            .size
12710            .width;
12711
12712        gpui::Point::new(em_width, line_height)
12713    }
12714}
12715
12716fn get_unstaged_changes_for_buffers(
12717    project: &Model<Project>,
12718    buffers: impl IntoIterator<Item = Model<Buffer>>,
12719    cx: &mut ViewContext<Editor>,
12720) {
12721    let mut tasks = Vec::new();
12722    project.update(cx, |project, cx| {
12723        for buffer in buffers {
12724            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12725        }
12726    });
12727    cx.spawn(|this, mut cx| async move {
12728        let change_sets = futures::future::join_all(tasks).await;
12729        this.update(&mut cx, |this, cx| {
12730            for change_set in change_sets {
12731                if let Some(change_set) = change_set.log_err() {
12732                    this.diff_map.add_change_set(change_set, cx);
12733                }
12734            }
12735        })
12736        .ok();
12737    })
12738    .detach();
12739}
12740
12741fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12742    let tab_size = tab_size.get() as usize;
12743    let mut width = offset;
12744
12745    for ch in text.chars() {
12746        width += if ch == '\t' {
12747            tab_size - (width % tab_size)
12748        } else {
12749            1
12750        };
12751    }
12752
12753    width - offset
12754}
12755
12756#[cfg(test)]
12757mod tests {
12758    use super::*;
12759
12760    #[test]
12761    fn test_string_size_with_expanded_tabs() {
12762        let nz = |val| NonZeroU32::new(val).unwrap();
12763        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12764        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12765        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12766        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12767        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12768        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12769        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12770        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12771    }
12772}
12773
12774/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12775struct WordBreakingTokenizer<'a> {
12776    input: &'a str,
12777}
12778
12779impl<'a> WordBreakingTokenizer<'a> {
12780    fn new(input: &'a str) -> Self {
12781        Self { input }
12782    }
12783}
12784
12785fn is_char_ideographic(ch: char) -> bool {
12786    use unicode_script::Script::*;
12787    use unicode_script::UnicodeScript;
12788    matches!(ch.script(), Han | Tangut | Yi)
12789}
12790
12791fn is_grapheme_ideographic(text: &str) -> bool {
12792    text.chars().any(is_char_ideographic)
12793}
12794
12795fn is_grapheme_whitespace(text: &str) -> bool {
12796    text.chars().any(|x| x.is_whitespace())
12797}
12798
12799fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12800    text.chars().next().map_or(false, |ch| {
12801        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12802    })
12803}
12804
12805#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12806struct WordBreakToken<'a> {
12807    token: &'a str,
12808    grapheme_len: usize,
12809    is_whitespace: bool,
12810}
12811
12812impl<'a> Iterator for WordBreakingTokenizer<'a> {
12813    /// Yields a span, the count of graphemes in the token, and whether it was
12814    /// whitespace. Note that it also breaks at word boundaries.
12815    type Item = WordBreakToken<'a>;
12816
12817    fn next(&mut self) -> Option<Self::Item> {
12818        use unicode_segmentation::UnicodeSegmentation;
12819        if self.input.is_empty() {
12820            return None;
12821        }
12822
12823        let mut iter = self.input.graphemes(true).peekable();
12824        let mut offset = 0;
12825        let mut graphemes = 0;
12826        if let Some(first_grapheme) = iter.next() {
12827            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12828            offset += first_grapheme.len();
12829            graphemes += 1;
12830            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12831                if let Some(grapheme) = iter.peek().copied() {
12832                    if should_stay_with_preceding_ideograph(grapheme) {
12833                        offset += grapheme.len();
12834                        graphemes += 1;
12835                    }
12836                }
12837            } else {
12838                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12839                let mut next_word_bound = words.peek().copied();
12840                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12841                    next_word_bound = words.next();
12842                }
12843                while let Some(grapheme) = iter.peek().copied() {
12844                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12845                        break;
12846                    };
12847                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12848                        break;
12849                    };
12850                    offset += grapheme.len();
12851                    graphemes += 1;
12852                    iter.next();
12853                }
12854            }
12855            let token = &self.input[..offset];
12856            self.input = &self.input[offset..];
12857            if is_whitespace {
12858                Some(WordBreakToken {
12859                    token: " ",
12860                    grapheme_len: 1,
12861                    is_whitespace: true,
12862                })
12863            } else {
12864                Some(WordBreakToken {
12865                    token,
12866                    grapheme_len: graphemes,
12867                    is_whitespace: false,
12868                })
12869            }
12870        } else {
12871            None
12872        }
12873    }
12874}
12875
12876#[test]
12877fn test_word_breaking_tokenizer() {
12878    let tests: &[(&str, &[(&str, usize, bool)])] = &[
12879        ("", &[]),
12880        ("  ", &[(" ", 1, true)]),
12881        ("Ʒ", &[("Ʒ", 1, false)]),
12882        ("Ǽ", &[("Ǽ", 1, false)]),
12883        ("", &[("", 1, false)]),
12884        ("⋑⋑", &[("⋑⋑", 2, false)]),
12885        (
12886            "原理,进而",
12887            &[
12888                ("", 1, false),
12889                ("理,", 2, false),
12890                ("", 1, false),
12891                ("", 1, false),
12892            ],
12893        ),
12894        (
12895            "hello world",
12896            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12897        ),
12898        (
12899            "hello, world",
12900            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12901        ),
12902        (
12903            "  hello world",
12904            &[
12905                (" ", 1, true),
12906                ("hello", 5, false),
12907                (" ", 1, true),
12908                ("world", 5, false),
12909            ],
12910        ),
12911        (
12912            "这是什么 \n 钢笔",
12913            &[
12914                ("", 1, false),
12915                ("", 1, false),
12916                ("", 1, false),
12917                ("", 1, false),
12918                (" ", 1, true),
12919                ("", 1, false),
12920                ("", 1, false),
12921            ],
12922        ),
12923        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12924    ];
12925
12926    for (input, result) in tests {
12927        assert_eq!(
12928            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12929            result
12930                .iter()
12931                .copied()
12932                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12933                    token,
12934                    grapheme_len,
12935                    is_whitespace,
12936                })
12937                .collect::<Vec<_>>()
12938        );
12939    }
12940}
12941
12942fn wrap_with_prefix(
12943    line_prefix: String,
12944    unwrapped_text: String,
12945    wrap_column: usize,
12946    tab_size: NonZeroU32,
12947) -> String {
12948    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12949    let mut wrapped_text = String::new();
12950    let mut current_line = line_prefix.clone();
12951
12952    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12953    let mut current_line_len = line_prefix_len;
12954    for WordBreakToken {
12955        token,
12956        grapheme_len,
12957        is_whitespace,
12958    } in tokenizer
12959    {
12960        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12961            wrapped_text.push_str(current_line.trim_end());
12962            wrapped_text.push('\n');
12963            current_line.truncate(line_prefix.len());
12964            current_line_len = line_prefix_len;
12965            if !is_whitespace {
12966                current_line.push_str(token);
12967                current_line_len += grapheme_len;
12968            }
12969        } else if !is_whitespace {
12970            current_line.push_str(token);
12971            current_line_len += grapheme_len;
12972        } else if current_line_len != line_prefix_len {
12973            current_line.push(' ');
12974            current_line_len += 1;
12975        }
12976    }
12977
12978    if !current_line.is_empty() {
12979        wrapped_text.push_str(&current_line);
12980    }
12981    wrapped_text
12982}
12983
12984#[test]
12985fn test_wrap_with_prefix() {
12986    assert_eq!(
12987        wrap_with_prefix(
12988            "# ".to_string(),
12989            "abcdefg".to_string(),
12990            4,
12991            NonZeroU32::new(4).unwrap()
12992        ),
12993        "# abcdefg"
12994    );
12995    assert_eq!(
12996        wrap_with_prefix(
12997            "".to_string(),
12998            "\thello world".to_string(),
12999            8,
13000            NonZeroU32::new(4).unwrap()
13001        ),
13002        "hello\nworld"
13003    );
13004    assert_eq!(
13005        wrap_with_prefix(
13006            "// ".to_string(),
13007            "xx \nyy zz aa bb cc".to_string(),
13008            12,
13009            NonZeroU32::new(4).unwrap()
13010        ),
13011        "// xx yy zz\n// aa bb cc"
13012    );
13013    assert_eq!(
13014        wrap_with_prefix(
13015            String::new(),
13016            "这是什么 \n 钢笔".to_string(),
13017            3,
13018            NonZeroU32::new(4).unwrap()
13019        ),
13020        "这是什\n么 钢\n"
13021    );
13022}
13023
13024fn hunks_for_selections(
13025    snapshot: &EditorSnapshot,
13026    selections: &[Selection<Point>],
13027) -> Vec<MultiBufferDiffHunk> {
13028    hunks_for_ranges(
13029        selections.iter().map(|selection| selection.range()),
13030        snapshot,
13031    )
13032}
13033
13034pub fn hunks_for_ranges(
13035    ranges: impl Iterator<Item = Range<Point>>,
13036    snapshot: &EditorSnapshot,
13037) -> Vec<MultiBufferDiffHunk> {
13038    let mut hunks = Vec::new();
13039    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13040        HashMap::default();
13041    for query_range in ranges {
13042        let query_rows =
13043            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13044        for hunk in snapshot.diff_map.diff_hunks_in_range(
13045            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13046            &snapshot.buffer_snapshot,
13047        ) {
13048            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13049            // when the caret is just above or just below the deleted hunk.
13050            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13051            let related_to_selection = if allow_adjacent {
13052                hunk.row_range.overlaps(&query_rows)
13053                    || hunk.row_range.start == query_rows.end
13054                    || hunk.row_range.end == query_rows.start
13055            } else {
13056                hunk.row_range.overlaps(&query_rows)
13057            };
13058            if related_to_selection {
13059                if !processed_buffer_rows
13060                    .entry(hunk.buffer_id)
13061                    .or_default()
13062                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13063                {
13064                    continue;
13065                }
13066                hunks.push(hunk);
13067            }
13068        }
13069    }
13070
13071    hunks
13072}
13073
13074pub trait CollaborationHub {
13075    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13076    fn user_participant_indices<'a>(
13077        &self,
13078        cx: &'a AppContext,
13079    ) -> &'a HashMap<u64, ParticipantIndex>;
13080    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13081}
13082
13083impl CollaborationHub for Model<Project> {
13084    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13085        self.read(cx).collaborators()
13086    }
13087
13088    fn user_participant_indices<'a>(
13089        &self,
13090        cx: &'a AppContext,
13091    ) -> &'a HashMap<u64, ParticipantIndex> {
13092        self.read(cx).user_store().read(cx).participant_indices()
13093    }
13094
13095    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13096        let this = self.read(cx);
13097        let user_ids = this.collaborators().values().map(|c| c.user_id);
13098        this.user_store().read_with(cx, |user_store, cx| {
13099            user_store.participant_names(user_ids, cx)
13100        })
13101    }
13102}
13103
13104pub trait SemanticsProvider {
13105    fn hover(
13106        &self,
13107        buffer: &Model<Buffer>,
13108        position: text::Anchor,
13109        cx: &mut AppContext,
13110    ) -> Option<Task<Vec<project::Hover>>>;
13111
13112    fn inlay_hints(
13113        &self,
13114        buffer_handle: Model<Buffer>,
13115        range: Range<text::Anchor>,
13116        cx: &mut AppContext,
13117    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13118
13119    fn resolve_inlay_hint(
13120        &self,
13121        hint: InlayHint,
13122        buffer_handle: Model<Buffer>,
13123        server_id: LanguageServerId,
13124        cx: &mut AppContext,
13125    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13126
13127    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13128
13129    fn document_highlights(
13130        &self,
13131        buffer: &Model<Buffer>,
13132        position: text::Anchor,
13133        cx: &mut AppContext,
13134    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13135
13136    fn definitions(
13137        &self,
13138        buffer: &Model<Buffer>,
13139        position: text::Anchor,
13140        kind: GotoDefinitionKind,
13141        cx: &mut AppContext,
13142    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13143
13144    fn range_for_rename(
13145        &self,
13146        buffer: &Model<Buffer>,
13147        position: text::Anchor,
13148        cx: &mut AppContext,
13149    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13150
13151    fn perform_rename(
13152        &self,
13153        buffer: &Model<Buffer>,
13154        position: text::Anchor,
13155        new_name: String,
13156        cx: &mut AppContext,
13157    ) -> Option<Task<Result<ProjectTransaction>>>;
13158}
13159
13160pub trait CompletionProvider {
13161    fn completions(
13162        &self,
13163        buffer: &Model<Buffer>,
13164        buffer_position: text::Anchor,
13165        trigger: CompletionContext,
13166        cx: &mut ViewContext<Editor>,
13167    ) -> Task<Result<Vec<Completion>>>;
13168
13169    fn resolve_completions(
13170        &self,
13171        buffer: Model<Buffer>,
13172        completion_indices: Vec<usize>,
13173        completions: Arc<RwLock<Box<[Completion]>>>,
13174        cx: &mut ViewContext<Editor>,
13175    ) -> Task<Result<bool>>;
13176
13177    fn apply_additional_edits_for_completion(
13178        &self,
13179        buffer: Model<Buffer>,
13180        completion: Completion,
13181        push_to_history: bool,
13182        cx: &mut ViewContext<Editor>,
13183    ) -> Task<Result<Option<language::Transaction>>>;
13184
13185    fn is_completion_trigger(
13186        &self,
13187        buffer: &Model<Buffer>,
13188        position: language::Anchor,
13189        text: &str,
13190        trigger_in_words: bool,
13191        cx: &mut ViewContext<Editor>,
13192    ) -> bool;
13193
13194    fn sort_completions(&self) -> bool {
13195        true
13196    }
13197}
13198
13199pub trait CodeActionProvider {
13200    fn code_actions(
13201        &self,
13202        buffer: &Model<Buffer>,
13203        range: Range<text::Anchor>,
13204        cx: &mut WindowContext,
13205    ) -> Task<Result<Vec<CodeAction>>>;
13206
13207    fn apply_code_action(
13208        &self,
13209        buffer_handle: Model<Buffer>,
13210        action: CodeAction,
13211        excerpt_id: ExcerptId,
13212        push_to_history: bool,
13213        cx: &mut WindowContext,
13214    ) -> Task<Result<ProjectTransaction>>;
13215}
13216
13217impl CodeActionProvider for Model<Project> {
13218    fn code_actions(
13219        &self,
13220        buffer: &Model<Buffer>,
13221        range: Range<text::Anchor>,
13222        cx: &mut WindowContext,
13223    ) -> Task<Result<Vec<CodeAction>>> {
13224        self.update(cx, |project, cx| {
13225            project.code_actions(buffer, range, None, cx)
13226        })
13227    }
13228
13229    fn apply_code_action(
13230        &self,
13231        buffer_handle: Model<Buffer>,
13232        action: CodeAction,
13233        _excerpt_id: ExcerptId,
13234        push_to_history: bool,
13235        cx: &mut WindowContext,
13236    ) -> Task<Result<ProjectTransaction>> {
13237        self.update(cx, |project, cx| {
13238            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13239        })
13240    }
13241}
13242
13243fn snippet_completions(
13244    project: &Project,
13245    buffer: &Model<Buffer>,
13246    buffer_position: text::Anchor,
13247    cx: &mut AppContext,
13248) -> Task<Result<Vec<Completion>>> {
13249    let language = buffer.read(cx).language_at(buffer_position);
13250    let language_name = language.as_ref().map(|language| language.lsp_id());
13251    let snippet_store = project.snippets().read(cx);
13252    let snippets = snippet_store.snippets_for(language_name, cx);
13253
13254    if snippets.is_empty() {
13255        return Task::ready(Ok(vec![]));
13256    }
13257    let snapshot = buffer.read(cx).text_snapshot();
13258    let chars: String = snapshot
13259        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13260        .collect();
13261
13262    let scope = language.map(|language| language.default_scope());
13263    let executor = cx.background_executor().clone();
13264
13265    cx.background_executor().spawn(async move {
13266        let classifier = CharClassifier::new(scope).for_completion(true);
13267        let mut last_word = chars
13268            .chars()
13269            .take_while(|c| classifier.is_word(*c))
13270            .collect::<String>();
13271        last_word = last_word.chars().rev().collect();
13272
13273        if last_word.is_empty() {
13274            return Ok(vec![]);
13275        }
13276
13277        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13278        let to_lsp = |point: &text::Anchor| {
13279            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13280            point_to_lsp(end)
13281        };
13282        let lsp_end = to_lsp(&buffer_position);
13283
13284        let candidates = snippets
13285            .iter()
13286            .enumerate()
13287            .flat_map(|(ix, snippet)| {
13288                snippet
13289                    .prefix
13290                    .iter()
13291                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13292            })
13293            .collect::<Vec<StringMatchCandidate>>();
13294
13295        let mut matches = fuzzy::match_strings(
13296            &candidates,
13297            &last_word,
13298            last_word.chars().any(|c| c.is_uppercase()),
13299            100,
13300            &Default::default(),
13301            executor,
13302        )
13303        .await;
13304
13305        // Remove all candidates where the query's start does not match the start of any word in the candidate
13306        if let Some(query_start) = last_word.chars().next() {
13307            matches.retain(|string_match| {
13308                split_words(&string_match.string).any(|word| {
13309                    // Check that the first codepoint of the word as lowercase matches the first
13310                    // codepoint of the query as lowercase
13311                    word.chars()
13312                        .flat_map(|codepoint| codepoint.to_lowercase())
13313                        .zip(query_start.to_lowercase())
13314                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13315                })
13316            });
13317        }
13318
13319        let matched_strings = matches
13320            .into_iter()
13321            .map(|m| m.string)
13322            .collect::<HashSet<_>>();
13323
13324        let result: Vec<Completion> = snippets
13325            .into_iter()
13326            .filter_map(|snippet| {
13327                let matching_prefix = snippet
13328                    .prefix
13329                    .iter()
13330                    .find(|prefix| matched_strings.contains(*prefix))?;
13331                let start = as_offset - last_word.len();
13332                let start = snapshot.anchor_before(start);
13333                let range = start..buffer_position;
13334                let lsp_start = to_lsp(&start);
13335                let lsp_range = lsp::Range {
13336                    start: lsp_start,
13337                    end: lsp_end,
13338                };
13339                Some(Completion {
13340                    old_range: range,
13341                    new_text: snippet.body.clone(),
13342                    label: CodeLabel {
13343                        text: matching_prefix.clone(),
13344                        runs: vec![],
13345                        filter_range: 0..matching_prefix.len(),
13346                    },
13347                    server_id: LanguageServerId(usize::MAX),
13348                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13349                    lsp_completion: lsp::CompletionItem {
13350                        label: snippet.prefix.first().unwrap().clone(),
13351                        kind: Some(CompletionItemKind::SNIPPET),
13352                        label_details: snippet.description.as_ref().map(|description| {
13353                            lsp::CompletionItemLabelDetails {
13354                                detail: Some(description.clone()),
13355                                description: None,
13356                            }
13357                        }),
13358                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13359                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13360                            lsp::InsertReplaceEdit {
13361                                new_text: snippet.body.clone(),
13362                                insert: lsp_range,
13363                                replace: lsp_range,
13364                            },
13365                        )),
13366                        filter_text: Some(snippet.body.clone()),
13367                        sort_text: Some(char::MAX.to_string()),
13368                        ..Default::default()
13369                    },
13370                    confirm: None,
13371                })
13372            })
13373            .collect();
13374
13375        Ok(result)
13376    })
13377}
13378
13379impl CompletionProvider for Model<Project> {
13380    fn completions(
13381        &self,
13382        buffer: &Model<Buffer>,
13383        buffer_position: text::Anchor,
13384        options: CompletionContext,
13385        cx: &mut ViewContext<Editor>,
13386    ) -> Task<Result<Vec<Completion>>> {
13387        self.update(cx, |project, cx| {
13388            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13389            let project_completions = project.completions(buffer, buffer_position, options, cx);
13390            cx.background_executor().spawn(async move {
13391                let mut completions = project_completions.await?;
13392                let snippets_completions = snippets.await?;
13393                completions.extend(snippets_completions);
13394                Ok(completions)
13395            })
13396        })
13397    }
13398
13399    fn resolve_completions(
13400        &self,
13401        buffer: Model<Buffer>,
13402        completion_indices: Vec<usize>,
13403        completions: Arc<RwLock<Box<[Completion]>>>,
13404        cx: &mut ViewContext<Editor>,
13405    ) -> Task<Result<bool>> {
13406        self.update(cx, |project, cx| {
13407            project.resolve_completions(buffer, completion_indices, completions, cx)
13408        })
13409    }
13410
13411    fn apply_additional_edits_for_completion(
13412        &self,
13413        buffer: Model<Buffer>,
13414        completion: Completion,
13415        push_to_history: bool,
13416        cx: &mut ViewContext<Editor>,
13417    ) -> Task<Result<Option<language::Transaction>>> {
13418        self.update(cx, |project, cx| {
13419            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13420        })
13421    }
13422
13423    fn is_completion_trigger(
13424        &self,
13425        buffer: &Model<Buffer>,
13426        position: language::Anchor,
13427        text: &str,
13428        trigger_in_words: bool,
13429        cx: &mut ViewContext<Editor>,
13430    ) -> bool {
13431        let mut chars = text.chars();
13432        let char = if let Some(char) = chars.next() {
13433            char
13434        } else {
13435            return false;
13436        };
13437        if chars.next().is_some() {
13438            return false;
13439        }
13440
13441        let buffer = buffer.read(cx);
13442        let snapshot = buffer.snapshot();
13443        if !snapshot.settings_at(position, cx).show_completions_on_input {
13444            return false;
13445        }
13446        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13447        if trigger_in_words && classifier.is_word(char) {
13448            return true;
13449        }
13450
13451        buffer.completion_triggers().contains(text)
13452    }
13453}
13454
13455impl SemanticsProvider for Model<Project> {
13456    fn hover(
13457        &self,
13458        buffer: &Model<Buffer>,
13459        position: text::Anchor,
13460        cx: &mut AppContext,
13461    ) -> Option<Task<Vec<project::Hover>>> {
13462        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13463    }
13464
13465    fn document_highlights(
13466        &self,
13467        buffer: &Model<Buffer>,
13468        position: text::Anchor,
13469        cx: &mut AppContext,
13470    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13471        Some(self.update(cx, |project, cx| {
13472            project.document_highlights(buffer, position, cx)
13473        }))
13474    }
13475
13476    fn definitions(
13477        &self,
13478        buffer: &Model<Buffer>,
13479        position: text::Anchor,
13480        kind: GotoDefinitionKind,
13481        cx: &mut AppContext,
13482    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13483        Some(self.update(cx, |project, cx| match kind {
13484            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13485            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13486            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13487            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13488        }))
13489    }
13490
13491    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13492        // TODO: make this work for remote projects
13493        self.read(cx)
13494            .language_servers_for_local_buffer(buffer.read(cx), cx)
13495            .any(
13496                |(_, server)| match server.capabilities().inlay_hint_provider {
13497                    Some(lsp::OneOf::Left(enabled)) => enabled,
13498                    Some(lsp::OneOf::Right(_)) => true,
13499                    None => false,
13500                },
13501            )
13502    }
13503
13504    fn inlay_hints(
13505        &self,
13506        buffer_handle: Model<Buffer>,
13507        range: Range<text::Anchor>,
13508        cx: &mut AppContext,
13509    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13510        Some(self.update(cx, |project, cx| {
13511            project.inlay_hints(buffer_handle, range, cx)
13512        }))
13513    }
13514
13515    fn resolve_inlay_hint(
13516        &self,
13517        hint: InlayHint,
13518        buffer_handle: Model<Buffer>,
13519        server_id: LanguageServerId,
13520        cx: &mut AppContext,
13521    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13522        Some(self.update(cx, |project, cx| {
13523            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13524        }))
13525    }
13526
13527    fn range_for_rename(
13528        &self,
13529        buffer: &Model<Buffer>,
13530        position: text::Anchor,
13531        cx: &mut AppContext,
13532    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13533        Some(self.update(cx, |project, cx| {
13534            project.prepare_rename(buffer.clone(), position, cx)
13535        }))
13536    }
13537
13538    fn perform_rename(
13539        &self,
13540        buffer: &Model<Buffer>,
13541        position: text::Anchor,
13542        new_name: String,
13543        cx: &mut AppContext,
13544    ) -> Option<Task<Result<ProjectTransaction>>> {
13545        Some(self.update(cx, |project, cx| {
13546            project.perform_rename(buffer.clone(), position, new_name, cx)
13547        }))
13548    }
13549}
13550
13551fn inlay_hint_settings(
13552    location: Anchor,
13553    snapshot: &MultiBufferSnapshot,
13554    cx: &mut ViewContext<'_, Editor>,
13555) -> InlayHintSettings {
13556    let file = snapshot.file_at(location);
13557    let language = snapshot.language_at(location).map(|l| l.name());
13558    language_settings(language, file, cx).inlay_hints
13559}
13560
13561fn consume_contiguous_rows(
13562    contiguous_row_selections: &mut Vec<Selection<Point>>,
13563    selection: &Selection<Point>,
13564    display_map: &DisplaySnapshot,
13565    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13566) -> (MultiBufferRow, MultiBufferRow) {
13567    contiguous_row_selections.push(selection.clone());
13568    let start_row = MultiBufferRow(selection.start.row);
13569    let mut end_row = ending_row(selection, display_map);
13570
13571    while let Some(next_selection) = selections.peek() {
13572        if next_selection.start.row <= end_row.0 {
13573            end_row = ending_row(next_selection, display_map);
13574            contiguous_row_selections.push(selections.next().unwrap().clone());
13575        } else {
13576            break;
13577        }
13578    }
13579    (start_row, end_row)
13580}
13581
13582fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13583    if next_selection.end.column > 0 || next_selection.is_empty() {
13584        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13585    } else {
13586        MultiBufferRow(next_selection.end.row)
13587    }
13588}
13589
13590impl EditorSnapshot {
13591    pub fn remote_selections_in_range<'a>(
13592        &'a self,
13593        range: &'a Range<Anchor>,
13594        collaboration_hub: &dyn CollaborationHub,
13595        cx: &'a AppContext,
13596    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13597        let participant_names = collaboration_hub.user_names(cx);
13598        let participant_indices = collaboration_hub.user_participant_indices(cx);
13599        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13600        let collaborators_by_replica_id = collaborators_by_peer_id
13601            .iter()
13602            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13603            .collect::<HashMap<_, _>>();
13604        self.buffer_snapshot
13605            .selections_in_range(range, false)
13606            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13607                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13608                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13609                let user_name = participant_names.get(&collaborator.user_id).cloned();
13610                Some(RemoteSelection {
13611                    replica_id,
13612                    selection,
13613                    cursor_shape,
13614                    line_mode,
13615                    participant_index,
13616                    peer_id: collaborator.peer_id,
13617                    user_name,
13618                })
13619            })
13620    }
13621
13622    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13623        self.display_snapshot.buffer_snapshot.language_at(position)
13624    }
13625
13626    pub fn is_focused(&self) -> bool {
13627        self.is_focused
13628    }
13629
13630    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13631        self.placeholder_text.as_ref()
13632    }
13633
13634    pub fn scroll_position(&self) -> gpui::Point<f32> {
13635        self.scroll_anchor.scroll_position(&self.display_snapshot)
13636    }
13637
13638    fn gutter_dimensions(
13639        &self,
13640        font_id: FontId,
13641        font_size: Pixels,
13642        em_width: Pixels,
13643        em_advance: Pixels,
13644        max_line_number_width: Pixels,
13645        cx: &AppContext,
13646    ) -> GutterDimensions {
13647        if !self.show_gutter {
13648            return GutterDimensions::default();
13649        }
13650        let descent = cx.text_system().descent(font_id, font_size);
13651
13652        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13653            matches!(
13654                ProjectSettings::get_global(cx).git.git_gutter,
13655                Some(GitGutterSetting::TrackedFiles)
13656            )
13657        });
13658        let gutter_settings = EditorSettings::get_global(cx).gutter;
13659        let show_line_numbers = self
13660            .show_line_numbers
13661            .unwrap_or(gutter_settings.line_numbers);
13662        let line_gutter_width = if show_line_numbers {
13663            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13664            let min_width_for_number_on_gutter = em_advance * 4.0;
13665            max_line_number_width.max(min_width_for_number_on_gutter)
13666        } else {
13667            0.0.into()
13668        };
13669
13670        let show_code_actions = self
13671            .show_code_actions
13672            .unwrap_or(gutter_settings.code_actions);
13673
13674        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13675
13676        let git_blame_entries_width =
13677            self.git_blame_gutter_max_author_length
13678                .map(|max_author_length| {
13679                    // Length of the author name, but also space for the commit hash,
13680                    // the spacing and the timestamp.
13681                    let max_char_count = max_author_length
13682                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13683                        + 7 // length of commit sha
13684                        + 14 // length of max relative timestamp ("60 minutes ago")
13685                        + 4; // gaps and margins
13686
13687                    em_advance * max_char_count
13688                });
13689
13690        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13691        left_padding += if show_code_actions || show_runnables {
13692            em_width * 3.0
13693        } else if show_git_gutter && show_line_numbers {
13694            em_width * 2.0
13695        } else if show_git_gutter || show_line_numbers {
13696            em_width
13697        } else {
13698            px(0.)
13699        };
13700
13701        let right_padding = if gutter_settings.folds && show_line_numbers {
13702            em_width * 4.0
13703        } else if gutter_settings.folds {
13704            em_width * 3.0
13705        } else if show_line_numbers {
13706            em_width
13707        } else {
13708            px(0.)
13709        };
13710
13711        GutterDimensions {
13712            left_padding,
13713            right_padding,
13714            width: line_gutter_width + left_padding + right_padding,
13715            margin: -descent,
13716            git_blame_entries_width,
13717        }
13718    }
13719
13720    pub fn render_crease_toggle(
13721        &self,
13722        buffer_row: MultiBufferRow,
13723        row_contains_cursor: bool,
13724        editor: View<Editor>,
13725        cx: &mut WindowContext,
13726    ) -> Option<AnyElement> {
13727        let folded = self.is_line_folded(buffer_row);
13728        let mut is_foldable = false;
13729
13730        if let Some(crease) = self
13731            .crease_snapshot
13732            .query_row(buffer_row, &self.buffer_snapshot)
13733        {
13734            is_foldable = true;
13735            match crease {
13736                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13737                    if let Some(render_toggle) = render_toggle {
13738                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13739                            if folded {
13740                                editor.update(cx, |editor, cx| {
13741                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13742                                });
13743                            } else {
13744                                editor.update(cx, |editor, cx| {
13745                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13746                                });
13747                            }
13748                        });
13749                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13750                    }
13751                }
13752            }
13753        }
13754
13755        is_foldable |= self.starts_indent(buffer_row);
13756
13757        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13758            Some(
13759                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13760                    .selected(folded)
13761                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13762                        if folded {
13763                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13764                        } else {
13765                            this.fold_at(&FoldAt { buffer_row }, cx);
13766                        }
13767                    }))
13768                    .into_any_element(),
13769            )
13770        } else {
13771            None
13772        }
13773    }
13774
13775    pub fn render_crease_trailer(
13776        &self,
13777        buffer_row: MultiBufferRow,
13778        cx: &mut WindowContext,
13779    ) -> Option<AnyElement> {
13780        let folded = self.is_line_folded(buffer_row);
13781        if let Crease::Inline { render_trailer, .. } = self
13782            .crease_snapshot
13783            .query_row(buffer_row, &self.buffer_snapshot)?
13784        {
13785            let render_trailer = render_trailer.as_ref()?;
13786            Some(render_trailer(buffer_row, folded, cx))
13787        } else {
13788            None
13789        }
13790    }
13791}
13792
13793impl Deref for EditorSnapshot {
13794    type Target = DisplaySnapshot;
13795
13796    fn deref(&self) -> &Self::Target {
13797        &self.display_snapshot
13798    }
13799}
13800
13801#[derive(Clone, Debug, PartialEq, Eq)]
13802pub enum EditorEvent {
13803    InputIgnored {
13804        text: Arc<str>,
13805    },
13806    InputHandled {
13807        utf16_range_to_replace: Option<Range<isize>>,
13808        text: Arc<str>,
13809    },
13810    ExcerptsAdded {
13811        buffer: Model<Buffer>,
13812        predecessor: ExcerptId,
13813        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13814    },
13815    ExcerptsRemoved {
13816        ids: Vec<ExcerptId>,
13817    },
13818    ExcerptsEdited {
13819        ids: Vec<ExcerptId>,
13820    },
13821    ExcerptsExpanded {
13822        ids: Vec<ExcerptId>,
13823    },
13824    BufferEdited,
13825    Edited {
13826        transaction_id: clock::Lamport,
13827    },
13828    Reparsed(BufferId),
13829    Focused,
13830    FocusedIn,
13831    Blurred,
13832    DirtyChanged,
13833    Saved,
13834    TitleChanged,
13835    DiffBaseChanged,
13836    SelectionsChanged {
13837        local: bool,
13838    },
13839    ScrollPositionChanged {
13840        local: bool,
13841        autoscroll: bool,
13842    },
13843    Closed,
13844    TransactionUndone {
13845        transaction_id: clock::Lamport,
13846    },
13847    TransactionBegun {
13848        transaction_id: clock::Lamport,
13849    },
13850    Reloaded,
13851    CursorShapeChanged,
13852}
13853
13854impl EventEmitter<EditorEvent> for Editor {}
13855
13856impl FocusableView for Editor {
13857    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13858        self.focus_handle.clone()
13859    }
13860}
13861
13862impl Render for Editor {
13863    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13864        let settings = ThemeSettings::get_global(cx);
13865
13866        let mut text_style = match self.mode {
13867            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13868                color: cx.theme().colors().editor_foreground,
13869                font_family: settings.ui_font.family.clone(),
13870                font_features: settings.ui_font.features.clone(),
13871                font_fallbacks: settings.ui_font.fallbacks.clone(),
13872                font_size: rems(0.875).into(),
13873                font_weight: settings.ui_font.weight,
13874                line_height: relative(settings.buffer_line_height.value()),
13875                ..Default::default()
13876            },
13877            EditorMode::Full => TextStyle {
13878                color: cx.theme().colors().editor_foreground,
13879                font_family: settings.buffer_font.family.clone(),
13880                font_features: settings.buffer_font.features.clone(),
13881                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13882                font_size: settings.buffer_font_size(cx).into(),
13883                font_weight: settings.buffer_font.weight,
13884                line_height: relative(settings.buffer_line_height.value()),
13885                ..Default::default()
13886            },
13887        };
13888        if let Some(text_style_refinement) = &self.text_style_refinement {
13889            text_style.refine(text_style_refinement)
13890        }
13891
13892        let background = match self.mode {
13893            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13894            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13895            EditorMode::Full => cx.theme().colors().editor_background,
13896        };
13897
13898        EditorElement::new(
13899            cx.view(),
13900            EditorStyle {
13901                background,
13902                local_player: cx.theme().players().local(),
13903                text: text_style,
13904                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13905                syntax: cx.theme().syntax().clone(),
13906                status: cx.theme().status().clone(),
13907                inlay_hints_style: make_inlay_hints_style(cx),
13908                suggestions_style: HighlightStyle {
13909                    color: Some(cx.theme().status().predictive),
13910                    ..HighlightStyle::default()
13911                },
13912                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13913            },
13914        )
13915    }
13916}
13917
13918impl ViewInputHandler for Editor {
13919    fn text_for_range(
13920        &mut self,
13921        range_utf16: Range<usize>,
13922        adjusted_range: &mut Option<Range<usize>>,
13923        cx: &mut ViewContext<Self>,
13924    ) -> Option<String> {
13925        let snapshot = self.buffer.read(cx).read(cx);
13926        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13927        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13928        if (start.0..end.0) != range_utf16 {
13929            adjusted_range.replace(start.0..end.0);
13930        }
13931        Some(snapshot.text_for_range(start..end).collect())
13932    }
13933
13934    fn selected_text_range(
13935        &mut self,
13936        ignore_disabled_input: bool,
13937        cx: &mut ViewContext<Self>,
13938    ) -> Option<UTF16Selection> {
13939        // Prevent the IME menu from appearing when holding down an alphabetic key
13940        // while input is disabled.
13941        if !ignore_disabled_input && !self.input_enabled {
13942            return None;
13943        }
13944
13945        let selection = self.selections.newest::<OffsetUtf16>(cx);
13946        let range = selection.range();
13947
13948        Some(UTF16Selection {
13949            range: range.start.0..range.end.0,
13950            reversed: selection.reversed,
13951        })
13952    }
13953
13954    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13955        let snapshot = self.buffer.read(cx).read(cx);
13956        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13957        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13958    }
13959
13960    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13961        self.clear_highlights::<InputComposition>(cx);
13962        self.ime_transaction.take();
13963    }
13964
13965    fn replace_text_in_range(
13966        &mut self,
13967        range_utf16: Option<Range<usize>>,
13968        text: &str,
13969        cx: &mut ViewContext<Self>,
13970    ) {
13971        if !self.input_enabled {
13972            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13973            return;
13974        }
13975
13976        self.transact(cx, |this, cx| {
13977            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13978                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13979                Some(this.selection_replacement_ranges(range_utf16, cx))
13980            } else {
13981                this.marked_text_ranges(cx)
13982            };
13983
13984            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13985                let newest_selection_id = this.selections.newest_anchor().id;
13986                this.selections
13987                    .all::<OffsetUtf16>(cx)
13988                    .iter()
13989                    .zip(ranges_to_replace.iter())
13990                    .find_map(|(selection, range)| {
13991                        if selection.id == newest_selection_id {
13992                            Some(
13993                                (range.start.0 as isize - selection.head().0 as isize)
13994                                    ..(range.end.0 as isize - selection.head().0 as isize),
13995                            )
13996                        } else {
13997                            None
13998                        }
13999                    })
14000            });
14001
14002            cx.emit(EditorEvent::InputHandled {
14003                utf16_range_to_replace: range_to_replace,
14004                text: text.into(),
14005            });
14006
14007            if let Some(new_selected_ranges) = new_selected_ranges {
14008                this.change_selections(None, cx, |selections| {
14009                    selections.select_ranges(new_selected_ranges)
14010                });
14011                this.backspace(&Default::default(), cx);
14012            }
14013
14014            this.handle_input(text, cx);
14015        });
14016
14017        if let Some(transaction) = self.ime_transaction {
14018            self.buffer.update(cx, |buffer, cx| {
14019                buffer.group_until_transaction(transaction, cx);
14020            });
14021        }
14022
14023        self.unmark_text(cx);
14024    }
14025
14026    fn replace_and_mark_text_in_range(
14027        &mut self,
14028        range_utf16: Option<Range<usize>>,
14029        text: &str,
14030        new_selected_range_utf16: Option<Range<usize>>,
14031        cx: &mut ViewContext<Self>,
14032    ) {
14033        if !self.input_enabled {
14034            return;
14035        }
14036
14037        let transaction = self.transact(cx, |this, cx| {
14038            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14039                let snapshot = this.buffer.read(cx).read(cx);
14040                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14041                    for marked_range in &mut marked_ranges {
14042                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14043                        marked_range.start.0 += relative_range_utf16.start;
14044                        marked_range.start =
14045                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14046                        marked_range.end =
14047                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14048                    }
14049                }
14050                Some(marked_ranges)
14051            } else if let Some(range_utf16) = range_utf16 {
14052                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14053                Some(this.selection_replacement_ranges(range_utf16, cx))
14054            } else {
14055                None
14056            };
14057
14058            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14059                let newest_selection_id = this.selections.newest_anchor().id;
14060                this.selections
14061                    .all::<OffsetUtf16>(cx)
14062                    .iter()
14063                    .zip(ranges_to_replace.iter())
14064                    .find_map(|(selection, range)| {
14065                        if selection.id == newest_selection_id {
14066                            Some(
14067                                (range.start.0 as isize - selection.head().0 as isize)
14068                                    ..(range.end.0 as isize - selection.head().0 as isize),
14069                            )
14070                        } else {
14071                            None
14072                        }
14073                    })
14074            });
14075
14076            cx.emit(EditorEvent::InputHandled {
14077                utf16_range_to_replace: range_to_replace,
14078                text: text.into(),
14079            });
14080
14081            if let Some(ranges) = ranges_to_replace {
14082                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14083            }
14084
14085            let marked_ranges = {
14086                let snapshot = this.buffer.read(cx).read(cx);
14087                this.selections
14088                    .disjoint_anchors()
14089                    .iter()
14090                    .map(|selection| {
14091                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14092                    })
14093                    .collect::<Vec<_>>()
14094            };
14095
14096            if text.is_empty() {
14097                this.unmark_text(cx);
14098            } else {
14099                this.highlight_text::<InputComposition>(
14100                    marked_ranges.clone(),
14101                    HighlightStyle {
14102                        underline: Some(UnderlineStyle {
14103                            thickness: px(1.),
14104                            color: None,
14105                            wavy: false,
14106                        }),
14107                        ..Default::default()
14108                    },
14109                    cx,
14110                );
14111            }
14112
14113            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14114            let use_autoclose = this.use_autoclose;
14115            let use_auto_surround = this.use_auto_surround;
14116            this.set_use_autoclose(false);
14117            this.set_use_auto_surround(false);
14118            this.handle_input(text, cx);
14119            this.set_use_autoclose(use_autoclose);
14120            this.set_use_auto_surround(use_auto_surround);
14121
14122            if let Some(new_selected_range) = new_selected_range_utf16 {
14123                let snapshot = this.buffer.read(cx).read(cx);
14124                let new_selected_ranges = marked_ranges
14125                    .into_iter()
14126                    .map(|marked_range| {
14127                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14128                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14129                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14130                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14131                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14132                    })
14133                    .collect::<Vec<_>>();
14134
14135                drop(snapshot);
14136                this.change_selections(None, cx, |selections| {
14137                    selections.select_ranges(new_selected_ranges)
14138                });
14139            }
14140        });
14141
14142        self.ime_transaction = self.ime_transaction.or(transaction);
14143        if let Some(transaction) = self.ime_transaction {
14144            self.buffer.update(cx, |buffer, cx| {
14145                buffer.group_until_transaction(transaction, cx);
14146            });
14147        }
14148
14149        if self.text_highlights::<InputComposition>(cx).is_none() {
14150            self.ime_transaction.take();
14151        }
14152    }
14153
14154    fn bounds_for_range(
14155        &mut self,
14156        range_utf16: Range<usize>,
14157        element_bounds: gpui::Bounds<Pixels>,
14158        cx: &mut ViewContext<Self>,
14159    ) -> Option<gpui::Bounds<Pixels>> {
14160        let text_layout_details = self.text_layout_details(cx);
14161        let gpui::Point {
14162            x: em_width,
14163            y: line_height,
14164        } = self.character_size(cx);
14165
14166        let snapshot = self.snapshot(cx);
14167        let scroll_position = snapshot.scroll_position();
14168        let scroll_left = scroll_position.x * em_width;
14169
14170        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14171        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14172            + self.gutter_dimensions.width
14173            + self.gutter_dimensions.margin;
14174        let y = line_height * (start.row().as_f32() - scroll_position.y);
14175
14176        Some(Bounds {
14177            origin: element_bounds.origin + point(x, y),
14178            size: size(em_width, line_height),
14179        })
14180    }
14181}
14182
14183trait SelectionExt {
14184    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14185    fn spanned_rows(
14186        &self,
14187        include_end_if_at_line_start: bool,
14188        map: &DisplaySnapshot,
14189    ) -> Range<MultiBufferRow>;
14190}
14191
14192impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14193    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14194        let start = self
14195            .start
14196            .to_point(&map.buffer_snapshot)
14197            .to_display_point(map);
14198        let end = self
14199            .end
14200            .to_point(&map.buffer_snapshot)
14201            .to_display_point(map);
14202        if self.reversed {
14203            end..start
14204        } else {
14205            start..end
14206        }
14207    }
14208
14209    fn spanned_rows(
14210        &self,
14211        include_end_if_at_line_start: bool,
14212        map: &DisplaySnapshot,
14213    ) -> Range<MultiBufferRow> {
14214        let start = self.start.to_point(&map.buffer_snapshot);
14215        let mut end = self.end.to_point(&map.buffer_snapshot);
14216        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14217            end.row -= 1;
14218        }
14219
14220        let buffer_start = map.prev_line_boundary(start).0;
14221        let buffer_end = map.next_line_boundary(end).0;
14222        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14223    }
14224}
14225
14226impl<T: InvalidationRegion> InvalidationStack<T> {
14227    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14228    where
14229        S: Clone + ToOffset,
14230    {
14231        while let Some(region) = self.last() {
14232            let all_selections_inside_invalidation_ranges =
14233                if selections.len() == region.ranges().len() {
14234                    selections
14235                        .iter()
14236                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14237                        .all(|(selection, invalidation_range)| {
14238                            let head = selection.head().to_offset(buffer);
14239                            invalidation_range.start <= head && invalidation_range.end >= head
14240                        })
14241                } else {
14242                    false
14243                };
14244
14245            if all_selections_inside_invalidation_ranges {
14246                break;
14247            } else {
14248                self.pop();
14249            }
14250        }
14251    }
14252}
14253
14254impl<T> Default for InvalidationStack<T> {
14255    fn default() -> Self {
14256        Self(Default::default())
14257    }
14258}
14259
14260impl<T> Deref for InvalidationStack<T> {
14261    type Target = Vec<T>;
14262
14263    fn deref(&self) -> &Self::Target {
14264        &self.0
14265    }
14266}
14267
14268impl<T> DerefMut for InvalidationStack<T> {
14269    fn deref_mut(&mut self) -> &mut Self::Target {
14270        &mut self.0
14271    }
14272}
14273
14274impl InvalidationRegion for SnippetState {
14275    fn ranges(&self) -> &[Range<Anchor>] {
14276        &self.ranges[self.active_index]
14277    }
14278}
14279
14280pub fn diagnostic_block_renderer(
14281    diagnostic: Diagnostic,
14282    max_message_rows: Option<u8>,
14283    allow_closing: bool,
14284    _is_valid: bool,
14285) -> RenderBlock {
14286    let (text_without_backticks, code_ranges) =
14287        highlight_diagnostic_message(&diagnostic, max_message_rows);
14288
14289    Arc::new(move |cx: &mut BlockContext| {
14290        let group_id: SharedString = cx.block_id.to_string().into();
14291
14292        let mut text_style = cx.text_style().clone();
14293        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14294        let theme_settings = ThemeSettings::get_global(cx);
14295        text_style.font_family = theme_settings.buffer_font.family.clone();
14296        text_style.font_style = theme_settings.buffer_font.style;
14297        text_style.font_features = theme_settings.buffer_font.features.clone();
14298        text_style.font_weight = theme_settings.buffer_font.weight;
14299
14300        let multi_line_diagnostic = diagnostic.message.contains('\n');
14301
14302        let buttons = |diagnostic: &Diagnostic| {
14303            if multi_line_diagnostic {
14304                v_flex()
14305            } else {
14306                h_flex()
14307            }
14308            .when(allow_closing, |div| {
14309                div.children(diagnostic.is_primary.then(|| {
14310                    IconButton::new("close-block", IconName::XCircle)
14311                        .icon_color(Color::Muted)
14312                        .size(ButtonSize::Compact)
14313                        .style(ButtonStyle::Transparent)
14314                        .visible_on_hover(group_id.clone())
14315                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14316                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14317                }))
14318            })
14319            .child(
14320                IconButton::new("copy-block", IconName::Copy)
14321                    .icon_color(Color::Muted)
14322                    .size(ButtonSize::Compact)
14323                    .style(ButtonStyle::Transparent)
14324                    .visible_on_hover(group_id.clone())
14325                    .on_click({
14326                        let message = diagnostic.message.clone();
14327                        move |_click, cx| {
14328                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14329                        }
14330                    })
14331                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14332            )
14333        };
14334
14335        let icon_size = buttons(&diagnostic)
14336            .into_any_element()
14337            .layout_as_root(AvailableSpace::min_size(), cx);
14338
14339        h_flex()
14340            .id(cx.block_id)
14341            .group(group_id.clone())
14342            .relative()
14343            .size_full()
14344            .block_mouse_down()
14345            .pl(cx.gutter_dimensions.width)
14346            .w(cx.max_width - cx.gutter_dimensions.full_width())
14347            .child(
14348                div()
14349                    .flex()
14350                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14351                    .flex_shrink(),
14352            )
14353            .child(buttons(&diagnostic))
14354            .child(div().flex().flex_shrink_0().child(
14355                StyledText::new(text_without_backticks.clone()).with_highlights(
14356                    &text_style,
14357                    code_ranges.iter().map(|range| {
14358                        (
14359                            range.clone(),
14360                            HighlightStyle {
14361                                font_weight: Some(FontWeight::BOLD),
14362                                ..Default::default()
14363                            },
14364                        )
14365                    }),
14366                ),
14367            ))
14368            .into_any_element()
14369    })
14370}
14371
14372pub fn highlight_diagnostic_message(
14373    diagnostic: &Diagnostic,
14374    mut max_message_rows: Option<u8>,
14375) -> (SharedString, Vec<Range<usize>>) {
14376    let mut text_without_backticks = String::new();
14377    let mut code_ranges = Vec::new();
14378
14379    if let Some(source) = &diagnostic.source {
14380        text_without_backticks.push_str(source);
14381        code_ranges.push(0..source.len());
14382        text_without_backticks.push_str(": ");
14383    }
14384
14385    let mut prev_offset = 0;
14386    let mut in_code_block = false;
14387    let has_row_limit = max_message_rows.is_some();
14388    let mut newline_indices = diagnostic
14389        .message
14390        .match_indices('\n')
14391        .filter(|_| has_row_limit)
14392        .map(|(ix, _)| ix)
14393        .fuse()
14394        .peekable();
14395
14396    for (quote_ix, _) in diagnostic
14397        .message
14398        .match_indices('`')
14399        .chain([(diagnostic.message.len(), "")])
14400    {
14401        let mut first_newline_ix = None;
14402        let mut last_newline_ix = None;
14403        while let Some(newline_ix) = newline_indices.peek() {
14404            if *newline_ix < quote_ix {
14405                if first_newline_ix.is_none() {
14406                    first_newline_ix = Some(*newline_ix);
14407                }
14408                last_newline_ix = Some(*newline_ix);
14409
14410                if let Some(rows_left) = &mut max_message_rows {
14411                    if *rows_left == 0 {
14412                        break;
14413                    } else {
14414                        *rows_left -= 1;
14415                    }
14416                }
14417                let _ = newline_indices.next();
14418            } else {
14419                break;
14420            }
14421        }
14422        let prev_len = text_without_backticks.len();
14423        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14424        text_without_backticks.push_str(new_text);
14425        if in_code_block {
14426            code_ranges.push(prev_len..text_without_backticks.len());
14427        }
14428        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14429        in_code_block = !in_code_block;
14430        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14431            text_without_backticks.push_str("...");
14432            break;
14433        }
14434    }
14435
14436    (text_without_backticks.into(), code_ranges)
14437}
14438
14439fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14440    match severity {
14441        DiagnosticSeverity::ERROR => colors.error,
14442        DiagnosticSeverity::WARNING => colors.warning,
14443        DiagnosticSeverity::INFORMATION => colors.info,
14444        DiagnosticSeverity::HINT => colors.info,
14445        _ => colors.ignored,
14446    }
14447}
14448
14449pub fn styled_runs_for_code_label<'a>(
14450    label: &'a CodeLabel,
14451    syntax_theme: &'a theme::SyntaxTheme,
14452) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14453    let fade_out = HighlightStyle {
14454        fade_out: Some(0.35),
14455        ..Default::default()
14456    };
14457
14458    let mut prev_end = label.filter_range.end;
14459    label
14460        .runs
14461        .iter()
14462        .enumerate()
14463        .flat_map(move |(ix, (range, highlight_id))| {
14464            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14465                style
14466            } else {
14467                return Default::default();
14468            };
14469            let mut muted_style = style;
14470            muted_style.highlight(fade_out);
14471
14472            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14473            if range.start >= label.filter_range.end {
14474                if range.start > prev_end {
14475                    runs.push((prev_end..range.start, fade_out));
14476                }
14477                runs.push((range.clone(), muted_style));
14478            } else if range.end <= label.filter_range.end {
14479                runs.push((range.clone(), style));
14480            } else {
14481                runs.push((range.start..label.filter_range.end, style));
14482                runs.push((label.filter_range.end..range.end, muted_style));
14483            }
14484            prev_end = cmp::max(prev_end, range.end);
14485
14486            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14487                runs.push((prev_end..label.text.len(), fade_out));
14488            }
14489
14490            runs
14491        })
14492}
14493
14494pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14495    let mut prev_index = 0;
14496    let mut prev_codepoint: Option<char> = None;
14497    text.char_indices()
14498        .chain([(text.len(), '\0')])
14499        .filter_map(move |(index, codepoint)| {
14500            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14501            let is_boundary = index == text.len()
14502                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14503                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14504            if is_boundary {
14505                let chunk = &text[prev_index..index];
14506                prev_index = index;
14507                Some(chunk)
14508            } else {
14509                None
14510            }
14511        })
14512}
14513
14514pub trait RangeToAnchorExt: Sized {
14515    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14516
14517    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14518        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14519        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14520    }
14521}
14522
14523impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14524    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14525        let start_offset = self.start.to_offset(snapshot);
14526        let end_offset = self.end.to_offset(snapshot);
14527        if start_offset == end_offset {
14528            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14529        } else {
14530            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14531        }
14532    }
14533}
14534
14535pub trait RowExt {
14536    fn as_f32(&self) -> f32;
14537
14538    fn next_row(&self) -> Self;
14539
14540    fn previous_row(&self) -> Self;
14541
14542    fn minus(&self, other: Self) -> u32;
14543}
14544
14545impl RowExt for DisplayRow {
14546    fn as_f32(&self) -> f32 {
14547        self.0 as f32
14548    }
14549
14550    fn next_row(&self) -> Self {
14551        Self(self.0 + 1)
14552    }
14553
14554    fn previous_row(&self) -> Self {
14555        Self(self.0.saturating_sub(1))
14556    }
14557
14558    fn minus(&self, other: Self) -> u32 {
14559        self.0 - other.0
14560    }
14561}
14562
14563impl RowExt for MultiBufferRow {
14564    fn as_f32(&self) -> f32 {
14565        self.0 as f32
14566    }
14567
14568    fn next_row(&self) -> Self {
14569        Self(self.0 + 1)
14570    }
14571
14572    fn previous_row(&self) -> Self {
14573        Self(self.0.saturating_sub(1))
14574    }
14575
14576    fn minus(&self, other: Self) -> u32 {
14577        self.0 - other.0
14578    }
14579}
14580
14581trait RowRangeExt {
14582    type Row;
14583
14584    fn len(&self) -> usize;
14585
14586    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14587}
14588
14589impl RowRangeExt for Range<MultiBufferRow> {
14590    type Row = MultiBufferRow;
14591
14592    fn len(&self) -> usize {
14593        (self.end.0 - self.start.0) as usize
14594    }
14595
14596    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14597        (self.start.0..self.end.0).map(MultiBufferRow)
14598    }
14599}
14600
14601impl RowRangeExt for Range<DisplayRow> {
14602    type Row = DisplayRow;
14603
14604    fn len(&self) -> usize {
14605        (self.end.0 - self.start.0) as usize
14606    }
14607
14608    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14609        (self.start.0..self.end.0).map(DisplayRow)
14610    }
14611}
14612
14613fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14614    if hunk.diff_base_byte_range.is_empty() {
14615        DiffHunkStatus::Added
14616    } else if hunk.row_range.is_empty() {
14617        DiffHunkStatus::Removed
14618    } else {
14619        DiffHunkStatus::Modified
14620    }
14621}
14622
14623/// If select range has more than one line, we
14624/// just point the cursor to range.start.
14625fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14626    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14627        range
14628    } else {
14629        range.start..range.start
14630    }
14631}
14632
14633pub struct KillRing(ClipboardItem);
14634impl Global for KillRing {}
14635
14636const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);