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;
  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 position = self.selections.newest_anchor().head();
 9297        let Some((buffer, buffer_position)) =
 9298            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9299        else {
 9300            return;
 9301        };
 9302
 9303        cx.spawn(|editor, mut cx| async move {
 9304            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9305                editor.update(&mut cx, |_, cx| {
 9306                    cx.open_url(&url);
 9307                })
 9308            } else {
 9309                Ok(())
 9310            }
 9311        })
 9312        .detach();
 9313    }
 9314
 9315    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9316        let Some(workspace) = self.workspace() else {
 9317            return;
 9318        };
 9319
 9320        let position = self.selections.newest_anchor().head();
 9321
 9322        let Some((buffer, buffer_position)) =
 9323            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9324        else {
 9325            return;
 9326        };
 9327
 9328        let project = self.project.clone();
 9329
 9330        cx.spawn(|_, mut cx| async move {
 9331            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9332
 9333            if let Some((_, path)) = result {
 9334                workspace
 9335                    .update(&mut cx, |workspace, cx| {
 9336                        workspace.open_resolved_path(path, cx)
 9337                    })?
 9338                    .await?;
 9339            }
 9340            anyhow::Ok(())
 9341        })
 9342        .detach();
 9343    }
 9344
 9345    pub(crate) fn navigate_to_hover_links(
 9346        &mut self,
 9347        kind: Option<GotoDefinitionKind>,
 9348        mut definitions: Vec<HoverLink>,
 9349        split: bool,
 9350        cx: &mut ViewContext<Editor>,
 9351    ) -> Task<Result<Navigated>> {
 9352        // If there is one definition, just open it directly
 9353        if definitions.len() == 1 {
 9354            let definition = definitions.pop().unwrap();
 9355
 9356            enum TargetTaskResult {
 9357                Location(Option<Location>),
 9358                AlreadyNavigated,
 9359            }
 9360
 9361            let target_task = match definition {
 9362                HoverLink::Text(link) => {
 9363                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9364                }
 9365                HoverLink::InlayHint(lsp_location, server_id) => {
 9366                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9367                    cx.background_executor().spawn(async move {
 9368                        let location = computation.await?;
 9369                        Ok(TargetTaskResult::Location(location))
 9370                    })
 9371                }
 9372                HoverLink::Url(url) => {
 9373                    cx.open_url(&url);
 9374                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9375                }
 9376                HoverLink::File(path) => {
 9377                    if let Some(workspace) = self.workspace() {
 9378                        cx.spawn(|_, mut cx| async move {
 9379                            workspace
 9380                                .update(&mut cx, |workspace, cx| {
 9381                                    workspace.open_resolved_path(path, cx)
 9382                                })?
 9383                                .await
 9384                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9385                        })
 9386                    } else {
 9387                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9388                    }
 9389                }
 9390            };
 9391            cx.spawn(|editor, mut cx| async move {
 9392                let target = match target_task.await.context("target resolution task")? {
 9393                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9394                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9395                    TargetTaskResult::Location(Some(target)) => target,
 9396                };
 9397
 9398                editor.update(&mut cx, |editor, cx| {
 9399                    let Some(workspace) = editor.workspace() else {
 9400                        return Navigated::No;
 9401                    };
 9402                    let pane = workspace.read(cx).active_pane().clone();
 9403
 9404                    let range = target.range.to_offset(target.buffer.read(cx));
 9405                    let range = editor.range_for_match(&range);
 9406
 9407                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9408                        let buffer = target.buffer.read(cx);
 9409                        let range = check_multiline_range(buffer, range);
 9410                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9411                            s.select_ranges([range]);
 9412                        });
 9413                    } else {
 9414                        cx.window_context().defer(move |cx| {
 9415                            let target_editor: View<Self> =
 9416                                workspace.update(cx, |workspace, cx| {
 9417                                    let pane = if split {
 9418                                        workspace.adjacent_pane(cx)
 9419                                    } else {
 9420                                        workspace.active_pane().clone()
 9421                                    };
 9422
 9423                                    workspace.open_project_item(
 9424                                        pane,
 9425                                        target.buffer.clone(),
 9426                                        true,
 9427                                        true,
 9428                                        cx,
 9429                                    )
 9430                                });
 9431                            target_editor.update(cx, |target_editor, cx| {
 9432                                // When selecting a definition in a different buffer, disable the nav history
 9433                                // to avoid creating a history entry at the previous cursor location.
 9434                                pane.update(cx, |pane, _| pane.disable_history());
 9435                                let buffer = target.buffer.read(cx);
 9436                                let range = check_multiline_range(buffer, range);
 9437                                target_editor.change_selections(
 9438                                    Some(Autoscroll::focused()),
 9439                                    cx,
 9440                                    |s| {
 9441                                        s.select_ranges([range]);
 9442                                    },
 9443                                );
 9444                                pane.update(cx, |pane, _| pane.enable_history());
 9445                            });
 9446                        });
 9447                    }
 9448                    Navigated::Yes
 9449                })
 9450            })
 9451        } else if !definitions.is_empty() {
 9452            cx.spawn(|editor, mut cx| async move {
 9453                let (title, location_tasks, workspace) = editor
 9454                    .update(&mut cx, |editor, cx| {
 9455                        let tab_kind = match kind {
 9456                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9457                            _ => "Definitions",
 9458                        };
 9459                        let title = definitions
 9460                            .iter()
 9461                            .find_map(|definition| match definition {
 9462                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9463                                    let buffer = origin.buffer.read(cx);
 9464                                    format!(
 9465                                        "{} for {}",
 9466                                        tab_kind,
 9467                                        buffer
 9468                                            .text_for_range(origin.range.clone())
 9469                                            .collect::<String>()
 9470                                    )
 9471                                }),
 9472                                HoverLink::InlayHint(_, _) => None,
 9473                                HoverLink::Url(_) => None,
 9474                                HoverLink::File(_) => None,
 9475                            })
 9476                            .unwrap_or(tab_kind.to_string());
 9477                        let location_tasks = definitions
 9478                            .into_iter()
 9479                            .map(|definition| match definition {
 9480                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9481                                HoverLink::InlayHint(lsp_location, server_id) => {
 9482                                    editor.compute_target_location(lsp_location, server_id, cx)
 9483                                }
 9484                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9485                                HoverLink::File(_) => Task::ready(Ok(None)),
 9486                            })
 9487                            .collect::<Vec<_>>();
 9488                        (title, location_tasks, editor.workspace().clone())
 9489                    })
 9490                    .context("location tasks preparation")?;
 9491
 9492                let locations = future::join_all(location_tasks)
 9493                    .await
 9494                    .into_iter()
 9495                    .filter_map(|location| location.transpose())
 9496                    .collect::<Result<_>>()
 9497                    .context("location tasks")?;
 9498
 9499                let Some(workspace) = workspace else {
 9500                    return Ok(Navigated::No);
 9501                };
 9502                let opened = workspace
 9503                    .update(&mut cx, |workspace, cx| {
 9504                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9505                    })
 9506                    .ok();
 9507
 9508                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9509            })
 9510        } else {
 9511            Task::ready(Ok(Navigated::No))
 9512        }
 9513    }
 9514
 9515    fn compute_target_location(
 9516        &self,
 9517        lsp_location: lsp::Location,
 9518        server_id: LanguageServerId,
 9519        cx: &mut ViewContext<Self>,
 9520    ) -> Task<anyhow::Result<Option<Location>>> {
 9521        let Some(project) = self.project.clone() else {
 9522            return Task::Ready(Some(Ok(None)));
 9523        };
 9524
 9525        cx.spawn(move |editor, mut cx| async move {
 9526            let location_task = editor.update(&mut cx, |_, cx| {
 9527                project.update(cx, |project, cx| {
 9528                    let language_server_name = project
 9529                        .language_server_statuses(cx)
 9530                        .find(|(id, _)| server_id == *id)
 9531                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9532                    language_server_name.map(|language_server_name| {
 9533                        project.open_local_buffer_via_lsp(
 9534                            lsp_location.uri.clone(),
 9535                            server_id,
 9536                            language_server_name,
 9537                            cx,
 9538                        )
 9539                    })
 9540                })
 9541            })?;
 9542            let location = match location_task {
 9543                Some(task) => Some({
 9544                    let target_buffer_handle = task.await.context("open local buffer")?;
 9545                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9546                        let target_start = target_buffer
 9547                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9548                        let target_end = target_buffer
 9549                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9550                        target_buffer.anchor_after(target_start)
 9551                            ..target_buffer.anchor_before(target_end)
 9552                    })?;
 9553                    Location {
 9554                        buffer: target_buffer_handle,
 9555                        range,
 9556                    }
 9557                }),
 9558                None => None,
 9559            };
 9560            Ok(location)
 9561        })
 9562    }
 9563
 9564    pub fn find_all_references(
 9565        &mut self,
 9566        _: &FindAllReferences,
 9567        cx: &mut ViewContext<Self>,
 9568    ) -> Option<Task<Result<Navigated>>> {
 9569        let selection = self.selections.newest::<usize>(cx);
 9570        let multi_buffer = self.buffer.read(cx);
 9571        let head = selection.head();
 9572
 9573        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9574        let head_anchor = multi_buffer_snapshot.anchor_at(
 9575            head,
 9576            if head < selection.tail() {
 9577                Bias::Right
 9578            } else {
 9579                Bias::Left
 9580            },
 9581        );
 9582
 9583        match self
 9584            .find_all_references_task_sources
 9585            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9586        {
 9587            Ok(_) => {
 9588                log::info!(
 9589                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9590                );
 9591                return None;
 9592            }
 9593            Err(i) => {
 9594                self.find_all_references_task_sources.insert(i, head_anchor);
 9595            }
 9596        }
 9597
 9598        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9599        let workspace = self.workspace()?;
 9600        let project = workspace.read(cx).project().clone();
 9601        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9602        Some(cx.spawn(|editor, mut cx| async move {
 9603            let _cleanup = defer({
 9604                let mut cx = cx.clone();
 9605                move || {
 9606                    let _ = editor.update(&mut cx, |editor, _| {
 9607                        if let Ok(i) =
 9608                            editor
 9609                                .find_all_references_task_sources
 9610                                .binary_search_by(|anchor| {
 9611                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9612                                })
 9613                        {
 9614                            editor.find_all_references_task_sources.remove(i);
 9615                        }
 9616                    });
 9617                }
 9618            });
 9619
 9620            let locations = references.await?;
 9621            if locations.is_empty() {
 9622                return anyhow::Ok(Navigated::No);
 9623            }
 9624
 9625            workspace.update(&mut cx, |workspace, cx| {
 9626                let title = locations
 9627                    .first()
 9628                    .as_ref()
 9629                    .map(|location| {
 9630                        let buffer = location.buffer.read(cx);
 9631                        format!(
 9632                            "References to `{}`",
 9633                            buffer
 9634                                .text_for_range(location.range.clone())
 9635                                .collect::<String>()
 9636                        )
 9637                    })
 9638                    .unwrap();
 9639                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9640                Navigated::Yes
 9641            })
 9642        }))
 9643    }
 9644
 9645    /// Opens a multibuffer with the given project locations in it
 9646    pub fn open_locations_in_multibuffer(
 9647        workspace: &mut Workspace,
 9648        mut locations: Vec<Location>,
 9649        title: String,
 9650        split: bool,
 9651        cx: &mut ViewContext<Workspace>,
 9652    ) {
 9653        // If there are multiple definitions, open them in a multibuffer
 9654        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9655        let mut locations = locations.into_iter().peekable();
 9656        let mut ranges_to_highlight = Vec::new();
 9657        let capability = workspace.project().read(cx).capability();
 9658
 9659        let excerpt_buffer = cx.new_model(|cx| {
 9660            let mut multibuffer = MultiBuffer::new(capability);
 9661            while let Some(location) = locations.next() {
 9662                let buffer = location.buffer.read(cx);
 9663                let mut ranges_for_buffer = Vec::new();
 9664                let range = location.range.to_offset(buffer);
 9665                ranges_for_buffer.push(range.clone());
 9666
 9667                while let Some(next_location) = locations.peek() {
 9668                    if next_location.buffer == location.buffer {
 9669                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9670                        locations.next();
 9671                    } else {
 9672                        break;
 9673                    }
 9674                }
 9675
 9676                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9677                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9678                    location.buffer.clone(),
 9679                    ranges_for_buffer,
 9680                    DEFAULT_MULTIBUFFER_CONTEXT,
 9681                    cx,
 9682                ))
 9683            }
 9684
 9685            multibuffer.with_title(title)
 9686        });
 9687
 9688        let editor = cx.new_view(|cx| {
 9689            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9690        });
 9691        editor.update(cx, |editor, cx| {
 9692            if let Some(first_range) = ranges_to_highlight.first() {
 9693                editor.change_selections(None, cx, |selections| {
 9694                    selections.clear_disjoint();
 9695                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9696                });
 9697            }
 9698            editor.highlight_background::<Self>(
 9699                &ranges_to_highlight,
 9700                |theme| theme.editor_highlighted_line_background,
 9701                cx,
 9702            );
 9703            editor.register_buffers_with_language_servers(cx);
 9704        });
 9705
 9706        let item = Box::new(editor);
 9707        let item_id = item.item_id();
 9708
 9709        if split {
 9710            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9711        } else {
 9712            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9713                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9714                    pane.close_current_preview_item(cx)
 9715                } else {
 9716                    None
 9717                }
 9718            });
 9719            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9720        }
 9721        workspace.active_pane().update(cx, |pane, cx| {
 9722            pane.set_preview_item_id(Some(item_id), cx);
 9723        });
 9724    }
 9725
 9726    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9727        use language::ToOffset as _;
 9728
 9729        let provider = self.semantics_provider.clone()?;
 9730        let selection = self.selections.newest_anchor().clone();
 9731        let (cursor_buffer, cursor_buffer_position) = self
 9732            .buffer
 9733            .read(cx)
 9734            .text_anchor_for_position(selection.head(), cx)?;
 9735        let (tail_buffer, cursor_buffer_position_end) = self
 9736            .buffer
 9737            .read(cx)
 9738            .text_anchor_for_position(selection.tail(), cx)?;
 9739        if tail_buffer != cursor_buffer {
 9740            return None;
 9741        }
 9742
 9743        let snapshot = cursor_buffer.read(cx).snapshot();
 9744        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9745        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9746        let prepare_rename = provider
 9747            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9748            .unwrap_or_else(|| Task::ready(Ok(None)));
 9749        drop(snapshot);
 9750
 9751        Some(cx.spawn(|this, mut cx| async move {
 9752            let rename_range = if let Some(range) = prepare_rename.await? {
 9753                Some(range)
 9754            } else {
 9755                this.update(&mut cx, |this, cx| {
 9756                    let buffer = this.buffer.read(cx).snapshot(cx);
 9757                    let mut buffer_highlights = this
 9758                        .document_highlights_for_position(selection.head(), &buffer)
 9759                        .filter(|highlight| {
 9760                            highlight.start.excerpt_id == selection.head().excerpt_id
 9761                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9762                        });
 9763                    buffer_highlights
 9764                        .next()
 9765                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9766                })?
 9767            };
 9768            if let Some(rename_range) = rename_range {
 9769                this.update(&mut cx, |this, cx| {
 9770                    let snapshot = cursor_buffer.read(cx).snapshot();
 9771                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9772                    let cursor_offset_in_rename_range =
 9773                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9774                    let cursor_offset_in_rename_range_end =
 9775                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9776
 9777                    this.take_rename(false, cx);
 9778                    let buffer = this.buffer.read(cx).read(cx);
 9779                    let cursor_offset = selection.head().to_offset(&buffer);
 9780                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9781                    let rename_end = rename_start + rename_buffer_range.len();
 9782                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9783                    let mut old_highlight_id = None;
 9784                    let old_name: Arc<str> = buffer
 9785                        .chunks(rename_start..rename_end, true)
 9786                        .map(|chunk| {
 9787                            if old_highlight_id.is_none() {
 9788                                old_highlight_id = chunk.syntax_highlight_id;
 9789                            }
 9790                            chunk.text
 9791                        })
 9792                        .collect::<String>()
 9793                        .into();
 9794
 9795                    drop(buffer);
 9796
 9797                    // Position the selection in the rename editor so that it matches the current selection.
 9798                    this.show_local_selections = false;
 9799                    let rename_editor = cx.new_view(|cx| {
 9800                        let mut editor = Editor::single_line(cx);
 9801                        editor.buffer.update(cx, |buffer, cx| {
 9802                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9803                        });
 9804                        let rename_selection_range = match cursor_offset_in_rename_range
 9805                            .cmp(&cursor_offset_in_rename_range_end)
 9806                        {
 9807                            Ordering::Equal => {
 9808                                editor.select_all(&SelectAll, cx);
 9809                                return editor;
 9810                            }
 9811                            Ordering::Less => {
 9812                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9813                            }
 9814                            Ordering::Greater => {
 9815                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9816                            }
 9817                        };
 9818                        if rename_selection_range.end > old_name.len() {
 9819                            editor.select_all(&SelectAll, cx);
 9820                        } else {
 9821                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9822                                s.select_ranges([rename_selection_range]);
 9823                            });
 9824                        }
 9825                        editor
 9826                    });
 9827                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9828                        if e == &EditorEvent::Focused {
 9829                            cx.emit(EditorEvent::FocusedIn)
 9830                        }
 9831                    })
 9832                    .detach();
 9833
 9834                    let write_highlights =
 9835                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9836                    let read_highlights =
 9837                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9838                    let ranges = write_highlights
 9839                        .iter()
 9840                        .flat_map(|(_, ranges)| ranges.iter())
 9841                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9842                        .cloned()
 9843                        .collect();
 9844
 9845                    this.highlight_text::<Rename>(
 9846                        ranges,
 9847                        HighlightStyle {
 9848                            fade_out: Some(0.6),
 9849                            ..Default::default()
 9850                        },
 9851                        cx,
 9852                    );
 9853                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9854                    cx.focus(&rename_focus_handle);
 9855                    let block_id = this.insert_blocks(
 9856                        [BlockProperties {
 9857                            style: BlockStyle::Flex,
 9858                            placement: BlockPlacement::Below(range.start),
 9859                            height: 1,
 9860                            render: Arc::new({
 9861                                let rename_editor = rename_editor.clone();
 9862                                move |cx: &mut BlockContext| {
 9863                                    let mut text_style = cx.editor_style.text.clone();
 9864                                    if let Some(highlight_style) = old_highlight_id
 9865                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9866                                    {
 9867                                        text_style = text_style.highlight(highlight_style);
 9868                                    }
 9869                                    div()
 9870                                        .block_mouse_down()
 9871                                        .pl(cx.anchor_x)
 9872                                        .child(EditorElement::new(
 9873                                            &rename_editor,
 9874                                            EditorStyle {
 9875                                                background: cx.theme().system().transparent,
 9876                                                local_player: cx.editor_style.local_player,
 9877                                                text: text_style,
 9878                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9879                                                syntax: cx.editor_style.syntax.clone(),
 9880                                                status: cx.editor_style.status.clone(),
 9881                                                inlay_hints_style: HighlightStyle {
 9882                                                    font_weight: Some(FontWeight::BOLD),
 9883                                                    ..make_inlay_hints_style(cx)
 9884                                                },
 9885                                                suggestions_style: HighlightStyle {
 9886                                                    color: Some(cx.theme().status().predictive),
 9887                                                    ..HighlightStyle::default()
 9888                                                },
 9889                                                ..EditorStyle::default()
 9890                                            },
 9891                                        ))
 9892                                        .into_any_element()
 9893                                }
 9894                            }),
 9895                            priority: 0,
 9896                        }],
 9897                        Some(Autoscroll::fit()),
 9898                        cx,
 9899                    )[0];
 9900                    this.pending_rename = Some(RenameState {
 9901                        range,
 9902                        old_name,
 9903                        editor: rename_editor,
 9904                        block_id,
 9905                    });
 9906                })?;
 9907            }
 9908
 9909            Ok(())
 9910        }))
 9911    }
 9912
 9913    pub fn confirm_rename(
 9914        &mut self,
 9915        _: &ConfirmRename,
 9916        cx: &mut ViewContext<Self>,
 9917    ) -> Option<Task<Result<()>>> {
 9918        let rename = self.take_rename(false, cx)?;
 9919        let workspace = self.workspace()?.downgrade();
 9920        let (buffer, start) = self
 9921            .buffer
 9922            .read(cx)
 9923            .text_anchor_for_position(rename.range.start, cx)?;
 9924        let (end_buffer, _) = self
 9925            .buffer
 9926            .read(cx)
 9927            .text_anchor_for_position(rename.range.end, cx)?;
 9928        if buffer != end_buffer {
 9929            return None;
 9930        }
 9931
 9932        let old_name = rename.old_name;
 9933        let new_name = rename.editor.read(cx).text(cx);
 9934
 9935        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9936            &buffer,
 9937            start,
 9938            new_name.clone(),
 9939            cx,
 9940        )?;
 9941
 9942        Some(cx.spawn(|editor, mut cx| async move {
 9943            let project_transaction = rename.await?;
 9944            Self::open_project_transaction(
 9945                &editor,
 9946                workspace,
 9947                project_transaction,
 9948                format!("Rename: {}{}", old_name, new_name),
 9949                cx.clone(),
 9950            )
 9951            .await?;
 9952
 9953            editor.update(&mut cx, |editor, cx| {
 9954                editor.refresh_document_highlights(cx);
 9955            })?;
 9956            Ok(())
 9957        }))
 9958    }
 9959
 9960    fn take_rename(
 9961        &mut self,
 9962        moving_cursor: bool,
 9963        cx: &mut ViewContext<Self>,
 9964    ) -> Option<RenameState> {
 9965        let rename = self.pending_rename.take()?;
 9966        if rename.editor.focus_handle(cx).is_focused(cx) {
 9967            cx.focus(&self.focus_handle);
 9968        }
 9969
 9970        self.remove_blocks(
 9971            [rename.block_id].into_iter().collect(),
 9972            Some(Autoscroll::fit()),
 9973            cx,
 9974        );
 9975        self.clear_highlights::<Rename>(cx);
 9976        self.show_local_selections = true;
 9977
 9978        if moving_cursor {
 9979            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
 9980                editor.selections.newest::<usize>(cx).head()
 9981            });
 9982
 9983            // Update the selection to match the position of the selection inside
 9984            // the rename editor.
 9985            let snapshot = self.buffer.read(cx).read(cx);
 9986            let rename_range = rename.range.to_offset(&snapshot);
 9987            let cursor_in_editor = snapshot
 9988                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9989                .min(rename_range.end);
 9990            drop(snapshot);
 9991
 9992            self.change_selections(None, cx, |s| {
 9993                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9994            });
 9995        } else {
 9996            self.refresh_document_highlights(cx);
 9997        }
 9998
 9999        Some(rename)
10000    }
10001
10002    pub fn pending_rename(&self) -> Option<&RenameState> {
10003        self.pending_rename.as_ref()
10004    }
10005
10006    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10007        let project = match &self.project {
10008            Some(project) => project.clone(),
10009            None => return None,
10010        };
10011
10012        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10013    }
10014
10015    fn format_selections(
10016        &mut self,
10017        _: &FormatSelections,
10018        cx: &mut ViewContext<Self>,
10019    ) -> Option<Task<Result<()>>> {
10020        let project = match &self.project {
10021            Some(project) => project.clone(),
10022            None => return None,
10023        };
10024
10025        let selections = self
10026            .selections
10027            .all_adjusted(cx)
10028            .into_iter()
10029            .filter(|s| !s.is_empty())
10030            .collect_vec();
10031
10032        Some(self.perform_format(
10033            project,
10034            FormatTrigger::Manual,
10035            FormatTarget::Ranges(selections),
10036            cx,
10037        ))
10038    }
10039
10040    fn perform_format(
10041        &mut self,
10042        project: Model<Project>,
10043        trigger: FormatTrigger,
10044        target: FormatTarget,
10045        cx: &mut ViewContext<Self>,
10046    ) -> Task<Result<()>> {
10047        let buffer = self.buffer().clone();
10048        let mut buffers = buffer.read(cx).all_buffers();
10049        if trigger == FormatTrigger::Save {
10050            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10051        }
10052
10053        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10054        let format = project.update(cx, |project, cx| {
10055            project.format(buffers, true, trigger, target, cx)
10056        });
10057
10058        cx.spawn(|_, mut cx| async move {
10059            let transaction = futures::select_biased! {
10060                () = timeout => {
10061                    log::warn!("timed out waiting for formatting");
10062                    None
10063                }
10064                transaction = format.log_err().fuse() => transaction,
10065            };
10066
10067            buffer
10068                .update(&mut cx, |buffer, cx| {
10069                    if let Some(transaction) = transaction {
10070                        if !buffer.is_singleton() {
10071                            buffer.push_transaction(&transaction.0, cx);
10072                        }
10073                    }
10074
10075                    cx.notify();
10076                })
10077                .ok();
10078
10079            Ok(())
10080        })
10081    }
10082
10083    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10084        if let Some(project) = self.project.clone() {
10085            self.buffer.update(cx, |multi_buffer, cx| {
10086                project.update(cx, |project, cx| {
10087                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10088                });
10089            })
10090        }
10091    }
10092
10093    fn cancel_language_server_work(
10094        &mut self,
10095        _: &actions::CancelLanguageServerWork,
10096        cx: &mut ViewContext<Self>,
10097    ) {
10098        if let Some(project) = self.project.clone() {
10099            self.buffer.update(cx, |multi_buffer, cx| {
10100                project.update(cx, |project, cx| {
10101                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10102                });
10103            })
10104        }
10105    }
10106
10107    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10108        cx.show_character_palette();
10109    }
10110
10111    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10112        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10113            let buffer = self.buffer.read(cx).snapshot(cx);
10114            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10115            let is_valid = buffer
10116                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10117                .any(|entry| {
10118                    entry.diagnostic.is_primary
10119                        && !entry.range.is_empty()
10120                        && entry.range.start == primary_range_start
10121                        && entry.diagnostic.message == active_diagnostics.primary_message
10122                });
10123
10124            if is_valid != active_diagnostics.is_valid {
10125                active_diagnostics.is_valid = is_valid;
10126                let mut new_styles = HashMap::default();
10127                for (block_id, diagnostic) in &active_diagnostics.blocks {
10128                    new_styles.insert(
10129                        *block_id,
10130                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10131                    );
10132                }
10133                self.display_map.update(cx, |display_map, _cx| {
10134                    display_map.replace_blocks(new_styles)
10135                });
10136            }
10137        }
10138    }
10139
10140    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10141        self.dismiss_diagnostics(cx);
10142        let snapshot = self.snapshot(cx);
10143        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10144            let buffer = self.buffer.read(cx).snapshot(cx);
10145
10146            let mut primary_range = None;
10147            let mut primary_message = None;
10148            let mut group_end = Point::zero();
10149            let diagnostic_group = buffer
10150                .diagnostic_group::<MultiBufferPoint>(group_id)
10151                .filter_map(|entry| {
10152                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10153                        && (entry.range.start.row == entry.range.end.row
10154                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10155                    {
10156                        return None;
10157                    }
10158                    if entry.range.end > group_end {
10159                        group_end = entry.range.end;
10160                    }
10161                    if entry.diagnostic.is_primary {
10162                        primary_range = Some(entry.range.clone());
10163                        primary_message = Some(entry.diagnostic.message.clone());
10164                    }
10165                    Some(entry)
10166                })
10167                .collect::<Vec<_>>();
10168            let primary_range = primary_range?;
10169            let primary_message = primary_message?;
10170            let primary_range =
10171                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10172
10173            let blocks = display_map
10174                .insert_blocks(
10175                    diagnostic_group.iter().map(|entry| {
10176                        let diagnostic = entry.diagnostic.clone();
10177                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10178                        BlockProperties {
10179                            style: BlockStyle::Fixed,
10180                            placement: BlockPlacement::Below(
10181                                buffer.anchor_after(entry.range.start),
10182                            ),
10183                            height: message_height,
10184                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10185                            priority: 0,
10186                        }
10187                    }),
10188                    cx,
10189                )
10190                .into_iter()
10191                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10192                .collect();
10193
10194            Some(ActiveDiagnosticGroup {
10195                primary_range,
10196                primary_message,
10197                group_id,
10198                blocks,
10199                is_valid: true,
10200            })
10201        });
10202        self.active_diagnostics.is_some()
10203    }
10204
10205    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10206        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10207            self.display_map.update(cx, |display_map, cx| {
10208                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10209            });
10210            cx.notify();
10211        }
10212    }
10213
10214    pub fn set_selections_from_remote(
10215        &mut self,
10216        selections: Vec<Selection<Anchor>>,
10217        pending_selection: Option<Selection<Anchor>>,
10218        cx: &mut ViewContext<Self>,
10219    ) {
10220        let old_cursor_position = self.selections.newest_anchor().head();
10221        self.selections.change_with(cx, |s| {
10222            s.select_anchors(selections);
10223            if let Some(pending_selection) = pending_selection {
10224                s.set_pending(pending_selection, SelectMode::Character);
10225            } else {
10226                s.clear_pending();
10227            }
10228        });
10229        self.selections_did_change(false, &old_cursor_position, true, cx);
10230    }
10231
10232    fn push_to_selection_history(&mut self) {
10233        self.selection_history.push(SelectionHistoryEntry {
10234            selections: self.selections.disjoint_anchors(),
10235            select_next_state: self.select_next_state.clone(),
10236            select_prev_state: self.select_prev_state.clone(),
10237            add_selections_state: self.add_selections_state.clone(),
10238        });
10239    }
10240
10241    pub fn transact(
10242        &mut self,
10243        cx: &mut ViewContext<Self>,
10244        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10245    ) -> Option<TransactionId> {
10246        self.start_transaction_at(Instant::now(), cx);
10247        update(self, cx);
10248        self.end_transaction_at(Instant::now(), cx)
10249    }
10250
10251    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10252        self.end_selection(cx);
10253        if let Some(tx_id) = self
10254            .buffer
10255            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10256        {
10257            self.selection_history
10258                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10259            cx.emit(EditorEvent::TransactionBegun {
10260                transaction_id: tx_id,
10261            })
10262        }
10263    }
10264
10265    fn end_transaction_at(
10266        &mut self,
10267        now: Instant,
10268        cx: &mut ViewContext<Self>,
10269    ) -> Option<TransactionId> {
10270        if let Some(transaction_id) = self
10271            .buffer
10272            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10273        {
10274            if let Some((_, end_selections)) =
10275                self.selection_history.transaction_mut(transaction_id)
10276            {
10277                *end_selections = Some(self.selections.disjoint_anchors());
10278            } else {
10279                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10280            }
10281
10282            cx.emit(EditorEvent::Edited { transaction_id });
10283            Some(transaction_id)
10284        } else {
10285            None
10286        }
10287    }
10288
10289    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10290        let selection = self.selections.newest::<Point>(cx);
10291
10292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10293        let range = if selection.is_empty() {
10294            let point = selection.head().to_display_point(&display_map);
10295            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10296            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10297                .to_point(&display_map);
10298            start..end
10299        } else {
10300            selection.range()
10301        };
10302        if display_map.folds_in_range(range).next().is_some() {
10303            self.unfold_lines(&Default::default(), cx)
10304        } else {
10305            self.fold(&Default::default(), cx)
10306        }
10307    }
10308
10309    pub fn toggle_fold_recursive(
10310        &mut self,
10311        _: &actions::ToggleFoldRecursive,
10312        cx: &mut ViewContext<Self>,
10313    ) {
10314        let selection = self.selections.newest::<Point>(cx);
10315
10316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10317        let range = if selection.is_empty() {
10318            let point = selection.head().to_display_point(&display_map);
10319            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10320            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10321                .to_point(&display_map);
10322            start..end
10323        } else {
10324            selection.range()
10325        };
10326        if display_map.folds_in_range(range).next().is_some() {
10327            self.unfold_recursive(&Default::default(), cx)
10328        } else {
10329            self.fold_recursive(&Default::default(), cx)
10330        }
10331    }
10332
10333    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10334        let mut to_fold = Vec::new();
10335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10336        let selections = self.selections.all_adjusted(cx);
10337
10338        for selection in selections {
10339            let range = selection.range().sorted();
10340            let buffer_start_row = range.start.row;
10341
10342            if range.start.row != range.end.row {
10343                let mut found = false;
10344                let mut row = range.start.row;
10345                while row <= range.end.row {
10346                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10347                        found = true;
10348                        row = crease.range().end.row + 1;
10349                        to_fold.push(crease);
10350                    } else {
10351                        row += 1
10352                    }
10353                }
10354                if found {
10355                    continue;
10356                }
10357            }
10358
10359            for row in (0..=range.start.row).rev() {
10360                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10361                    if crease.range().end.row >= buffer_start_row {
10362                        to_fold.push(crease);
10363                        if row <= range.start.row {
10364                            break;
10365                        }
10366                    }
10367                }
10368            }
10369        }
10370
10371        self.fold_creases(to_fold, true, cx);
10372    }
10373
10374    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10375        if !self.buffer.read(cx).is_singleton() {
10376            return;
10377        }
10378
10379        let fold_at_level = fold_at.level;
10380        let snapshot = self.buffer.read(cx).snapshot(cx);
10381        let mut to_fold = Vec::new();
10382        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10383
10384        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10385            while start_row < end_row {
10386                match self
10387                    .snapshot(cx)
10388                    .crease_for_buffer_row(MultiBufferRow(start_row))
10389                {
10390                    Some(crease) => {
10391                        let nested_start_row = crease.range().start.row + 1;
10392                        let nested_end_row = crease.range().end.row;
10393
10394                        if current_level < fold_at_level {
10395                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10396                        } else if current_level == fold_at_level {
10397                            to_fold.push(crease);
10398                        }
10399
10400                        start_row = nested_end_row + 1;
10401                    }
10402                    None => start_row += 1,
10403                }
10404            }
10405        }
10406
10407        self.fold_creases(to_fold, true, cx);
10408    }
10409
10410    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10411        if !self.buffer.read(cx).is_singleton() {
10412            return;
10413        }
10414
10415        let mut fold_ranges = Vec::new();
10416        let snapshot = self.buffer.read(cx).snapshot(cx);
10417
10418        for row in 0..snapshot.max_row().0 {
10419            if let Some(foldable_range) =
10420                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10421            {
10422                fold_ranges.push(foldable_range);
10423            }
10424        }
10425
10426        self.fold_creases(fold_ranges, true, cx);
10427    }
10428
10429    pub fn fold_function_bodies(
10430        &mut self,
10431        _: &actions::FoldFunctionBodies,
10432        cx: &mut ViewContext<Self>,
10433    ) {
10434        let snapshot = self.buffer.read(cx).snapshot(cx);
10435        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10436            return;
10437        };
10438        let creases = buffer
10439            .function_body_fold_ranges(0..buffer.len())
10440            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10441            .collect();
10442
10443        self.fold_creases(creases, true, cx);
10444    }
10445
10446    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10447        let mut to_fold = Vec::new();
10448        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10449        let selections = self.selections.all_adjusted(cx);
10450
10451        for selection in selections {
10452            let range = selection.range().sorted();
10453            let buffer_start_row = range.start.row;
10454
10455            if range.start.row != range.end.row {
10456                let mut found = false;
10457                for row in range.start.row..=range.end.row {
10458                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10459                        found = true;
10460                        to_fold.push(crease);
10461                    }
10462                }
10463                if found {
10464                    continue;
10465                }
10466            }
10467
10468            for row in (0..=range.start.row).rev() {
10469                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10470                    if crease.range().end.row >= buffer_start_row {
10471                        to_fold.push(crease);
10472                    } else {
10473                        break;
10474                    }
10475                }
10476            }
10477        }
10478
10479        self.fold_creases(to_fold, true, cx);
10480    }
10481
10482    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10483        let buffer_row = fold_at.buffer_row;
10484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10485
10486        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10487            let autoscroll = self
10488                .selections
10489                .all::<Point>(cx)
10490                .iter()
10491                .any(|selection| crease.range().overlaps(&selection.range()));
10492
10493            self.fold_creases(vec![crease], autoscroll, cx);
10494        }
10495    }
10496
10497    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10498        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10499        let buffer = &display_map.buffer_snapshot;
10500        let selections = self.selections.all::<Point>(cx);
10501        let ranges = selections
10502            .iter()
10503            .map(|s| {
10504                let range = s.display_range(&display_map).sorted();
10505                let mut start = range.start.to_point(&display_map);
10506                let mut end = range.end.to_point(&display_map);
10507                start.column = 0;
10508                end.column = buffer.line_len(MultiBufferRow(end.row));
10509                start..end
10510            })
10511            .collect::<Vec<_>>();
10512
10513        self.unfold_ranges(&ranges, true, true, cx);
10514    }
10515
10516    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10517        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10518        let selections = self.selections.all::<Point>(cx);
10519        let ranges = selections
10520            .iter()
10521            .map(|s| {
10522                let mut range = s.display_range(&display_map).sorted();
10523                *range.start.column_mut() = 0;
10524                *range.end.column_mut() = display_map.line_len(range.end.row());
10525                let start = range.start.to_point(&display_map);
10526                let end = range.end.to_point(&display_map);
10527                start..end
10528            })
10529            .collect::<Vec<_>>();
10530
10531        self.unfold_ranges(&ranges, true, true, cx);
10532    }
10533
10534    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10535        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10536
10537        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10538            ..Point::new(
10539                unfold_at.buffer_row.0,
10540                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10541            );
10542
10543        let autoscroll = self
10544            .selections
10545            .all::<Point>(cx)
10546            .iter()
10547            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10548
10549        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10550    }
10551
10552    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10553        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10554        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10555    }
10556
10557    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10558        let selections = self.selections.all::<Point>(cx);
10559        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10560        let line_mode = self.selections.line_mode;
10561        let ranges = selections
10562            .into_iter()
10563            .map(|s| {
10564                if line_mode {
10565                    let start = Point::new(s.start.row, 0);
10566                    let end = Point::new(
10567                        s.end.row,
10568                        display_map
10569                            .buffer_snapshot
10570                            .line_len(MultiBufferRow(s.end.row)),
10571                    );
10572                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10573                } else {
10574                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10575                }
10576            })
10577            .collect::<Vec<_>>();
10578        self.fold_creases(ranges, true, cx);
10579    }
10580
10581    pub fn fold_creases<T: ToOffset + Clone>(
10582        &mut self,
10583        creases: Vec<Crease<T>>,
10584        auto_scroll: bool,
10585        cx: &mut ViewContext<Self>,
10586    ) {
10587        if creases.is_empty() {
10588            return;
10589        }
10590
10591        let mut buffers_affected = HashSet::default();
10592        let multi_buffer = self.buffer().read(cx);
10593        for crease in &creases {
10594            if let Some((_, buffer, _)) =
10595                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10596            {
10597                buffers_affected.insert(buffer.read(cx).remote_id());
10598            };
10599        }
10600
10601        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10602
10603        if auto_scroll {
10604            self.request_autoscroll(Autoscroll::fit(), cx);
10605        }
10606
10607        for buffer_id in buffers_affected {
10608            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10609        }
10610
10611        cx.notify();
10612
10613        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10614            // Clear diagnostics block when folding a range that contains it.
10615            let snapshot = self.snapshot(cx);
10616            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10617                drop(snapshot);
10618                self.active_diagnostics = Some(active_diagnostics);
10619                self.dismiss_diagnostics(cx);
10620            } else {
10621                self.active_diagnostics = Some(active_diagnostics);
10622            }
10623        }
10624
10625        self.scrollbar_marker_state.dirty = true;
10626    }
10627
10628    /// Removes any folds whose ranges intersect any of the given ranges.
10629    pub fn unfold_ranges<T: ToOffset + Clone>(
10630        &mut self,
10631        ranges: &[Range<T>],
10632        inclusive: bool,
10633        auto_scroll: bool,
10634        cx: &mut ViewContext<Self>,
10635    ) {
10636        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10637            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10638        });
10639    }
10640
10641    /// Removes any folds with the given ranges.
10642    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10643        &mut self,
10644        ranges: &[Range<T>],
10645        type_id: TypeId,
10646        auto_scroll: bool,
10647        cx: &mut ViewContext<Self>,
10648    ) {
10649        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10650            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10651        });
10652    }
10653
10654    fn remove_folds_with<T: ToOffset + Clone>(
10655        &mut self,
10656        ranges: &[Range<T>],
10657        auto_scroll: bool,
10658        cx: &mut ViewContext<Self>,
10659        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10660    ) {
10661        if ranges.is_empty() {
10662            return;
10663        }
10664
10665        let mut buffers_affected = HashSet::default();
10666        let multi_buffer = self.buffer().read(cx);
10667        for range in ranges {
10668            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10669                buffers_affected.insert(buffer.read(cx).remote_id());
10670            };
10671        }
10672
10673        self.display_map.update(cx, update);
10674
10675        if auto_scroll {
10676            self.request_autoscroll(Autoscroll::fit(), cx);
10677        }
10678
10679        for buffer_id in buffers_affected {
10680            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10681        }
10682
10683        cx.notify();
10684        self.scrollbar_marker_state.dirty = true;
10685        self.active_indent_guides_state.dirty = true;
10686    }
10687
10688    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10689        self.display_map.read(cx).fold_placeholder.clone()
10690    }
10691
10692    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10693        if hovered != self.gutter_hovered {
10694            self.gutter_hovered = hovered;
10695            cx.notify();
10696        }
10697    }
10698
10699    pub fn insert_blocks(
10700        &mut self,
10701        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10702        autoscroll: Option<Autoscroll>,
10703        cx: &mut ViewContext<Self>,
10704    ) -> Vec<CustomBlockId> {
10705        let blocks = self
10706            .display_map
10707            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10708        if let Some(autoscroll) = autoscroll {
10709            self.request_autoscroll(autoscroll, cx);
10710        }
10711        cx.notify();
10712        blocks
10713    }
10714
10715    pub fn resize_blocks(
10716        &mut self,
10717        heights: HashMap<CustomBlockId, u32>,
10718        autoscroll: Option<Autoscroll>,
10719        cx: &mut ViewContext<Self>,
10720    ) {
10721        self.display_map
10722            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10723        if let Some(autoscroll) = autoscroll {
10724            self.request_autoscroll(autoscroll, cx);
10725        }
10726        cx.notify();
10727    }
10728
10729    pub fn replace_blocks(
10730        &mut self,
10731        renderers: HashMap<CustomBlockId, RenderBlock>,
10732        autoscroll: Option<Autoscroll>,
10733        cx: &mut ViewContext<Self>,
10734    ) {
10735        self.display_map
10736            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10737        if let Some(autoscroll) = autoscroll {
10738            self.request_autoscroll(autoscroll, cx);
10739        }
10740        cx.notify();
10741    }
10742
10743    pub fn remove_blocks(
10744        &mut self,
10745        block_ids: HashSet<CustomBlockId>,
10746        autoscroll: Option<Autoscroll>,
10747        cx: &mut ViewContext<Self>,
10748    ) {
10749        self.display_map.update(cx, |display_map, cx| {
10750            display_map.remove_blocks(block_ids, cx)
10751        });
10752        if let Some(autoscroll) = autoscroll {
10753            self.request_autoscroll(autoscroll, cx);
10754        }
10755        cx.notify();
10756    }
10757
10758    pub fn row_for_block(
10759        &self,
10760        block_id: CustomBlockId,
10761        cx: &mut ViewContext<Self>,
10762    ) -> Option<DisplayRow> {
10763        self.display_map
10764            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10765    }
10766
10767    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10768        self.focused_block = Some(focused_block);
10769    }
10770
10771    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10772        self.focused_block.take()
10773    }
10774
10775    pub fn insert_creases(
10776        &mut self,
10777        creases: impl IntoIterator<Item = Crease<Anchor>>,
10778        cx: &mut ViewContext<Self>,
10779    ) -> Vec<CreaseId> {
10780        self.display_map
10781            .update(cx, |map, cx| map.insert_creases(creases, cx))
10782    }
10783
10784    pub fn remove_creases(
10785        &mut self,
10786        ids: impl IntoIterator<Item = CreaseId>,
10787        cx: &mut ViewContext<Self>,
10788    ) {
10789        self.display_map
10790            .update(cx, |map, cx| map.remove_creases(ids, cx));
10791    }
10792
10793    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10794        self.display_map
10795            .update(cx, |map, cx| map.snapshot(cx))
10796            .longest_row()
10797    }
10798
10799    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10800        self.display_map
10801            .update(cx, |map, cx| map.snapshot(cx))
10802            .max_point()
10803    }
10804
10805    pub fn text(&self, cx: &AppContext) -> String {
10806        self.buffer.read(cx).read(cx).text()
10807    }
10808
10809    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10810        let text = self.text(cx);
10811        let text = text.trim();
10812
10813        if text.is_empty() {
10814            return None;
10815        }
10816
10817        Some(text.to_string())
10818    }
10819
10820    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10821        self.transact(cx, |this, cx| {
10822            this.buffer
10823                .read(cx)
10824                .as_singleton()
10825                .expect("you can only call set_text on editors for singleton buffers")
10826                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10827        });
10828    }
10829
10830    pub fn display_text(&self, cx: &mut AppContext) -> String {
10831        self.display_map
10832            .update(cx, |map, cx| map.snapshot(cx))
10833            .text()
10834    }
10835
10836    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10837        let mut wrap_guides = smallvec::smallvec![];
10838
10839        if self.show_wrap_guides == Some(false) {
10840            return wrap_guides;
10841        }
10842
10843        let settings = self.buffer.read(cx).settings_at(0, cx);
10844        if settings.show_wrap_guides {
10845            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10846                wrap_guides.push((soft_wrap as usize, true));
10847            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10848                wrap_guides.push((soft_wrap as usize, true));
10849            }
10850            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10851        }
10852
10853        wrap_guides
10854    }
10855
10856    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10857        let settings = self.buffer.read(cx).settings_at(0, cx);
10858        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10859        match mode {
10860            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10861                SoftWrap::None
10862            }
10863            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10864            language_settings::SoftWrap::PreferredLineLength => {
10865                SoftWrap::Column(settings.preferred_line_length)
10866            }
10867            language_settings::SoftWrap::Bounded => {
10868                SoftWrap::Bounded(settings.preferred_line_length)
10869            }
10870        }
10871    }
10872
10873    pub fn set_soft_wrap_mode(
10874        &mut self,
10875        mode: language_settings::SoftWrap,
10876        cx: &mut ViewContext<Self>,
10877    ) {
10878        self.soft_wrap_mode_override = Some(mode);
10879        cx.notify();
10880    }
10881
10882    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10883        self.text_style_refinement = Some(style);
10884    }
10885
10886    /// called by the Element so we know what style we were most recently rendered with.
10887    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10888        let rem_size = cx.rem_size();
10889        self.display_map.update(cx, |map, cx| {
10890            map.set_font(
10891                style.text.font(),
10892                style.text.font_size.to_pixels(rem_size),
10893                cx,
10894            )
10895        });
10896        self.style = Some(style);
10897    }
10898
10899    pub fn style(&self) -> Option<&EditorStyle> {
10900        self.style.as_ref()
10901    }
10902
10903    // Called by the element. This method is not designed to be called outside of the editor
10904    // element's layout code because it does not notify when rewrapping is computed synchronously.
10905    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10906        self.display_map
10907            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10908    }
10909
10910    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10911        if self.soft_wrap_mode_override.is_some() {
10912            self.soft_wrap_mode_override.take();
10913        } else {
10914            let soft_wrap = match self.soft_wrap_mode(cx) {
10915                SoftWrap::GitDiff => return,
10916                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10917                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10918                    language_settings::SoftWrap::None
10919                }
10920            };
10921            self.soft_wrap_mode_override = Some(soft_wrap);
10922        }
10923        cx.notify();
10924    }
10925
10926    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10927        let Some(workspace) = self.workspace() else {
10928            return;
10929        };
10930        let fs = workspace.read(cx).app_state().fs.clone();
10931        let current_show = TabBarSettings::get_global(cx).show;
10932        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10933            setting.show = Some(!current_show);
10934        });
10935    }
10936
10937    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10938        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10939            self.buffer
10940                .read(cx)
10941                .settings_at(0, cx)
10942                .indent_guides
10943                .enabled
10944        });
10945        self.show_indent_guides = Some(!currently_enabled);
10946        cx.notify();
10947    }
10948
10949    fn should_show_indent_guides(&self) -> Option<bool> {
10950        self.show_indent_guides
10951    }
10952
10953    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10954        let mut editor_settings = EditorSettings::get_global(cx).clone();
10955        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10956        EditorSettings::override_global(editor_settings, cx);
10957    }
10958
10959    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10960        self.use_relative_line_numbers
10961            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10962    }
10963
10964    pub fn toggle_relative_line_numbers(
10965        &mut self,
10966        _: &ToggleRelativeLineNumbers,
10967        cx: &mut ViewContext<Self>,
10968    ) {
10969        let is_relative = self.should_use_relative_line_numbers(cx);
10970        self.set_relative_line_number(Some(!is_relative), cx)
10971    }
10972
10973    pub fn set_relative_line_number(
10974        &mut self,
10975        is_relative: Option<bool>,
10976        cx: &mut ViewContext<Self>,
10977    ) {
10978        self.use_relative_line_numbers = is_relative;
10979        cx.notify();
10980    }
10981
10982    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10983        self.show_gutter = show_gutter;
10984        cx.notify();
10985    }
10986
10987    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10988        self.show_line_numbers = Some(show_line_numbers);
10989        cx.notify();
10990    }
10991
10992    pub fn set_show_git_diff_gutter(
10993        &mut self,
10994        show_git_diff_gutter: bool,
10995        cx: &mut ViewContext<Self>,
10996    ) {
10997        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10998        cx.notify();
10999    }
11000
11001    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11002        self.show_code_actions = Some(show_code_actions);
11003        cx.notify();
11004    }
11005
11006    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11007        self.show_runnables = Some(show_runnables);
11008        cx.notify();
11009    }
11010
11011    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11012        if self.display_map.read(cx).masked != masked {
11013            self.display_map.update(cx, |map, _| map.masked = masked);
11014        }
11015        cx.notify()
11016    }
11017
11018    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11019        self.show_wrap_guides = Some(show_wrap_guides);
11020        cx.notify();
11021    }
11022
11023    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11024        self.show_indent_guides = Some(show_indent_guides);
11025        cx.notify();
11026    }
11027
11028    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11029        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11030            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11031                if let Some(dir) = file.abs_path(cx).parent() {
11032                    return Some(dir.to_owned());
11033                }
11034            }
11035
11036            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11037                return Some(project_path.path.to_path_buf());
11038            }
11039        }
11040
11041        None
11042    }
11043
11044    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11045        self.active_excerpt(cx)?
11046            .1
11047            .read(cx)
11048            .file()
11049            .and_then(|f| f.as_local())
11050    }
11051
11052    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11053        if let Some(target) = self.target_file(cx) {
11054            cx.reveal_path(&target.abs_path(cx));
11055        }
11056    }
11057
11058    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11059        if let Some(file) = self.target_file(cx) {
11060            if let Some(path) = file.abs_path(cx).to_str() {
11061                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11062            }
11063        }
11064    }
11065
11066    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11067        if let Some(file) = self.target_file(cx) {
11068            if let Some(path) = file.path().to_str() {
11069                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11070            }
11071        }
11072    }
11073
11074    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11075        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11076
11077        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11078            self.start_git_blame(true, cx);
11079        }
11080
11081        cx.notify();
11082    }
11083
11084    pub fn toggle_git_blame_inline(
11085        &mut self,
11086        _: &ToggleGitBlameInline,
11087        cx: &mut ViewContext<Self>,
11088    ) {
11089        self.toggle_git_blame_inline_internal(true, cx);
11090        cx.notify();
11091    }
11092
11093    pub fn git_blame_inline_enabled(&self) -> bool {
11094        self.git_blame_inline_enabled
11095    }
11096
11097    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11098        self.show_selection_menu = self
11099            .show_selection_menu
11100            .map(|show_selections_menu| !show_selections_menu)
11101            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11102
11103        cx.notify();
11104    }
11105
11106    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11107        self.show_selection_menu
11108            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11109    }
11110
11111    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11112        if let Some(project) = self.project.as_ref() {
11113            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11114                return;
11115            };
11116
11117            if buffer.read(cx).file().is_none() {
11118                return;
11119            }
11120
11121            let focused = self.focus_handle(cx).contains_focused(cx);
11122
11123            let project = project.clone();
11124            let blame =
11125                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11126            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11127            self.blame = Some(blame);
11128        }
11129    }
11130
11131    fn toggle_git_blame_inline_internal(
11132        &mut self,
11133        user_triggered: bool,
11134        cx: &mut ViewContext<Self>,
11135    ) {
11136        if self.git_blame_inline_enabled {
11137            self.git_blame_inline_enabled = false;
11138            self.show_git_blame_inline = false;
11139            self.show_git_blame_inline_delay_task.take();
11140        } else {
11141            self.git_blame_inline_enabled = true;
11142            self.start_git_blame_inline(user_triggered, cx);
11143        }
11144
11145        cx.notify();
11146    }
11147
11148    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11149        self.start_git_blame(user_triggered, cx);
11150
11151        if ProjectSettings::get_global(cx)
11152            .git
11153            .inline_blame_delay()
11154            .is_some()
11155        {
11156            self.start_inline_blame_timer(cx);
11157        } else {
11158            self.show_git_blame_inline = true
11159        }
11160    }
11161
11162    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11163        self.blame.as_ref()
11164    }
11165
11166    pub fn show_git_blame_gutter(&self) -> bool {
11167        self.show_git_blame_gutter
11168    }
11169
11170    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11171        self.show_git_blame_gutter && self.has_blame_entries(cx)
11172    }
11173
11174    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11175        self.show_git_blame_inline
11176            && self.focus_handle.is_focused(cx)
11177            && !self.newest_selection_head_on_empty_line(cx)
11178            && self.has_blame_entries(cx)
11179    }
11180
11181    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11182        self.blame()
11183            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11184    }
11185
11186    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11187        let cursor_anchor = self.selections.newest_anchor().head();
11188
11189        let snapshot = self.buffer.read(cx).snapshot(cx);
11190        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11191
11192        snapshot.line_len(buffer_row) == 0
11193    }
11194
11195    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11196        let buffer_and_selection = maybe!({
11197            let selection = self.selections.newest::<Point>(cx);
11198            let selection_range = selection.range();
11199
11200            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11201                (buffer, selection_range.start.row..selection_range.end.row)
11202            } else {
11203                let buffer_ranges = self
11204                    .buffer()
11205                    .read(cx)
11206                    .range_to_buffer_ranges(selection_range, cx);
11207
11208                let (buffer, range, _) = if selection.reversed {
11209                    buffer_ranges.first()
11210                } else {
11211                    buffer_ranges.last()
11212                }?;
11213
11214                let snapshot = buffer.read(cx).snapshot();
11215                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11216                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11217                (buffer.clone(), selection)
11218            };
11219
11220            Some((buffer, selection))
11221        });
11222
11223        let Some((buffer, selection)) = buffer_and_selection else {
11224            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11225        };
11226
11227        let Some(project) = self.project.as_ref() else {
11228            return Task::ready(Err(anyhow!("editor does not have project")));
11229        };
11230
11231        project.update(cx, |project, cx| {
11232            project.get_permalink_to_line(&buffer, selection, cx)
11233        })
11234    }
11235
11236    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11237        let permalink_task = self.get_permalink_to_line(cx);
11238        let workspace = self.workspace();
11239
11240        cx.spawn(|_, mut cx| async move {
11241            match permalink_task.await {
11242                Ok(permalink) => {
11243                    cx.update(|cx| {
11244                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11245                    })
11246                    .ok();
11247                }
11248                Err(err) => {
11249                    let message = format!("Failed to copy permalink: {err}");
11250
11251                    Err::<(), anyhow::Error>(err).log_err();
11252
11253                    if let Some(workspace) = workspace {
11254                        workspace
11255                            .update(&mut cx, |workspace, cx| {
11256                                struct CopyPermalinkToLine;
11257
11258                                workspace.show_toast(
11259                                    Toast::new(
11260                                        NotificationId::unique::<CopyPermalinkToLine>(),
11261                                        message,
11262                                    ),
11263                                    cx,
11264                                )
11265                            })
11266                            .ok();
11267                    }
11268                }
11269            }
11270        })
11271        .detach();
11272    }
11273
11274    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11275        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11276        if let Some(file) = self.target_file(cx) {
11277            if let Some(path) = file.path().to_str() {
11278                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11279            }
11280        }
11281    }
11282
11283    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11284        let permalink_task = self.get_permalink_to_line(cx);
11285        let workspace = self.workspace();
11286
11287        cx.spawn(|_, mut cx| async move {
11288            match permalink_task.await {
11289                Ok(permalink) => {
11290                    cx.update(|cx| {
11291                        cx.open_url(permalink.as_ref());
11292                    })
11293                    .ok();
11294                }
11295                Err(err) => {
11296                    let message = format!("Failed to open permalink: {err}");
11297
11298                    Err::<(), anyhow::Error>(err).log_err();
11299
11300                    if let Some(workspace) = workspace {
11301                        workspace
11302                            .update(&mut cx, |workspace, cx| {
11303                                struct OpenPermalinkToLine;
11304
11305                                workspace.show_toast(
11306                                    Toast::new(
11307                                        NotificationId::unique::<OpenPermalinkToLine>(),
11308                                        message,
11309                                    ),
11310                                    cx,
11311                                )
11312                            })
11313                            .ok();
11314                    }
11315                }
11316            }
11317        })
11318        .detach();
11319    }
11320
11321    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11322        self.insert_uuid(UuidVersion::V4, cx);
11323    }
11324
11325    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11326        self.insert_uuid(UuidVersion::V7, cx);
11327    }
11328
11329    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11330        self.transact(cx, |this, cx| {
11331            let edits = this
11332                .selections
11333                .all::<Point>(cx)
11334                .into_iter()
11335                .map(|selection| {
11336                    let uuid = match version {
11337                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11338                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11339                    };
11340
11341                    (selection.range(), uuid.to_string())
11342                });
11343            this.edit(edits, cx);
11344            this.refresh_inline_completion(true, false, cx);
11345        });
11346    }
11347
11348    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11349    /// last highlight added will be used.
11350    ///
11351    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11352    pub fn highlight_rows<T: 'static>(
11353        &mut self,
11354        range: Range<Anchor>,
11355        color: Hsla,
11356        should_autoscroll: bool,
11357        cx: &mut ViewContext<Self>,
11358    ) {
11359        let snapshot = self.buffer().read(cx).snapshot(cx);
11360        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11361        let ix = row_highlights.binary_search_by(|highlight| {
11362            Ordering::Equal
11363                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11364                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11365        });
11366
11367        if let Err(mut ix) = ix {
11368            let index = post_inc(&mut self.highlight_order);
11369
11370            // If this range intersects with the preceding highlight, then merge it with
11371            // the preceding highlight. Otherwise insert a new highlight.
11372            let mut merged = false;
11373            if ix > 0 {
11374                let prev_highlight = &mut row_highlights[ix - 1];
11375                if prev_highlight
11376                    .range
11377                    .end
11378                    .cmp(&range.start, &snapshot)
11379                    .is_ge()
11380                {
11381                    ix -= 1;
11382                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11383                        prev_highlight.range.end = range.end;
11384                    }
11385                    merged = true;
11386                    prev_highlight.index = index;
11387                    prev_highlight.color = color;
11388                    prev_highlight.should_autoscroll = should_autoscroll;
11389                }
11390            }
11391
11392            if !merged {
11393                row_highlights.insert(
11394                    ix,
11395                    RowHighlight {
11396                        range: range.clone(),
11397                        index,
11398                        color,
11399                        should_autoscroll,
11400                    },
11401                );
11402            }
11403
11404            // If any of the following highlights intersect with this one, merge them.
11405            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11406                let highlight = &row_highlights[ix];
11407                if next_highlight
11408                    .range
11409                    .start
11410                    .cmp(&highlight.range.end, &snapshot)
11411                    .is_le()
11412                {
11413                    if next_highlight
11414                        .range
11415                        .end
11416                        .cmp(&highlight.range.end, &snapshot)
11417                        .is_gt()
11418                    {
11419                        row_highlights[ix].range.end = next_highlight.range.end;
11420                    }
11421                    row_highlights.remove(ix + 1);
11422                } else {
11423                    break;
11424                }
11425            }
11426        }
11427    }
11428
11429    /// Remove any highlighted row ranges of the given type that intersect the
11430    /// given ranges.
11431    pub fn remove_highlighted_rows<T: 'static>(
11432        &mut self,
11433        ranges_to_remove: Vec<Range<Anchor>>,
11434        cx: &mut ViewContext<Self>,
11435    ) {
11436        let snapshot = self.buffer().read(cx).snapshot(cx);
11437        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11438        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11439        row_highlights.retain(|highlight| {
11440            while let Some(range_to_remove) = ranges_to_remove.peek() {
11441                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11442                    Ordering::Less | Ordering::Equal => {
11443                        ranges_to_remove.next();
11444                    }
11445                    Ordering::Greater => {
11446                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11447                            Ordering::Less | Ordering::Equal => {
11448                                return false;
11449                            }
11450                            Ordering::Greater => break,
11451                        }
11452                    }
11453                }
11454            }
11455
11456            true
11457        })
11458    }
11459
11460    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11461    pub fn clear_row_highlights<T: 'static>(&mut self) {
11462        self.highlighted_rows.remove(&TypeId::of::<T>());
11463    }
11464
11465    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11466    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11467        self.highlighted_rows
11468            .get(&TypeId::of::<T>())
11469            .map_or(&[] as &[_], |vec| vec.as_slice())
11470            .iter()
11471            .map(|highlight| (highlight.range.clone(), highlight.color))
11472    }
11473
11474    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11475    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11476    /// Allows to ignore certain kinds of highlights.
11477    pub fn highlighted_display_rows(
11478        &mut self,
11479        cx: &mut WindowContext,
11480    ) -> BTreeMap<DisplayRow, Hsla> {
11481        let snapshot = self.snapshot(cx);
11482        let mut used_highlight_orders = HashMap::default();
11483        self.highlighted_rows
11484            .iter()
11485            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11486            .fold(
11487                BTreeMap::<DisplayRow, Hsla>::new(),
11488                |mut unique_rows, highlight| {
11489                    let start = highlight.range.start.to_display_point(&snapshot);
11490                    let end = highlight.range.end.to_display_point(&snapshot);
11491                    let start_row = start.row().0;
11492                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11493                        && end.column() == 0
11494                    {
11495                        end.row().0.saturating_sub(1)
11496                    } else {
11497                        end.row().0
11498                    };
11499                    for row in start_row..=end_row {
11500                        let used_index =
11501                            used_highlight_orders.entry(row).or_insert(highlight.index);
11502                        if highlight.index >= *used_index {
11503                            *used_index = highlight.index;
11504                            unique_rows.insert(DisplayRow(row), highlight.color);
11505                        }
11506                    }
11507                    unique_rows
11508                },
11509            )
11510    }
11511
11512    pub fn highlighted_display_row_for_autoscroll(
11513        &self,
11514        snapshot: &DisplaySnapshot,
11515    ) -> Option<DisplayRow> {
11516        self.highlighted_rows
11517            .values()
11518            .flat_map(|highlighted_rows| highlighted_rows.iter())
11519            .filter_map(|highlight| {
11520                if highlight.should_autoscroll {
11521                    Some(highlight.range.start.to_display_point(snapshot).row())
11522                } else {
11523                    None
11524                }
11525            })
11526            .min()
11527    }
11528
11529    pub fn set_search_within_ranges(
11530        &mut self,
11531        ranges: &[Range<Anchor>],
11532        cx: &mut ViewContext<Self>,
11533    ) {
11534        self.highlight_background::<SearchWithinRange>(
11535            ranges,
11536            |colors| colors.editor_document_highlight_read_background,
11537            cx,
11538        )
11539    }
11540
11541    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11542        self.breadcrumb_header = Some(new_header);
11543    }
11544
11545    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11546        self.clear_background_highlights::<SearchWithinRange>(cx);
11547    }
11548
11549    pub fn highlight_background<T: 'static>(
11550        &mut self,
11551        ranges: &[Range<Anchor>],
11552        color_fetcher: fn(&ThemeColors) -> Hsla,
11553        cx: &mut ViewContext<Self>,
11554    ) {
11555        self.background_highlights
11556            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11557        self.scrollbar_marker_state.dirty = true;
11558        cx.notify();
11559    }
11560
11561    pub fn clear_background_highlights<T: 'static>(
11562        &mut self,
11563        cx: &mut ViewContext<Self>,
11564    ) -> Option<BackgroundHighlight> {
11565        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11566        if !text_highlights.1.is_empty() {
11567            self.scrollbar_marker_state.dirty = true;
11568            cx.notify();
11569        }
11570        Some(text_highlights)
11571    }
11572
11573    pub fn highlight_gutter<T: 'static>(
11574        &mut self,
11575        ranges: &[Range<Anchor>],
11576        color_fetcher: fn(&AppContext) -> Hsla,
11577        cx: &mut ViewContext<Self>,
11578    ) {
11579        self.gutter_highlights
11580            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11581        cx.notify();
11582    }
11583
11584    pub fn clear_gutter_highlights<T: 'static>(
11585        &mut self,
11586        cx: &mut ViewContext<Self>,
11587    ) -> Option<GutterHighlight> {
11588        cx.notify();
11589        self.gutter_highlights.remove(&TypeId::of::<T>())
11590    }
11591
11592    #[cfg(feature = "test-support")]
11593    pub fn all_text_background_highlights(
11594        &mut self,
11595        cx: &mut ViewContext<Self>,
11596    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11597        let snapshot = self.snapshot(cx);
11598        let buffer = &snapshot.buffer_snapshot;
11599        let start = buffer.anchor_before(0);
11600        let end = buffer.anchor_after(buffer.len());
11601        let theme = cx.theme().colors();
11602        self.background_highlights_in_range(start..end, &snapshot, theme)
11603    }
11604
11605    #[cfg(feature = "test-support")]
11606    pub fn search_background_highlights(
11607        &mut self,
11608        cx: &mut ViewContext<Self>,
11609    ) -> Vec<Range<Point>> {
11610        let snapshot = self.buffer().read(cx).snapshot(cx);
11611
11612        let highlights = self
11613            .background_highlights
11614            .get(&TypeId::of::<items::BufferSearchHighlights>());
11615
11616        if let Some((_color, ranges)) = highlights {
11617            ranges
11618                .iter()
11619                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11620                .collect_vec()
11621        } else {
11622            vec![]
11623        }
11624    }
11625
11626    fn document_highlights_for_position<'a>(
11627        &'a self,
11628        position: Anchor,
11629        buffer: &'a MultiBufferSnapshot,
11630    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11631        let read_highlights = self
11632            .background_highlights
11633            .get(&TypeId::of::<DocumentHighlightRead>())
11634            .map(|h| &h.1);
11635        let write_highlights = self
11636            .background_highlights
11637            .get(&TypeId::of::<DocumentHighlightWrite>())
11638            .map(|h| &h.1);
11639        let left_position = position.bias_left(buffer);
11640        let right_position = position.bias_right(buffer);
11641        read_highlights
11642            .into_iter()
11643            .chain(write_highlights)
11644            .flat_map(move |ranges| {
11645                let start_ix = match ranges.binary_search_by(|probe| {
11646                    let cmp = probe.end.cmp(&left_position, buffer);
11647                    if cmp.is_ge() {
11648                        Ordering::Greater
11649                    } else {
11650                        Ordering::Less
11651                    }
11652                }) {
11653                    Ok(i) | Err(i) => i,
11654                };
11655
11656                ranges[start_ix..]
11657                    .iter()
11658                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11659            })
11660    }
11661
11662    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11663        self.background_highlights
11664            .get(&TypeId::of::<T>())
11665            .map_or(false, |(_, highlights)| !highlights.is_empty())
11666    }
11667
11668    pub fn background_highlights_in_range(
11669        &self,
11670        search_range: Range<Anchor>,
11671        display_snapshot: &DisplaySnapshot,
11672        theme: &ThemeColors,
11673    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11674        let mut results = Vec::new();
11675        for (color_fetcher, ranges) in self.background_highlights.values() {
11676            let color = color_fetcher(theme);
11677            let start_ix = match ranges.binary_search_by(|probe| {
11678                let cmp = probe
11679                    .end
11680                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11681                if cmp.is_gt() {
11682                    Ordering::Greater
11683                } else {
11684                    Ordering::Less
11685                }
11686            }) {
11687                Ok(i) | Err(i) => i,
11688            };
11689            for range in &ranges[start_ix..] {
11690                if range
11691                    .start
11692                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11693                    .is_ge()
11694                {
11695                    break;
11696                }
11697
11698                let start = range.start.to_display_point(display_snapshot);
11699                let end = range.end.to_display_point(display_snapshot);
11700                results.push((start..end, color))
11701            }
11702        }
11703        results
11704    }
11705
11706    pub fn background_highlight_row_ranges<T: 'static>(
11707        &self,
11708        search_range: Range<Anchor>,
11709        display_snapshot: &DisplaySnapshot,
11710        count: usize,
11711    ) -> Vec<RangeInclusive<DisplayPoint>> {
11712        let mut results = Vec::new();
11713        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11714            return vec![];
11715        };
11716
11717        let start_ix = match ranges.binary_search_by(|probe| {
11718            let cmp = probe
11719                .end
11720                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11721            if cmp.is_gt() {
11722                Ordering::Greater
11723            } else {
11724                Ordering::Less
11725            }
11726        }) {
11727            Ok(i) | Err(i) => i,
11728        };
11729        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11730            if let (Some(start_display), Some(end_display)) = (start, end) {
11731                results.push(
11732                    start_display.to_display_point(display_snapshot)
11733                        ..=end_display.to_display_point(display_snapshot),
11734                );
11735            }
11736        };
11737        let mut start_row: Option<Point> = None;
11738        let mut end_row: Option<Point> = None;
11739        if ranges.len() > count {
11740            return Vec::new();
11741        }
11742        for range in &ranges[start_ix..] {
11743            if range
11744                .start
11745                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11746                .is_ge()
11747            {
11748                break;
11749            }
11750            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11751            if let Some(current_row) = &end_row {
11752                if end.row == current_row.row {
11753                    continue;
11754                }
11755            }
11756            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11757            if start_row.is_none() {
11758                assert_eq!(end_row, None);
11759                start_row = Some(start);
11760                end_row = Some(end);
11761                continue;
11762            }
11763            if let Some(current_end) = end_row.as_mut() {
11764                if start.row > current_end.row + 1 {
11765                    push_region(start_row, end_row);
11766                    start_row = Some(start);
11767                    end_row = Some(end);
11768                } else {
11769                    // Merge two hunks.
11770                    *current_end = end;
11771                }
11772            } else {
11773                unreachable!();
11774            }
11775        }
11776        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11777        push_region(start_row, end_row);
11778        results
11779    }
11780
11781    pub fn gutter_highlights_in_range(
11782        &self,
11783        search_range: Range<Anchor>,
11784        display_snapshot: &DisplaySnapshot,
11785        cx: &AppContext,
11786    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11787        let mut results = Vec::new();
11788        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11789            let color = color_fetcher(cx);
11790            let start_ix = match ranges.binary_search_by(|probe| {
11791                let cmp = probe
11792                    .end
11793                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11794                if cmp.is_gt() {
11795                    Ordering::Greater
11796                } else {
11797                    Ordering::Less
11798                }
11799            }) {
11800                Ok(i) | Err(i) => i,
11801            };
11802            for range in &ranges[start_ix..] {
11803                if range
11804                    .start
11805                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11806                    .is_ge()
11807                {
11808                    break;
11809                }
11810
11811                let start = range.start.to_display_point(display_snapshot);
11812                let end = range.end.to_display_point(display_snapshot);
11813                results.push((start..end, color))
11814            }
11815        }
11816        results
11817    }
11818
11819    /// Get the text ranges corresponding to the redaction query
11820    pub fn redacted_ranges(
11821        &self,
11822        search_range: Range<Anchor>,
11823        display_snapshot: &DisplaySnapshot,
11824        cx: &WindowContext,
11825    ) -> Vec<Range<DisplayPoint>> {
11826        display_snapshot
11827            .buffer_snapshot
11828            .redacted_ranges(search_range, |file| {
11829                if let Some(file) = file {
11830                    file.is_private()
11831                        && EditorSettings::get(
11832                            Some(SettingsLocation {
11833                                worktree_id: file.worktree_id(cx),
11834                                path: file.path().as_ref(),
11835                            }),
11836                            cx,
11837                        )
11838                        .redact_private_values
11839                } else {
11840                    false
11841                }
11842            })
11843            .map(|range| {
11844                range.start.to_display_point(display_snapshot)
11845                    ..range.end.to_display_point(display_snapshot)
11846            })
11847            .collect()
11848    }
11849
11850    pub fn highlight_text<T: 'static>(
11851        &mut self,
11852        ranges: Vec<Range<Anchor>>,
11853        style: HighlightStyle,
11854        cx: &mut ViewContext<Self>,
11855    ) {
11856        self.display_map.update(cx, |map, _| {
11857            map.highlight_text(TypeId::of::<T>(), ranges, style)
11858        });
11859        cx.notify();
11860    }
11861
11862    pub(crate) fn highlight_inlays<T: 'static>(
11863        &mut self,
11864        highlights: Vec<InlayHighlight>,
11865        style: HighlightStyle,
11866        cx: &mut ViewContext<Self>,
11867    ) {
11868        self.display_map.update(cx, |map, _| {
11869            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11870        });
11871        cx.notify();
11872    }
11873
11874    pub fn text_highlights<'a, T: 'static>(
11875        &'a self,
11876        cx: &'a AppContext,
11877    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11878        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11879    }
11880
11881    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11882        let cleared = self
11883            .display_map
11884            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11885        if cleared {
11886            cx.notify();
11887        }
11888    }
11889
11890    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11891        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11892            && self.focus_handle.is_focused(cx)
11893    }
11894
11895    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11896        self.show_cursor_when_unfocused = is_enabled;
11897        cx.notify();
11898    }
11899
11900    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
11901        self.project
11902            .as_ref()
11903            .map(|project| project.read(cx).lsp_store())
11904    }
11905
11906    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11907        cx.notify();
11908    }
11909
11910    fn on_buffer_event(
11911        &mut self,
11912        multibuffer: Model<MultiBuffer>,
11913        event: &multi_buffer::Event,
11914        cx: &mut ViewContext<Self>,
11915    ) {
11916        match event {
11917            multi_buffer::Event::Edited {
11918                singleton_buffer_edited,
11919                edited_buffer: buffer_edited,
11920            } => {
11921                self.scrollbar_marker_state.dirty = true;
11922                self.active_indent_guides_state.dirty = true;
11923                self.refresh_active_diagnostics(cx);
11924                self.refresh_code_actions(cx);
11925                if self.has_active_inline_completion() {
11926                    self.update_visible_inline_completion(cx);
11927                }
11928                if let Some(buffer) = buffer_edited {
11929                    let buffer_id = buffer.read(cx).remote_id();
11930                    if !self.registered_buffers.contains_key(&buffer_id) {
11931                        if let Some(lsp_store) = self.lsp_store(cx) {
11932                            lsp_store.update(cx, |lsp_store, cx| {
11933                                self.registered_buffers.insert(
11934                                    buffer_id,
11935                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
11936                                );
11937                            })
11938                        }
11939                    }
11940                }
11941                cx.emit(EditorEvent::BufferEdited);
11942                cx.emit(SearchEvent::MatchesInvalidated);
11943                if *singleton_buffer_edited {
11944                    if let Some(project) = &self.project {
11945                        let project = project.read(cx);
11946                        #[allow(clippy::mutable_key_type)]
11947                        let languages_affected = multibuffer
11948                            .read(cx)
11949                            .all_buffers()
11950                            .into_iter()
11951                            .filter_map(|buffer| {
11952                                let buffer = buffer.read(cx);
11953                                let language = buffer.language()?;
11954                                if project.is_local()
11955                                    && project
11956                                        .language_servers_for_local_buffer(buffer, cx)
11957                                        .count()
11958                                        == 0
11959                                {
11960                                    None
11961                                } else {
11962                                    Some(language)
11963                                }
11964                            })
11965                            .cloned()
11966                            .collect::<HashSet<_>>();
11967                        if !languages_affected.is_empty() {
11968                            self.refresh_inlay_hints(
11969                                InlayHintRefreshReason::BufferEdited(languages_affected),
11970                                cx,
11971                            );
11972                        }
11973                    }
11974                }
11975
11976                let Some(project) = &self.project else { return };
11977                let (telemetry, is_via_ssh) = {
11978                    let project = project.read(cx);
11979                    let telemetry = project.client().telemetry().clone();
11980                    let is_via_ssh = project.is_via_ssh();
11981                    (telemetry, is_via_ssh)
11982                };
11983                refresh_linked_ranges(self, cx);
11984                telemetry.log_edit_event("editor", is_via_ssh);
11985            }
11986            multi_buffer::Event::ExcerptsAdded {
11987                buffer,
11988                predecessor,
11989                excerpts,
11990            } => {
11991                self.tasks_update_task = Some(self.refresh_runnables(cx));
11992                let buffer_id = buffer.read(cx).remote_id();
11993                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
11994                    if let Some(project) = &self.project {
11995                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
11996                    }
11997                }
11998                cx.emit(EditorEvent::ExcerptsAdded {
11999                    buffer: buffer.clone(),
12000                    predecessor: *predecessor,
12001                    excerpts: excerpts.clone(),
12002                });
12003                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12004            }
12005            multi_buffer::Event::ExcerptsRemoved { ids } => {
12006                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12007                let buffer = self.buffer.read(cx);
12008                self.registered_buffers
12009                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12010                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12011            }
12012            multi_buffer::Event::ExcerptsEdited { ids } => {
12013                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12014            }
12015            multi_buffer::Event::ExcerptsExpanded { ids } => {
12016                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12017            }
12018            multi_buffer::Event::Reparsed(buffer_id) => {
12019                self.tasks_update_task = Some(self.refresh_runnables(cx));
12020
12021                cx.emit(EditorEvent::Reparsed(*buffer_id));
12022            }
12023            multi_buffer::Event::LanguageChanged(buffer_id) => {
12024                linked_editing_ranges::refresh_linked_ranges(self, cx);
12025                cx.emit(EditorEvent::Reparsed(*buffer_id));
12026                cx.notify();
12027            }
12028            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12029            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12030            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12031                cx.emit(EditorEvent::TitleChanged)
12032            }
12033            // multi_buffer::Event::DiffBaseChanged => {
12034            //     self.scrollbar_marker_state.dirty = true;
12035            //     cx.emit(EditorEvent::DiffBaseChanged);
12036            //     cx.notify();
12037            // }
12038            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12039            multi_buffer::Event::DiagnosticsUpdated => {
12040                self.refresh_active_diagnostics(cx);
12041                self.scrollbar_marker_state.dirty = true;
12042                cx.notify();
12043            }
12044            _ => {}
12045        };
12046    }
12047
12048    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12049        cx.notify();
12050    }
12051
12052    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12053        self.tasks_update_task = Some(self.refresh_runnables(cx));
12054        self.refresh_inline_completion(true, false, cx);
12055        self.refresh_inlay_hints(
12056            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12057                self.selections.newest_anchor().head(),
12058                &self.buffer.read(cx).snapshot(cx),
12059                cx,
12060            )),
12061            cx,
12062        );
12063
12064        let old_cursor_shape = self.cursor_shape;
12065
12066        {
12067            let editor_settings = EditorSettings::get_global(cx);
12068            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12069            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12070            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12071        }
12072
12073        if old_cursor_shape != self.cursor_shape {
12074            cx.emit(EditorEvent::CursorShapeChanged);
12075        }
12076
12077        let project_settings = ProjectSettings::get_global(cx);
12078        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12079
12080        if self.mode == EditorMode::Full {
12081            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12082            if self.git_blame_inline_enabled != inline_blame_enabled {
12083                self.toggle_git_blame_inline_internal(false, cx);
12084            }
12085        }
12086
12087        cx.notify();
12088    }
12089
12090    pub fn set_searchable(&mut self, searchable: bool) {
12091        self.searchable = searchable;
12092    }
12093
12094    pub fn searchable(&self) -> bool {
12095        self.searchable
12096    }
12097
12098    fn open_proposed_changes_editor(
12099        &mut self,
12100        _: &OpenProposedChangesEditor,
12101        cx: &mut ViewContext<Self>,
12102    ) {
12103        let Some(workspace) = self.workspace() else {
12104            cx.propagate();
12105            return;
12106        };
12107
12108        let selections = self.selections.all::<usize>(cx);
12109        let buffer = self.buffer.read(cx);
12110        let mut new_selections_by_buffer = HashMap::default();
12111        for selection in selections {
12112            for (buffer, range, _) in
12113                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12114            {
12115                let mut range = range.to_point(buffer.read(cx));
12116                range.start.column = 0;
12117                range.end.column = buffer.read(cx).line_len(range.end.row);
12118                new_selections_by_buffer
12119                    .entry(buffer)
12120                    .or_insert(Vec::new())
12121                    .push(range)
12122            }
12123        }
12124
12125        let proposed_changes_buffers = new_selections_by_buffer
12126            .into_iter()
12127            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12128            .collect::<Vec<_>>();
12129        let proposed_changes_editor = cx.new_view(|cx| {
12130            ProposedChangesEditor::new(
12131                "Proposed changes",
12132                proposed_changes_buffers,
12133                self.project.clone(),
12134                cx,
12135            )
12136        });
12137
12138        cx.window_context().defer(move |cx| {
12139            workspace.update(cx, |workspace, cx| {
12140                workspace.active_pane().update(cx, |pane, cx| {
12141                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12142                });
12143            });
12144        });
12145    }
12146
12147    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12148        self.open_excerpts_common(None, true, cx)
12149    }
12150
12151    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12152        self.open_excerpts_common(None, false, cx)
12153    }
12154
12155    fn open_excerpts_common(
12156        &mut self,
12157        jump_data: Option<JumpData>,
12158        split: bool,
12159        cx: &mut ViewContext<Self>,
12160    ) {
12161        let Some(workspace) = self.workspace() else {
12162            cx.propagate();
12163            return;
12164        };
12165
12166        if self.buffer.read(cx).is_singleton() {
12167            cx.propagate();
12168            return;
12169        }
12170
12171        let mut new_selections_by_buffer = HashMap::default();
12172        match &jump_data {
12173            Some(jump_data) => {
12174                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12175                if let Some(buffer) = multi_buffer_snapshot
12176                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12177                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12178                {
12179                    let buffer_snapshot = buffer.read(cx).snapshot();
12180                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12181                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12182                    } else {
12183                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12184                    };
12185                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12186                    new_selections_by_buffer.insert(
12187                        buffer,
12188                        (
12189                            vec![jump_to_offset..jump_to_offset],
12190                            Some(jump_data.line_offset_from_top),
12191                        ),
12192                    );
12193                }
12194            }
12195            None => {
12196                let selections = self.selections.all::<usize>(cx);
12197                let buffer = self.buffer.read(cx);
12198                for selection in selections {
12199                    for (mut buffer_handle, mut range, _) in
12200                        buffer.range_to_buffer_ranges(selection.range(), cx)
12201                    {
12202                        // When editing branch buffers, jump to the corresponding location
12203                        // in their base buffer.
12204                        let buffer = buffer_handle.read(cx);
12205                        if let Some(base_buffer) = buffer.base_buffer() {
12206                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12207                            buffer_handle = base_buffer;
12208                        }
12209
12210                        if selection.reversed {
12211                            mem::swap(&mut range.start, &mut range.end);
12212                        }
12213                        new_selections_by_buffer
12214                            .entry(buffer_handle)
12215                            .or_insert((Vec::new(), None))
12216                            .0
12217                            .push(range)
12218                    }
12219                }
12220            }
12221        }
12222
12223        if new_selections_by_buffer.is_empty() {
12224            return;
12225        }
12226
12227        // We defer the pane interaction because we ourselves are a workspace item
12228        // and activating a new item causes the pane to call a method on us reentrantly,
12229        // which panics if we're on the stack.
12230        cx.window_context().defer(move |cx| {
12231            workspace.update(cx, |workspace, cx| {
12232                let pane = if split {
12233                    workspace.adjacent_pane(cx)
12234                } else {
12235                    workspace.active_pane().clone()
12236                };
12237
12238                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12239                    let editor = buffer
12240                        .read(cx)
12241                        .file()
12242                        .is_none()
12243                        .then(|| {
12244                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12245                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12246                            // Instead, we try to activate the existing editor in the pane first.
12247                            let (editor, pane_item_index) =
12248                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12249                                    let editor = item.downcast::<Editor>()?;
12250                                    let singleton_buffer =
12251                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12252                                    if singleton_buffer == buffer {
12253                                        Some((editor, i))
12254                                    } else {
12255                                        None
12256                                    }
12257                                })?;
12258                            pane.update(cx, |pane, cx| {
12259                                pane.activate_item(pane_item_index, true, true, cx)
12260                            });
12261                            Some(editor)
12262                        })
12263                        .flatten()
12264                        .unwrap_or_else(|| {
12265                            workspace.open_project_item::<Self>(
12266                                pane.clone(),
12267                                buffer,
12268                                true,
12269                                true,
12270                                cx,
12271                            )
12272                        });
12273
12274                    editor.update(cx, |editor, cx| {
12275                        let autoscroll = match scroll_offset {
12276                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12277                            None => Autoscroll::newest(),
12278                        };
12279                        let nav_history = editor.nav_history.take();
12280                        editor.change_selections(Some(autoscroll), cx, |s| {
12281                            s.select_ranges(ranges);
12282                        });
12283                        editor.nav_history = nav_history;
12284                    });
12285                }
12286            })
12287        });
12288    }
12289
12290    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12291        let snapshot = self.buffer.read(cx).read(cx);
12292        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12293        Some(
12294            ranges
12295                .iter()
12296                .map(move |range| {
12297                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12298                })
12299                .collect(),
12300        )
12301    }
12302
12303    fn selection_replacement_ranges(
12304        &self,
12305        range: Range<OffsetUtf16>,
12306        cx: &mut AppContext,
12307    ) -> Vec<Range<OffsetUtf16>> {
12308        let selections = self.selections.all::<OffsetUtf16>(cx);
12309        let newest_selection = selections
12310            .iter()
12311            .max_by_key(|selection| selection.id)
12312            .unwrap();
12313        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12314        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12315        let snapshot = self.buffer.read(cx).read(cx);
12316        selections
12317            .into_iter()
12318            .map(|mut selection| {
12319                selection.start.0 =
12320                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12321                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12322                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12323                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12324            })
12325            .collect()
12326    }
12327
12328    fn report_editor_event(
12329        &self,
12330        operation: &'static str,
12331        file_extension: Option<String>,
12332        cx: &AppContext,
12333    ) {
12334        if cfg!(any(test, feature = "test-support")) {
12335            return;
12336        }
12337
12338        let Some(project) = &self.project else { return };
12339
12340        // If None, we are in a file without an extension
12341        let file = self
12342            .buffer
12343            .read(cx)
12344            .as_singleton()
12345            .and_then(|b| b.read(cx).file());
12346        let file_extension = file_extension.or(file
12347            .as_ref()
12348            .and_then(|file| Path::new(file.file_name(cx)).extension())
12349            .and_then(|e| e.to_str())
12350            .map(|a| a.to_string()));
12351
12352        let vim_mode = cx
12353            .global::<SettingsStore>()
12354            .raw_user_settings()
12355            .get("vim_mode")
12356            == Some(&serde_json::Value::Bool(true));
12357
12358        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12359            == language::language_settings::InlineCompletionProvider::Copilot;
12360        let copilot_enabled_for_language = self
12361            .buffer
12362            .read(cx)
12363            .settings_at(0, cx)
12364            .show_inline_completions;
12365
12366        let project = project.read(cx);
12367        let telemetry = project.client().telemetry().clone();
12368        telemetry.report_editor_event(
12369            file_extension,
12370            vim_mode,
12371            operation,
12372            copilot_enabled,
12373            copilot_enabled_for_language,
12374            project.is_via_ssh(),
12375        )
12376    }
12377
12378    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12379    /// with each line being an array of {text, highlight} objects.
12380    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12381        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12382            return;
12383        };
12384
12385        #[derive(Serialize)]
12386        struct Chunk<'a> {
12387            text: String,
12388            highlight: Option<&'a str>,
12389        }
12390
12391        let snapshot = buffer.read(cx).snapshot();
12392        let range = self
12393            .selected_text_range(false, cx)
12394            .and_then(|selection| {
12395                if selection.range.is_empty() {
12396                    None
12397                } else {
12398                    Some(selection.range)
12399                }
12400            })
12401            .unwrap_or_else(|| 0..snapshot.len());
12402
12403        let chunks = snapshot.chunks(range, true);
12404        let mut lines = Vec::new();
12405        let mut line: VecDeque<Chunk> = VecDeque::new();
12406
12407        let Some(style) = self.style.as_ref() else {
12408            return;
12409        };
12410
12411        for chunk in chunks {
12412            let highlight = chunk
12413                .syntax_highlight_id
12414                .and_then(|id| id.name(&style.syntax));
12415            let mut chunk_lines = chunk.text.split('\n').peekable();
12416            while let Some(text) = chunk_lines.next() {
12417                let mut merged_with_last_token = false;
12418                if let Some(last_token) = line.back_mut() {
12419                    if last_token.highlight == highlight {
12420                        last_token.text.push_str(text);
12421                        merged_with_last_token = true;
12422                    }
12423                }
12424
12425                if !merged_with_last_token {
12426                    line.push_back(Chunk {
12427                        text: text.into(),
12428                        highlight,
12429                    });
12430                }
12431
12432                if chunk_lines.peek().is_some() {
12433                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12434                        line.pop_front();
12435                    }
12436                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12437                        line.pop_back();
12438                    }
12439
12440                    lines.push(mem::take(&mut line));
12441                }
12442            }
12443        }
12444
12445        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12446            return;
12447        };
12448        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12449    }
12450
12451    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12452        self.request_autoscroll(Autoscroll::newest(), cx);
12453        let position = self.selections.newest_display(cx).start;
12454        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12455    }
12456
12457    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12458        &self.inlay_hint_cache
12459    }
12460
12461    pub fn replay_insert_event(
12462        &mut self,
12463        text: &str,
12464        relative_utf16_range: Option<Range<isize>>,
12465        cx: &mut ViewContext<Self>,
12466    ) {
12467        if !self.input_enabled {
12468            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12469            return;
12470        }
12471        if let Some(relative_utf16_range) = relative_utf16_range {
12472            let selections = self.selections.all::<OffsetUtf16>(cx);
12473            self.change_selections(None, cx, |s| {
12474                let new_ranges = selections.into_iter().map(|range| {
12475                    let start = OffsetUtf16(
12476                        range
12477                            .head()
12478                            .0
12479                            .saturating_add_signed(relative_utf16_range.start),
12480                    );
12481                    let end = OffsetUtf16(
12482                        range
12483                            .head()
12484                            .0
12485                            .saturating_add_signed(relative_utf16_range.end),
12486                    );
12487                    start..end
12488                });
12489                s.select_ranges(new_ranges);
12490            });
12491        }
12492
12493        self.handle_input(text, cx);
12494    }
12495
12496    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12497        let Some(provider) = self.semantics_provider.as_ref() else {
12498            return false;
12499        };
12500
12501        let mut supports = false;
12502        self.buffer().read(cx).for_each_buffer(|buffer| {
12503            supports |= provider.supports_inlay_hints(buffer, cx);
12504        });
12505        supports
12506    }
12507
12508    pub fn focus(&self, cx: &mut WindowContext) {
12509        cx.focus(&self.focus_handle)
12510    }
12511
12512    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12513        self.focus_handle.is_focused(cx)
12514    }
12515
12516    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12517        cx.emit(EditorEvent::Focused);
12518
12519        if let Some(descendant) = self
12520            .last_focused_descendant
12521            .take()
12522            .and_then(|descendant| descendant.upgrade())
12523        {
12524            cx.focus(&descendant);
12525        } else {
12526            if let Some(blame) = self.blame.as_ref() {
12527                blame.update(cx, GitBlame::focus)
12528            }
12529
12530            self.blink_manager.update(cx, BlinkManager::enable);
12531            self.show_cursor_names(cx);
12532            self.buffer.update(cx, |buffer, cx| {
12533                buffer.finalize_last_transaction(cx);
12534                if self.leader_peer_id.is_none() {
12535                    buffer.set_active_selections(
12536                        &self.selections.disjoint_anchors(),
12537                        self.selections.line_mode,
12538                        self.cursor_shape,
12539                        cx,
12540                    );
12541                }
12542            });
12543        }
12544    }
12545
12546    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12547        cx.emit(EditorEvent::FocusedIn)
12548    }
12549
12550    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12551        if event.blurred != self.focus_handle {
12552            self.last_focused_descendant = Some(event.blurred);
12553        }
12554    }
12555
12556    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12557        self.blink_manager.update(cx, BlinkManager::disable);
12558        self.buffer
12559            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12560
12561        if let Some(blame) = self.blame.as_ref() {
12562            blame.update(cx, GitBlame::blur)
12563        }
12564        if !self.hover_state.focused(cx) {
12565            hide_hover(self, cx);
12566        }
12567
12568        self.hide_context_menu(cx);
12569        cx.emit(EditorEvent::Blurred);
12570        cx.notify();
12571    }
12572
12573    pub fn register_action<A: Action>(
12574        &mut self,
12575        listener: impl Fn(&A, &mut WindowContext) + 'static,
12576    ) -> Subscription {
12577        let id = self.next_editor_action_id.post_inc();
12578        let listener = Arc::new(listener);
12579        self.editor_actions.borrow_mut().insert(
12580            id,
12581            Box::new(move |cx| {
12582                let cx = cx.window_context();
12583                let listener = listener.clone();
12584                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12585                    let action = action.downcast_ref().unwrap();
12586                    if phase == DispatchPhase::Bubble {
12587                        listener(action, cx)
12588                    }
12589                })
12590            }),
12591        );
12592
12593        let editor_actions = self.editor_actions.clone();
12594        Subscription::new(move || {
12595            editor_actions.borrow_mut().remove(&id);
12596        })
12597    }
12598
12599    pub fn file_header_size(&self) -> u32 {
12600        FILE_HEADER_HEIGHT
12601    }
12602
12603    pub fn revert(
12604        &mut self,
12605        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12606        cx: &mut ViewContext<Self>,
12607    ) {
12608        self.buffer().update(cx, |multi_buffer, cx| {
12609            for (buffer_id, changes) in revert_changes {
12610                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12611                    buffer.update(cx, |buffer, cx| {
12612                        buffer.edit(
12613                            changes.into_iter().map(|(range, text)| {
12614                                (range, text.to_string().map(Arc::<str>::from))
12615                            }),
12616                            None,
12617                            cx,
12618                        );
12619                    });
12620                }
12621            }
12622        });
12623        self.change_selections(None, cx, |selections| selections.refresh());
12624    }
12625
12626    pub fn to_pixel_point(
12627        &mut self,
12628        source: multi_buffer::Anchor,
12629        editor_snapshot: &EditorSnapshot,
12630        cx: &mut ViewContext<Self>,
12631    ) -> Option<gpui::Point<Pixels>> {
12632        let source_point = source.to_display_point(editor_snapshot);
12633        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12634    }
12635
12636    pub fn display_to_pixel_point(
12637        &self,
12638        source: DisplayPoint,
12639        editor_snapshot: &EditorSnapshot,
12640        cx: &WindowContext,
12641    ) -> Option<gpui::Point<Pixels>> {
12642        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12643        let text_layout_details = self.text_layout_details(cx);
12644        let scroll_top = text_layout_details
12645            .scroll_anchor
12646            .scroll_position(editor_snapshot)
12647            .y;
12648
12649        if source.row().as_f32() < scroll_top.floor() {
12650            return None;
12651        }
12652        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12653        let source_y = line_height * (source.row().as_f32() - scroll_top);
12654        Some(gpui::Point::new(source_x, source_y))
12655    }
12656
12657    pub fn has_active_completions_menu(&self) -> bool {
12658        self.context_menu.read().as_ref().map_or(false, |menu| {
12659            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12660        })
12661    }
12662
12663    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12664        self.addons
12665            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12666    }
12667
12668    pub fn unregister_addon<T: Addon>(&mut self) {
12669        self.addons.remove(&std::any::TypeId::of::<T>());
12670    }
12671
12672    pub fn addon<T: Addon>(&self) -> Option<&T> {
12673        let type_id = std::any::TypeId::of::<T>();
12674        self.addons
12675            .get(&type_id)
12676            .and_then(|item| item.to_any().downcast_ref::<T>())
12677    }
12678
12679    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12680        let text_layout_details = self.text_layout_details(cx);
12681        let style = &text_layout_details.editor_style;
12682        let font_id = cx.text_system().resolve_font(&style.text.font());
12683        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12684        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12685
12686        let em_width = cx
12687            .text_system()
12688            .typographic_bounds(font_id, font_size, 'm')
12689            .unwrap()
12690            .size
12691            .width;
12692
12693        gpui::Point::new(em_width, line_height)
12694    }
12695}
12696
12697fn get_unstaged_changes_for_buffers(
12698    project: &Model<Project>,
12699    buffers: impl IntoIterator<Item = Model<Buffer>>,
12700    cx: &mut ViewContext<Editor>,
12701) {
12702    let mut tasks = Vec::new();
12703    project.update(cx, |project, cx| {
12704        for buffer in buffers {
12705            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12706        }
12707    });
12708    cx.spawn(|this, mut cx| async move {
12709        let change_sets = futures::future::join_all(tasks).await;
12710        this.update(&mut cx, |this, cx| {
12711            for change_set in change_sets {
12712                if let Some(change_set) = change_set.log_err() {
12713                    this.diff_map.add_change_set(change_set, cx);
12714                }
12715            }
12716        })
12717        .ok();
12718    })
12719    .detach();
12720}
12721
12722fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12723    let tab_size = tab_size.get() as usize;
12724    let mut width = offset;
12725
12726    for ch in text.chars() {
12727        width += if ch == '\t' {
12728            tab_size - (width % tab_size)
12729        } else {
12730            1
12731        };
12732    }
12733
12734    width - offset
12735}
12736
12737#[cfg(test)]
12738mod tests {
12739    use super::*;
12740
12741    #[test]
12742    fn test_string_size_with_expanded_tabs() {
12743        let nz = |val| NonZeroU32::new(val).unwrap();
12744        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12745        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12746        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12747        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12748        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12749        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12750        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12751        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12752    }
12753}
12754
12755/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12756struct WordBreakingTokenizer<'a> {
12757    input: &'a str,
12758}
12759
12760impl<'a> WordBreakingTokenizer<'a> {
12761    fn new(input: &'a str) -> Self {
12762        Self { input }
12763    }
12764}
12765
12766fn is_char_ideographic(ch: char) -> bool {
12767    use unicode_script::Script::*;
12768    use unicode_script::UnicodeScript;
12769    matches!(ch.script(), Han | Tangut | Yi)
12770}
12771
12772fn is_grapheme_ideographic(text: &str) -> bool {
12773    text.chars().any(is_char_ideographic)
12774}
12775
12776fn is_grapheme_whitespace(text: &str) -> bool {
12777    text.chars().any(|x| x.is_whitespace())
12778}
12779
12780fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12781    text.chars().next().map_or(false, |ch| {
12782        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12783    })
12784}
12785
12786#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12787struct WordBreakToken<'a> {
12788    token: &'a str,
12789    grapheme_len: usize,
12790    is_whitespace: bool,
12791}
12792
12793impl<'a> Iterator for WordBreakingTokenizer<'a> {
12794    /// Yields a span, the count of graphemes in the token, and whether it was
12795    /// whitespace. Note that it also breaks at word boundaries.
12796    type Item = WordBreakToken<'a>;
12797
12798    fn next(&mut self) -> Option<Self::Item> {
12799        use unicode_segmentation::UnicodeSegmentation;
12800        if self.input.is_empty() {
12801            return None;
12802        }
12803
12804        let mut iter = self.input.graphemes(true).peekable();
12805        let mut offset = 0;
12806        let mut graphemes = 0;
12807        if let Some(first_grapheme) = iter.next() {
12808            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12809            offset += first_grapheme.len();
12810            graphemes += 1;
12811            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12812                if let Some(grapheme) = iter.peek().copied() {
12813                    if should_stay_with_preceding_ideograph(grapheme) {
12814                        offset += grapheme.len();
12815                        graphemes += 1;
12816                    }
12817                }
12818            } else {
12819                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12820                let mut next_word_bound = words.peek().copied();
12821                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12822                    next_word_bound = words.next();
12823                }
12824                while let Some(grapheme) = iter.peek().copied() {
12825                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12826                        break;
12827                    };
12828                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12829                        break;
12830                    };
12831                    offset += grapheme.len();
12832                    graphemes += 1;
12833                    iter.next();
12834                }
12835            }
12836            let token = &self.input[..offset];
12837            self.input = &self.input[offset..];
12838            if is_whitespace {
12839                Some(WordBreakToken {
12840                    token: " ",
12841                    grapheme_len: 1,
12842                    is_whitespace: true,
12843                })
12844            } else {
12845                Some(WordBreakToken {
12846                    token,
12847                    grapheme_len: graphemes,
12848                    is_whitespace: false,
12849                })
12850            }
12851        } else {
12852            None
12853        }
12854    }
12855}
12856
12857#[test]
12858fn test_word_breaking_tokenizer() {
12859    let tests: &[(&str, &[(&str, usize, bool)])] = &[
12860        ("", &[]),
12861        ("  ", &[(" ", 1, true)]),
12862        ("Ʒ", &[("Ʒ", 1, false)]),
12863        ("Ǽ", &[("Ǽ", 1, false)]),
12864        ("", &[("", 1, false)]),
12865        ("⋑⋑", &[("⋑⋑", 2, false)]),
12866        (
12867            "原理,进而",
12868            &[
12869                ("", 1, false),
12870                ("理,", 2, false),
12871                ("", 1, false),
12872                ("", 1, false),
12873            ],
12874        ),
12875        (
12876            "hello world",
12877            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12878        ),
12879        (
12880            "hello, world",
12881            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12882        ),
12883        (
12884            "  hello world",
12885            &[
12886                (" ", 1, true),
12887                ("hello", 5, false),
12888                (" ", 1, true),
12889                ("world", 5, false),
12890            ],
12891        ),
12892        (
12893            "这是什么 \n 钢笔",
12894            &[
12895                ("", 1, false),
12896                ("", 1, false),
12897                ("", 1, false),
12898                ("", 1, false),
12899                (" ", 1, true),
12900                ("", 1, false),
12901                ("", 1, false),
12902            ],
12903        ),
12904        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12905    ];
12906
12907    for (input, result) in tests {
12908        assert_eq!(
12909            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12910            result
12911                .iter()
12912                .copied()
12913                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12914                    token,
12915                    grapheme_len,
12916                    is_whitespace,
12917                })
12918                .collect::<Vec<_>>()
12919        );
12920    }
12921}
12922
12923fn wrap_with_prefix(
12924    line_prefix: String,
12925    unwrapped_text: String,
12926    wrap_column: usize,
12927    tab_size: NonZeroU32,
12928) -> String {
12929    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12930    let mut wrapped_text = String::new();
12931    let mut current_line = line_prefix.clone();
12932
12933    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12934    let mut current_line_len = line_prefix_len;
12935    for WordBreakToken {
12936        token,
12937        grapheme_len,
12938        is_whitespace,
12939    } in tokenizer
12940    {
12941        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12942            wrapped_text.push_str(current_line.trim_end());
12943            wrapped_text.push('\n');
12944            current_line.truncate(line_prefix.len());
12945            current_line_len = line_prefix_len;
12946            if !is_whitespace {
12947                current_line.push_str(token);
12948                current_line_len += grapheme_len;
12949            }
12950        } else if !is_whitespace {
12951            current_line.push_str(token);
12952            current_line_len += grapheme_len;
12953        } else if current_line_len != line_prefix_len {
12954            current_line.push(' ');
12955            current_line_len += 1;
12956        }
12957    }
12958
12959    if !current_line.is_empty() {
12960        wrapped_text.push_str(&current_line);
12961    }
12962    wrapped_text
12963}
12964
12965#[test]
12966fn test_wrap_with_prefix() {
12967    assert_eq!(
12968        wrap_with_prefix(
12969            "# ".to_string(),
12970            "abcdefg".to_string(),
12971            4,
12972            NonZeroU32::new(4).unwrap()
12973        ),
12974        "# abcdefg"
12975    );
12976    assert_eq!(
12977        wrap_with_prefix(
12978            "".to_string(),
12979            "\thello world".to_string(),
12980            8,
12981            NonZeroU32::new(4).unwrap()
12982        ),
12983        "hello\nworld"
12984    );
12985    assert_eq!(
12986        wrap_with_prefix(
12987            "// ".to_string(),
12988            "xx \nyy zz aa bb cc".to_string(),
12989            12,
12990            NonZeroU32::new(4).unwrap()
12991        ),
12992        "// xx yy zz\n// aa bb cc"
12993    );
12994    assert_eq!(
12995        wrap_with_prefix(
12996            String::new(),
12997            "这是什么 \n 钢笔".to_string(),
12998            3,
12999            NonZeroU32::new(4).unwrap()
13000        ),
13001        "这是什\n么 钢\n"
13002    );
13003}
13004
13005fn hunks_for_selections(
13006    snapshot: &EditorSnapshot,
13007    selections: &[Selection<Point>],
13008) -> Vec<MultiBufferDiffHunk> {
13009    hunks_for_ranges(
13010        selections.iter().map(|selection| selection.range()),
13011        snapshot,
13012    )
13013}
13014
13015pub fn hunks_for_ranges(
13016    ranges: impl Iterator<Item = Range<Point>>,
13017    snapshot: &EditorSnapshot,
13018) -> Vec<MultiBufferDiffHunk> {
13019    let mut hunks = Vec::new();
13020    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13021        HashMap::default();
13022    for query_range in ranges {
13023        let query_rows =
13024            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13025        for hunk in snapshot.diff_map.diff_hunks_in_range(
13026            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13027            &snapshot.buffer_snapshot,
13028        ) {
13029            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13030            // when the caret is just above or just below the deleted hunk.
13031            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13032            let related_to_selection = if allow_adjacent {
13033                hunk.row_range.overlaps(&query_rows)
13034                    || hunk.row_range.start == query_rows.end
13035                    || hunk.row_range.end == query_rows.start
13036            } else {
13037                hunk.row_range.overlaps(&query_rows)
13038            };
13039            if related_to_selection {
13040                if !processed_buffer_rows
13041                    .entry(hunk.buffer_id)
13042                    .or_default()
13043                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13044                {
13045                    continue;
13046                }
13047                hunks.push(hunk);
13048            }
13049        }
13050    }
13051
13052    hunks
13053}
13054
13055pub trait CollaborationHub {
13056    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13057    fn user_participant_indices<'a>(
13058        &self,
13059        cx: &'a AppContext,
13060    ) -> &'a HashMap<u64, ParticipantIndex>;
13061    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13062}
13063
13064impl CollaborationHub for Model<Project> {
13065    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13066        self.read(cx).collaborators()
13067    }
13068
13069    fn user_participant_indices<'a>(
13070        &self,
13071        cx: &'a AppContext,
13072    ) -> &'a HashMap<u64, ParticipantIndex> {
13073        self.read(cx).user_store().read(cx).participant_indices()
13074    }
13075
13076    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13077        let this = self.read(cx);
13078        let user_ids = this.collaborators().values().map(|c| c.user_id);
13079        this.user_store().read_with(cx, |user_store, cx| {
13080            user_store.participant_names(user_ids, cx)
13081        })
13082    }
13083}
13084
13085pub trait SemanticsProvider {
13086    fn hover(
13087        &self,
13088        buffer: &Model<Buffer>,
13089        position: text::Anchor,
13090        cx: &mut AppContext,
13091    ) -> Option<Task<Vec<project::Hover>>>;
13092
13093    fn inlay_hints(
13094        &self,
13095        buffer_handle: Model<Buffer>,
13096        range: Range<text::Anchor>,
13097        cx: &mut AppContext,
13098    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13099
13100    fn resolve_inlay_hint(
13101        &self,
13102        hint: InlayHint,
13103        buffer_handle: Model<Buffer>,
13104        server_id: LanguageServerId,
13105        cx: &mut AppContext,
13106    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13107
13108    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13109
13110    fn document_highlights(
13111        &self,
13112        buffer: &Model<Buffer>,
13113        position: text::Anchor,
13114        cx: &mut AppContext,
13115    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13116
13117    fn definitions(
13118        &self,
13119        buffer: &Model<Buffer>,
13120        position: text::Anchor,
13121        kind: GotoDefinitionKind,
13122        cx: &mut AppContext,
13123    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13124
13125    fn range_for_rename(
13126        &self,
13127        buffer: &Model<Buffer>,
13128        position: text::Anchor,
13129        cx: &mut AppContext,
13130    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13131
13132    fn perform_rename(
13133        &self,
13134        buffer: &Model<Buffer>,
13135        position: text::Anchor,
13136        new_name: String,
13137        cx: &mut AppContext,
13138    ) -> Option<Task<Result<ProjectTransaction>>>;
13139}
13140
13141pub trait CompletionProvider {
13142    fn completions(
13143        &self,
13144        buffer: &Model<Buffer>,
13145        buffer_position: text::Anchor,
13146        trigger: CompletionContext,
13147        cx: &mut ViewContext<Editor>,
13148    ) -> Task<Result<Vec<Completion>>>;
13149
13150    fn resolve_completions(
13151        &self,
13152        buffer: Model<Buffer>,
13153        completion_indices: Vec<usize>,
13154        completions: Arc<RwLock<Box<[Completion]>>>,
13155        cx: &mut ViewContext<Editor>,
13156    ) -> Task<Result<bool>>;
13157
13158    fn apply_additional_edits_for_completion(
13159        &self,
13160        buffer: Model<Buffer>,
13161        completion: Completion,
13162        push_to_history: bool,
13163        cx: &mut ViewContext<Editor>,
13164    ) -> Task<Result<Option<language::Transaction>>>;
13165
13166    fn is_completion_trigger(
13167        &self,
13168        buffer: &Model<Buffer>,
13169        position: language::Anchor,
13170        text: &str,
13171        trigger_in_words: bool,
13172        cx: &mut ViewContext<Editor>,
13173    ) -> bool;
13174
13175    fn sort_completions(&self) -> bool {
13176        true
13177    }
13178}
13179
13180pub trait CodeActionProvider {
13181    fn code_actions(
13182        &self,
13183        buffer: &Model<Buffer>,
13184        range: Range<text::Anchor>,
13185        cx: &mut WindowContext,
13186    ) -> Task<Result<Vec<CodeAction>>>;
13187
13188    fn apply_code_action(
13189        &self,
13190        buffer_handle: Model<Buffer>,
13191        action: CodeAction,
13192        excerpt_id: ExcerptId,
13193        push_to_history: bool,
13194        cx: &mut WindowContext,
13195    ) -> Task<Result<ProjectTransaction>>;
13196}
13197
13198impl CodeActionProvider for Model<Project> {
13199    fn code_actions(
13200        &self,
13201        buffer: &Model<Buffer>,
13202        range: Range<text::Anchor>,
13203        cx: &mut WindowContext,
13204    ) -> Task<Result<Vec<CodeAction>>> {
13205        self.update(cx, |project, cx| {
13206            project.code_actions(buffer, range, None, cx)
13207        })
13208    }
13209
13210    fn apply_code_action(
13211        &self,
13212        buffer_handle: Model<Buffer>,
13213        action: CodeAction,
13214        _excerpt_id: ExcerptId,
13215        push_to_history: bool,
13216        cx: &mut WindowContext,
13217    ) -> Task<Result<ProjectTransaction>> {
13218        self.update(cx, |project, cx| {
13219            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13220        })
13221    }
13222}
13223
13224fn snippet_completions(
13225    project: &Project,
13226    buffer: &Model<Buffer>,
13227    buffer_position: text::Anchor,
13228    cx: &mut AppContext,
13229) -> Task<Result<Vec<Completion>>> {
13230    let language = buffer.read(cx).language_at(buffer_position);
13231    let language_name = language.as_ref().map(|language| language.lsp_id());
13232    let snippet_store = project.snippets().read(cx);
13233    let snippets = snippet_store.snippets_for(language_name, cx);
13234
13235    if snippets.is_empty() {
13236        return Task::ready(Ok(vec![]));
13237    }
13238    let snapshot = buffer.read(cx).text_snapshot();
13239    let chars: String = snapshot
13240        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13241        .collect();
13242
13243    let scope = language.map(|language| language.default_scope());
13244    let executor = cx.background_executor().clone();
13245
13246    cx.background_executor().spawn(async move {
13247        let classifier = CharClassifier::new(scope).for_completion(true);
13248        let mut last_word = chars
13249            .chars()
13250            .take_while(|c| classifier.is_word(*c))
13251            .collect::<String>();
13252        last_word = last_word.chars().rev().collect();
13253
13254        if last_word.is_empty() {
13255            return Ok(vec![]);
13256        }
13257
13258        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13259        let to_lsp = |point: &text::Anchor| {
13260            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13261            point_to_lsp(end)
13262        };
13263        let lsp_end = to_lsp(&buffer_position);
13264
13265        let candidates = snippets
13266            .iter()
13267            .enumerate()
13268            .flat_map(|(ix, snippet)| {
13269                snippet
13270                    .prefix
13271                    .iter()
13272                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13273            })
13274            .collect::<Vec<StringMatchCandidate>>();
13275
13276        let mut matches = fuzzy::match_strings(
13277            &candidates,
13278            &last_word,
13279            last_word.chars().any(|c| c.is_uppercase()),
13280            100,
13281            &Default::default(),
13282            executor,
13283        )
13284        .await;
13285
13286        // Remove all candidates where the query's start does not match the start of any word in the candidate
13287        if let Some(query_start) = last_word.chars().next() {
13288            matches.retain(|string_match| {
13289                split_words(&string_match.string).any(|word| {
13290                    // Check that the first codepoint of the word as lowercase matches the first
13291                    // codepoint of the query as lowercase
13292                    word.chars()
13293                        .flat_map(|codepoint| codepoint.to_lowercase())
13294                        .zip(query_start.to_lowercase())
13295                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13296                })
13297            });
13298        }
13299
13300        let matched_strings = matches
13301            .into_iter()
13302            .map(|m| m.string)
13303            .collect::<HashSet<_>>();
13304
13305        let result: Vec<Completion> = snippets
13306            .into_iter()
13307            .filter_map(|snippet| {
13308                let matching_prefix = snippet
13309                    .prefix
13310                    .iter()
13311                    .find(|prefix| matched_strings.contains(*prefix))?;
13312                let start = as_offset - last_word.len();
13313                let start = snapshot.anchor_before(start);
13314                let range = start..buffer_position;
13315                let lsp_start = to_lsp(&start);
13316                let lsp_range = lsp::Range {
13317                    start: lsp_start,
13318                    end: lsp_end,
13319                };
13320                Some(Completion {
13321                    old_range: range,
13322                    new_text: snippet.body.clone(),
13323                    label: CodeLabel {
13324                        text: matching_prefix.clone(),
13325                        runs: vec![],
13326                        filter_range: 0..matching_prefix.len(),
13327                    },
13328                    server_id: LanguageServerId(usize::MAX),
13329                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13330                    lsp_completion: lsp::CompletionItem {
13331                        label: snippet.prefix.first().unwrap().clone(),
13332                        kind: Some(CompletionItemKind::SNIPPET),
13333                        label_details: snippet.description.as_ref().map(|description| {
13334                            lsp::CompletionItemLabelDetails {
13335                                detail: Some(description.clone()),
13336                                description: None,
13337                            }
13338                        }),
13339                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13340                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13341                            lsp::InsertReplaceEdit {
13342                                new_text: snippet.body.clone(),
13343                                insert: lsp_range,
13344                                replace: lsp_range,
13345                            },
13346                        )),
13347                        filter_text: Some(snippet.body.clone()),
13348                        sort_text: Some(char::MAX.to_string()),
13349                        ..Default::default()
13350                    },
13351                    confirm: None,
13352                })
13353            })
13354            .collect();
13355
13356        Ok(result)
13357    })
13358}
13359
13360impl CompletionProvider for Model<Project> {
13361    fn completions(
13362        &self,
13363        buffer: &Model<Buffer>,
13364        buffer_position: text::Anchor,
13365        options: CompletionContext,
13366        cx: &mut ViewContext<Editor>,
13367    ) -> Task<Result<Vec<Completion>>> {
13368        self.update(cx, |project, cx| {
13369            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13370            let project_completions = project.completions(buffer, buffer_position, options, cx);
13371            cx.background_executor().spawn(async move {
13372                let mut completions = project_completions.await?;
13373                let snippets_completions = snippets.await?;
13374                completions.extend(snippets_completions);
13375                Ok(completions)
13376            })
13377        })
13378    }
13379
13380    fn resolve_completions(
13381        &self,
13382        buffer: Model<Buffer>,
13383        completion_indices: Vec<usize>,
13384        completions: Arc<RwLock<Box<[Completion]>>>,
13385        cx: &mut ViewContext<Editor>,
13386    ) -> Task<Result<bool>> {
13387        self.update(cx, |project, cx| {
13388            project.resolve_completions(buffer, completion_indices, completions, cx)
13389        })
13390    }
13391
13392    fn apply_additional_edits_for_completion(
13393        &self,
13394        buffer: Model<Buffer>,
13395        completion: Completion,
13396        push_to_history: bool,
13397        cx: &mut ViewContext<Editor>,
13398    ) -> Task<Result<Option<language::Transaction>>> {
13399        self.update(cx, |project, cx| {
13400            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13401        })
13402    }
13403
13404    fn is_completion_trigger(
13405        &self,
13406        buffer: &Model<Buffer>,
13407        position: language::Anchor,
13408        text: &str,
13409        trigger_in_words: bool,
13410        cx: &mut ViewContext<Editor>,
13411    ) -> bool {
13412        let mut chars = text.chars();
13413        let char = if let Some(char) = chars.next() {
13414            char
13415        } else {
13416            return false;
13417        };
13418        if chars.next().is_some() {
13419            return false;
13420        }
13421
13422        let buffer = buffer.read(cx);
13423        let snapshot = buffer.snapshot();
13424        if !snapshot.settings_at(position, cx).show_completions_on_input {
13425            return false;
13426        }
13427        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13428        if trigger_in_words && classifier.is_word(char) {
13429            return true;
13430        }
13431
13432        buffer.completion_triggers().contains(text)
13433    }
13434}
13435
13436impl SemanticsProvider for Model<Project> {
13437    fn hover(
13438        &self,
13439        buffer: &Model<Buffer>,
13440        position: text::Anchor,
13441        cx: &mut AppContext,
13442    ) -> Option<Task<Vec<project::Hover>>> {
13443        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13444    }
13445
13446    fn document_highlights(
13447        &self,
13448        buffer: &Model<Buffer>,
13449        position: text::Anchor,
13450        cx: &mut AppContext,
13451    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13452        Some(self.update(cx, |project, cx| {
13453            project.document_highlights(buffer, position, cx)
13454        }))
13455    }
13456
13457    fn definitions(
13458        &self,
13459        buffer: &Model<Buffer>,
13460        position: text::Anchor,
13461        kind: GotoDefinitionKind,
13462        cx: &mut AppContext,
13463    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13464        Some(self.update(cx, |project, cx| match kind {
13465            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13466            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13467            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13468            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13469        }))
13470    }
13471
13472    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13473        // TODO: make this work for remote projects
13474        self.read(cx)
13475            .language_servers_for_local_buffer(buffer.read(cx), cx)
13476            .any(
13477                |(_, server)| match server.capabilities().inlay_hint_provider {
13478                    Some(lsp::OneOf::Left(enabled)) => enabled,
13479                    Some(lsp::OneOf::Right(_)) => true,
13480                    None => false,
13481                },
13482            )
13483    }
13484
13485    fn inlay_hints(
13486        &self,
13487        buffer_handle: Model<Buffer>,
13488        range: Range<text::Anchor>,
13489        cx: &mut AppContext,
13490    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13491        Some(self.update(cx, |project, cx| {
13492            project.inlay_hints(buffer_handle, range, cx)
13493        }))
13494    }
13495
13496    fn resolve_inlay_hint(
13497        &self,
13498        hint: InlayHint,
13499        buffer_handle: Model<Buffer>,
13500        server_id: LanguageServerId,
13501        cx: &mut AppContext,
13502    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13503        Some(self.update(cx, |project, cx| {
13504            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13505        }))
13506    }
13507
13508    fn range_for_rename(
13509        &self,
13510        buffer: &Model<Buffer>,
13511        position: text::Anchor,
13512        cx: &mut AppContext,
13513    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13514        Some(self.update(cx, |project, cx| {
13515            project.prepare_rename(buffer.clone(), position, cx)
13516        }))
13517    }
13518
13519    fn perform_rename(
13520        &self,
13521        buffer: &Model<Buffer>,
13522        position: text::Anchor,
13523        new_name: String,
13524        cx: &mut AppContext,
13525    ) -> Option<Task<Result<ProjectTransaction>>> {
13526        Some(self.update(cx, |project, cx| {
13527            project.perform_rename(buffer.clone(), position, new_name, cx)
13528        }))
13529    }
13530}
13531
13532fn inlay_hint_settings(
13533    location: Anchor,
13534    snapshot: &MultiBufferSnapshot,
13535    cx: &mut ViewContext<'_, Editor>,
13536) -> InlayHintSettings {
13537    let file = snapshot.file_at(location);
13538    let language = snapshot.language_at(location).map(|l| l.name());
13539    language_settings(language, file, cx).inlay_hints
13540}
13541
13542fn consume_contiguous_rows(
13543    contiguous_row_selections: &mut Vec<Selection<Point>>,
13544    selection: &Selection<Point>,
13545    display_map: &DisplaySnapshot,
13546    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13547) -> (MultiBufferRow, MultiBufferRow) {
13548    contiguous_row_selections.push(selection.clone());
13549    let start_row = MultiBufferRow(selection.start.row);
13550    let mut end_row = ending_row(selection, display_map);
13551
13552    while let Some(next_selection) = selections.peek() {
13553        if next_selection.start.row <= end_row.0 {
13554            end_row = ending_row(next_selection, display_map);
13555            contiguous_row_selections.push(selections.next().unwrap().clone());
13556        } else {
13557            break;
13558        }
13559    }
13560    (start_row, end_row)
13561}
13562
13563fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13564    if next_selection.end.column > 0 || next_selection.is_empty() {
13565        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13566    } else {
13567        MultiBufferRow(next_selection.end.row)
13568    }
13569}
13570
13571impl EditorSnapshot {
13572    pub fn remote_selections_in_range<'a>(
13573        &'a self,
13574        range: &'a Range<Anchor>,
13575        collaboration_hub: &dyn CollaborationHub,
13576        cx: &'a AppContext,
13577    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13578        let participant_names = collaboration_hub.user_names(cx);
13579        let participant_indices = collaboration_hub.user_participant_indices(cx);
13580        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13581        let collaborators_by_replica_id = collaborators_by_peer_id
13582            .iter()
13583            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13584            .collect::<HashMap<_, _>>();
13585        self.buffer_snapshot
13586            .selections_in_range(range, false)
13587            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13588                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13589                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13590                let user_name = participant_names.get(&collaborator.user_id).cloned();
13591                Some(RemoteSelection {
13592                    replica_id,
13593                    selection,
13594                    cursor_shape,
13595                    line_mode,
13596                    participant_index,
13597                    peer_id: collaborator.peer_id,
13598                    user_name,
13599                })
13600            })
13601    }
13602
13603    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13604        self.display_snapshot.buffer_snapshot.language_at(position)
13605    }
13606
13607    pub fn is_focused(&self) -> bool {
13608        self.is_focused
13609    }
13610
13611    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13612        self.placeholder_text.as_ref()
13613    }
13614
13615    pub fn scroll_position(&self) -> gpui::Point<f32> {
13616        self.scroll_anchor.scroll_position(&self.display_snapshot)
13617    }
13618
13619    fn gutter_dimensions(
13620        &self,
13621        font_id: FontId,
13622        font_size: Pixels,
13623        em_width: Pixels,
13624        em_advance: Pixels,
13625        max_line_number_width: Pixels,
13626        cx: &AppContext,
13627    ) -> GutterDimensions {
13628        if !self.show_gutter {
13629            return GutterDimensions::default();
13630        }
13631        let descent = cx.text_system().descent(font_id, font_size);
13632
13633        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13634            matches!(
13635                ProjectSettings::get_global(cx).git.git_gutter,
13636                Some(GitGutterSetting::TrackedFiles)
13637            )
13638        });
13639        let gutter_settings = EditorSettings::get_global(cx).gutter;
13640        let show_line_numbers = self
13641            .show_line_numbers
13642            .unwrap_or(gutter_settings.line_numbers);
13643        let line_gutter_width = if show_line_numbers {
13644            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13645            let min_width_for_number_on_gutter = em_advance * 4.0;
13646            max_line_number_width.max(min_width_for_number_on_gutter)
13647        } else {
13648            0.0.into()
13649        };
13650
13651        let show_code_actions = self
13652            .show_code_actions
13653            .unwrap_or(gutter_settings.code_actions);
13654
13655        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13656
13657        let git_blame_entries_width =
13658            self.git_blame_gutter_max_author_length
13659                .map(|max_author_length| {
13660                    // Length of the author name, but also space for the commit hash,
13661                    // the spacing and the timestamp.
13662                    let max_char_count = max_author_length
13663                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13664                        + 7 // length of commit sha
13665                        + 14 // length of max relative timestamp ("60 minutes ago")
13666                        + 4; // gaps and margins
13667
13668                    em_advance * max_char_count
13669                });
13670
13671        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13672        left_padding += if show_code_actions || show_runnables {
13673            em_width * 3.0
13674        } else if show_git_gutter && show_line_numbers {
13675            em_width * 2.0
13676        } else if show_git_gutter || show_line_numbers {
13677            em_width
13678        } else {
13679            px(0.)
13680        };
13681
13682        let right_padding = if gutter_settings.folds && show_line_numbers {
13683            em_width * 4.0
13684        } else if gutter_settings.folds {
13685            em_width * 3.0
13686        } else if show_line_numbers {
13687            em_width
13688        } else {
13689            px(0.)
13690        };
13691
13692        GutterDimensions {
13693            left_padding,
13694            right_padding,
13695            width: line_gutter_width + left_padding + right_padding,
13696            margin: -descent,
13697            git_blame_entries_width,
13698        }
13699    }
13700
13701    pub fn render_crease_toggle(
13702        &self,
13703        buffer_row: MultiBufferRow,
13704        row_contains_cursor: bool,
13705        editor: View<Editor>,
13706        cx: &mut WindowContext,
13707    ) -> Option<AnyElement> {
13708        let folded = self.is_line_folded(buffer_row);
13709        let mut is_foldable = false;
13710
13711        if let Some(crease) = self
13712            .crease_snapshot
13713            .query_row(buffer_row, &self.buffer_snapshot)
13714        {
13715            is_foldable = true;
13716            match crease {
13717                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13718                    if let Some(render_toggle) = render_toggle {
13719                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13720                            if folded {
13721                                editor.update(cx, |editor, cx| {
13722                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13723                                });
13724                            } else {
13725                                editor.update(cx, |editor, cx| {
13726                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13727                                });
13728                            }
13729                        });
13730                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13731                    }
13732                }
13733            }
13734        }
13735
13736        is_foldable |= self.starts_indent(buffer_row);
13737
13738        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13739            Some(
13740                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13741                    .selected(folded)
13742                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13743                        if folded {
13744                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13745                        } else {
13746                            this.fold_at(&FoldAt { buffer_row }, cx);
13747                        }
13748                    }))
13749                    .into_any_element(),
13750            )
13751        } else {
13752            None
13753        }
13754    }
13755
13756    pub fn render_crease_trailer(
13757        &self,
13758        buffer_row: MultiBufferRow,
13759        cx: &mut WindowContext,
13760    ) -> Option<AnyElement> {
13761        let folded = self.is_line_folded(buffer_row);
13762        if let Crease::Inline { render_trailer, .. } = self
13763            .crease_snapshot
13764            .query_row(buffer_row, &self.buffer_snapshot)?
13765        {
13766            let render_trailer = render_trailer.as_ref()?;
13767            Some(render_trailer(buffer_row, folded, cx))
13768        } else {
13769            None
13770        }
13771    }
13772}
13773
13774impl Deref for EditorSnapshot {
13775    type Target = DisplaySnapshot;
13776
13777    fn deref(&self) -> &Self::Target {
13778        &self.display_snapshot
13779    }
13780}
13781
13782#[derive(Clone, Debug, PartialEq, Eq)]
13783pub enum EditorEvent {
13784    InputIgnored {
13785        text: Arc<str>,
13786    },
13787    InputHandled {
13788        utf16_range_to_replace: Option<Range<isize>>,
13789        text: Arc<str>,
13790    },
13791    ExcerptsAdded {
13792        buffer: Model<Buffer>,
13793        predecessor: ExcerptId,
13794        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13795    },
13796    ExcerptsRemoved {
13797        ids: Vec<ExcerptId>,
13798    },
13799    ExcerptsEdited {
13800        ids: Vec<ExcerptId>,
13801    },
13802    ExcerptsExpanded {
13803        ids: Vec<ExcerptId>,
13804    },
13805    BufferEdited,
13806    Edited {
13807        transaction_id: clock::Lamport,
13808    },
13809    Reparsed(BufferId),
13810    Focused,
13811    FocusedIn,
13812    Blurred,
13813    DirtyChanged,
13814    Saved,
13815    TitleChanged,
13816    DiffBaseChanged,
13817    SelectionsChanged {
13818        local: bool,
13819    },
13820    ScrollPositionChanged {
13821        local: bool,
13822        autoscroll: bool,
13823    },
13824    Closed,
13825    TransactionUndone {
13826        transaction_id: clock::Lamport,
13827    },
13828    TransactionBegun {
13829        transaction_id: clock::Lamport,
13830    },
13831    Reloaded,
13832    CursorShapeChanged,
13833}
13834
13835impl EventEmitter<EditorEvent> for Editor {}
13836
13837impl FocusableView for Editor {
13838    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13839        self.focus_handle.clone()
13840    }
13841}
13842
13843impl Render for Editor {
13844    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13845        let settings = ThemeSettings::get_global(cx);
13846
13847        let mut text_style = match self.mode {
13848            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13849                color: cx.theme().colors().editor_foreground,
13850                font_family: settings.ui_font.family.clone(),
13851                font_features: settings.ui_font.features.clone(),
13852                font_fallbacks: settings.ui_font.fallbacks.clone(),
13853                font_size: rems(0.875).into(),
13854                font_weight: settings.ui_font.weight,
13855                line_height: relative(settings.buffer_line_height.value()),
13856                ..Default::default()
13857            },
13858            EditorMode::Full => TextStyle {
13859                color: cx.theme().colors().editor_foreground,
13860                font_family: settings.buffer_font.family.clone(),
13861                font_features: settings.buffer_font.features.clone(),
13862                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13863                font_size: settings.buffer_font_size(cx).into(),
13864                font_weight: settings.buffer_font.weight,
13865                line_height: relative(settings.buffer_line_height.value()),
13866                ..Default::default()
13867            },
13868        };
13869        if let Some(text_style_refinement) = &self.text_style_refinement {
13870            text_style.refine(text_style_refinement)
13871        }
13872
13873        let background = match self.mode {
13874            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13875            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13876            EditorMode::Full => cx.theme().colors().editor_background,
13877        };
13878
13879        EditorElement::new(
13880            cx.view(),
13881            EditorStyle {
13882                background,
13883                local_player: cx.theme().players().local(),
13884                text: text_style,
13885                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13886                syntax: cx.theme().syntax().clone(),
13887                status: cx.theme().status().clone(),
13888                inlay_hints_style: make_inlay_hints_style(cx),
13889                suggestions_style: HighlightStyle {
13890                    color: Some(cx.theme().status().predictive),
13891                    ..HighlightStyle::default()
13892                },
13893                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13894            },
13895        )
13896    }
13897}
13898
13899impl ViewInputHandler for Editor {
13900    fn text_for_range(
13901        &mut self,
13902        range_utf16: Range<usize>,
13903        adjusted_range: &mut Option<Range<usize>>,
13904        cx: &mut ViewContext<Self>,
13905    ) -> Option<String> {
13906        let snapshot = self.buffer.read(cx).read(cx);
13907        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13908        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13909        if (start.0..end.0) != range_utf16 {
13910            adjusted_range.replace(start.0..end.0);
13911        }
13912        Some(snapshot.text_for_range(start..end).collect())
13913    }
13914
13915    fn selected_text_range(
13916        &mut self,
13917        ignore_disabled_input: bool,
13918        cx: &mut ViewContext<Self>,
13919    ) -> Option<UTF16Selection> {
13920        // Prevent the IME menu from appearing when holding down an alphabetic key
13921        // while input is disabled.
13922        if !ignore_disabled_input && !self.input_enabled {
13923            return None;
13924        }
13925
13926        let selection = self.selections.newest::<OffsetUtf16>(cx);
13927        let range = selection.range();
13928
13929        Some(UTF16Selection {
13930            range: range.start.0..range.end.0,
13931            reversed: selection.reversed,
13932        })
13933    }
13934
13935    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13936        let snapshot = self.buffer.read(cx).read(cx);
13937        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13938        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13939    }
13940
13941    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13942        self.clear_highlights::<InputComposition>(cx);
13943        self.ime_transaction.take();
13944    }
13945
13946    fn replace_text_in_range(
13947        &mut self,
13948        range_utf16: Option<Range<usize>>,
13949        text: &str,
13950        cx: &mut ViewContext<Self>,
13951    ) {
13952        if !self.input_enabled {
13953            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13954            return;
13955        }
13956
13957        self.transact(cx, |this, cx| {
13958            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13959                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13960                Some(this.selection_replacement_ranges(range_utf16, cx))
13961            } else {
13962                this.marked_text_ranges(cx)
13963            };
13964
13965            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13966                let newest_selection_id = this.selections.newest_anchor().id;
13967                this.selections
13968                    .all::<OffsetUtf16>(cx)
13969                    .iter()
13970                    .zip(ranges_to_replace.iter())
13971                    .find_map(|(selection, range)| {
13972                        if selection.id == newest_selection_id {
13973                            Some(
13974                                (range.start.0 as isize - selection.head().0 as isize)
13975                                    ..(range.end.0 as isize - selection.head().0 as isize),
13976                            )
13977                        } else {
13978                            None
13979                        }
13980                    })
13981            });
13982
13983            cx.emit(EditorEvent::InputHandled {
13984                utf16_range_to_replace: range_to_replace,
13985                text: text.into(),
13986            });
13987
13988            if let Some(new_selected_ranges) = new_selected_ranges {
13989                this.change_selections(None, cx, |selections| {
13990                    selections.select_ranges(new_selected_ranges)
13991                });
13992                this.backspace(&Default::default(), cx);
13993            }
13994
13995            this.handle_input(text, cx);
13996        });
13997
13998        if let Some(transaction) = self.ime_transaction {
13999            self.buffer.update(cx, |buffer, cx| {
14000                buffer.group_until_transaction(transaction, cx);
14001            });
14002        }
14003
14004        self.unmark_text(cx);
14005    }
14006
14007    fn replace_and_mark_text_in_range(
14008        &mut self,
14009        range_utf16: Option<Range<usize>>,
14010        text: &str,
14011        new_selected_range_utf16: Option<Range<usize>>,
14012        cx: &mut ViewContext<Self>,
14013    ) {
14014        if !self.input_enabled {
14015            return;
14016        }
14017
14018        let transaction = self.transact(cx, |this, cx| {
14019            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14020                let snapshot = this.buffer.read(cx).read(cx);
14021                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14022                    for marked_range in &mut marked_ranges {
14023                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14024                        marked_range.start.0 += relative_range_utf16.start;
14025                        marked_range.start =
14026                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14027                        marked_range.end =
14028                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14029                    }
14030                }
14031                Some(marked_ranges)
14032            } else if let Some(range_utf16) = range_utf16 {
14033                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14034                Some(this.selection_replacement_ranges(range_utf16, cx))
14035            } else {
14036                None
14037            };
14038
14039            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14040                let newest_selection_id = this.selections.newest_anchor().id;
14041                this.selections
14042                    .all::<OffsetUtf16>(cx)
14043                    .iter()
14044                    .zip(ranges_to_replace.iter())
14045                    .find_map(|(selection, range)| {
14046                        if selection.id == newest_selection_id {
14047                            Some(
14048                                (range.start.0 as isize - selection.head().0 as isize)
14049                                    ..(range.end.0 as isize - selection.head().0 as isize),
14050                            )
14051                        } else {
14052                            None
14053                        }
14054                    })
14055            });
14056
14057            cx.emit(EditorEvent::InputHandled {
14058                utf16_range_to_replace: range_to_replace,
14059                text: text.into(),
14060            });
14061
14062            if let Some(ranges) = ranges_to_replace {
14063                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14064            }
14065
14066            let marked_ranges = {
14067                let snapshot = this.buffer.read(cx).read(cx);
14068                this.selections
14069                    .disjoint_anchors()
14070                    .iter()
14071                    .map(|selection| {
14072                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14073                    })
14074                    .collect::<Vec<_>>()
14075            };
14076
14077            if text.is_empty() {
14078                this.unmark_text(cx);
14079            } else {
14080                this.highlight_text::<InputComposition>(
14081                    marked_ranges.clone(),
14082                    HighlightStyle {
14083                        underline: Some(UnderlineStyle {
14084                            thickness: px(1.),
14085                            color: None,
14086                            wavy: false,
14087                        }),
14088                        ..Default::default()
14089                    },
14090                    cx,
14091                );
14092            }
14093
14094            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14095            let use_autoclose = this.use_autoclose;
14096            let use_auto_surround = this.use_auto_surround;
14097            this.set_use_autoclose(false);
14098            this.set_use_auto_surround(false);
14099            this.handle_input(text, cx);
14100            this.set_use_autoclose(use_autoclose);
14101            this.set_use_auto_surround(use_auto_surround);
14102
14103            if let Some(new_selected_range) = new_selected_range_utf16 {
14104                let snapshot = this.buffer.read(cx).read(cx);
14105                let new_selected_ranges = marked_ranges
14106                    .into_iter()
14107                    .map(|marked_range| {
14108                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14109                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14110                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14111                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14112                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14113                    })
14114                    .collect::<Vec<_>>();
14115
14116                drop(snapshot);
14117                this.change_selections(None, cx, |selections| {
14118                    selections.select_ranges(new_selected_ranges)
14119                });
14120            }
14121        });
14122
14123        self.ime_transaction = self.ime_transaction.or(transaction);
14124        if let Some(transaction) = self.ime_transaction {
14125            self.buffer.update(cx, |buffer, cx| {
14126                buffer.group_until_transaction(transaction, cx);
14127            });
14128        }
14129
14130        if self.text_highlights::<InputComposition>(cx).is_none() {
14131            self.ime_transaction.take();
14132        }
14133    }
14134
14135    fn bounds_for_range(
14136        &mut self,
14137        range_utf16: Range<usize>,
14138        element_bounds: gpui::Bounds<Pixels>,
14139        cx: &mut ViewContext<Self>,
14140    ) -> Option<gpui::Bounds<Pixels>> {
14141        let text_layout_details = self.text_layout_details(cx);
14142        let gpui::Point {
14143            x: em_width,
14144            y: line_height,
14145        } = self.character_size(cx);
14146
14147        let snapshot = self.snapshot(cx);
14148        let scroll_position = snapshot.scroll_position();
14149        let scroll_left = scroll_position.x * em_width;
14150
14151        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14152        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14153            + self.gutter_dimensions.width
14154            + self.gutter_dimensions.margin;
14155        let y = line_height * (start.row().as_f32() - scroll_position.y);
14156
14157        Some(Bounds {
14158            origin: element_bounds.origin + point(x, y),
14159            size: size(em_width, line_height),
14160        })
14161    }
14162}
14163
14164trait SelectionExt {
14165    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14166    fn spanned_rows(
14167        &self,
14168        include_end_if_at_line_start: bool,
14169        map: &DisplaySnapshot,
14170    ) -> Range<MultiBufferRow>;
14171}
14172
14173impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14174    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14175        let start = self
14176            .start
14177            .to_point(&map.buffer_snapshot)
14178            .to_display_point(map);
14179        let end = self
14180            .end
14181            .to_point(&map.buffer_snapshot)
14182            .to_display_point(map);
14183        if self.reversed {
14184            end..start
14185        } else {
14186            start..end
14187        }
14188    }
14189
14190    fn spanned_rows(
14191        &self,
14192        include_end_if_at_line_start: bool,
14193        map: &DisplaySnapshot,
14194    ) -> Range<MultiBufferRow> {
14195        let start = self.start.to_point(&map.buffer_snapshot);
14196        let mut end = self.end.to_point(&map.buffer_snapshot);
14197        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14198            end.row -= 1;
14199        }
14200
14201        let buffer_start = map.prev_line_boundary(start).0;
14202        let buffer_end = map.next_line_boundary(end).0;
14203        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14204    }
14205}
14206
14207impl<T: InvalidationRegion> InvalidationStack<T> {
14208    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14209    where
14210        S: Clone + ToOffset,
14211    {
14212        while let Some(region) = self.last() {
14213            let all_selections_inside_invalidation_ranges =
14214                if selections.len() == region.ranges().len() {
14215                    selections
14216                        .iter()
14217                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14218                        .all(|(selection, invalidation_range)| {
14219                            let head = selection.head().to_offset(buffer);
14220                            invalidation_range.start <= head && invalidation_range.end >= head
14221                        })
14222                } else {
14223                    false
14224                };
14225
14226            if all_selections_inside_invalidation_ranges {
14227                break;
14228            } else {
14229                self.pop();
14230            }
14231        }
14232    }
14233}
14234
14235impl<T> Default for InvalidationStack<T> {
14236    fn default() -> Self {
14237        Self(Default::default())
14238    }
14239}
14240
14241impl<T> Deref for InvalidationStack<T> {
14242    type Target = Vec<T>;
14243
14244    fn deref(&self) -> &Self::Target {
14245        &self.0
14246    }
14247}
14248
14249impl<T> DerefMut for InvalidationStack<T> {
14250    fn deref_mut(&mut self) -> &mut Self::Target {
14251        &mut self.0
14252    }
14253}
14254
14255impl InvalidationRegion for SnippetState {
14256    fn ranges(&self) -> &[Range<Anchor>] {
14257        &self.ranges[self.active_index]
14258    }
14259}
14260
14261pub fn diagnostic_block_renderer(
14262    diagnostic: Diagnostic,
14263    max_message_rows: Option<u8>,
14264    allow_closing: bool,
14265    _is_valid: bool,
14266) -> RenderBlock {
14267    let (text_without_backticks, code_ranges) =
14268        highlight_diagnostic_message(&diagnostic, max_message_rows);
14269
14270    Arc::new(move |cx: &mut BlockContext| {
14271        let group_id: SharedString = cx.block_id.to_string().into();
14272
14273        let mut text_style = cx.text_style().clone();
14274        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14275        let theme_settings = ThemeSettings::get_global(cx);
14276        text_style.font_family = theme_settings.buffer_font.family.clone();
14277        text_style.font_style = theme_settings.buffer_font.style;
14278        text_style.font_features = theme_settings.buffer_font.features.clone();
14279        text_style.font_weight = theme_settings.buffer_font.weight;
14280
14281        let multi_line_diagnostic = diagnostic.message.contains('\n');
14282
14283        let buttons = |diagnostic: &Diagnostic| {
14284            if multi_line_diagnostic {
14285                v_flex()
14286            } else {
14287                h_flex()
14288            }
14289            .when(allow_closing, |div| {
14290                div.children(diagnostic.is_primary.then(|| {
14291                    IconButton::new("close-block", IconName::XCircle)
14292                        .icon_color(Color::Muted)
14293                        .size(ButtonSize::Compact)
14294                        .style(ButtonStyle::Transparent)
14295                        .visible_on_hover(group_id.clone())
14296                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14297                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14298                }))
14299            })
14300            .child(
14301                IconButton::new("copy-block", IconName::Copy)
14302                    .icon_color(Color::Muted)
14303                    .size(ButtonSize::Compact)
14304                    .style(ButtonStyle::Transparent)
14305                    .visible_on_hover(group_id.clone())
14306                    .on_click({
14307                        let message = diagnostic.message.clone();
14308                        move |_click, cx| {
14309                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14310                        }
14311                    })
14312                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14313            )
14314        };
14315
14316        let icon_size = buttons(&diagnostic)
14317            .into_any_element()
14318            .layout_as_root(AvailableSpace::min_size(), cx);
14319
14320        h_flex()
14321            .id(cx.block_id)
14322            .group(group_id.clone())
14323            .relative()
14324            .size_full()
14325            .block_mouse_down()
14326            .pl(cx.gutter_dimensions.width)
14327            .w(cx.max_width - cx.gutter_dimensions.full_width())
14328            .child(
14329                div()
14330                    .flex()
14331                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14332                    .flex_shrink(),
14333            )
14334            .child(buttons(&diagnostic))
14335            .child(div().flex().flex_shrink_0().child(
14336                StyledText::new(text_without_backticks.clone()).with_highlights(
14337                    &text_style,
14338                    code_ranges.iter().map(|range| {
14339                        (
14340                            range.clone(),
14341                            HighlightStyle {
14342                                font_weight: Some(FontWeight::BOLD),
14343                                ..Default::default()
14344                            },
14345                        )
14346                    }),
14347                ),
14348            ))
14349            .into_any_element()
14350    })
14351}
14352
14353pub fn highlight_diagnostic_message(
14354    diagnostic: &Diagnostic,
14355    mut max_message_rows: Option<u8>,
14356) -> (SharedString, Vec<Range<usize>>) {
14357    let mut text_without_backticks = String::new();
14358    let mut code_ranges = Vec::new();
14359
14360    if let Some(source) = &diagnostic.source {
14361        text_without_backticks.push_str(source);
14362        code_ranges.push(0..source.len());
14363        text_without_backticks.push_str(": ");
14364    }
14365
14366    let mut prev_offset = 0;
14367    let mut in_code_block = false;
14368    let has_row_limit = max_message_rows.is_some();
14369    let mut newline_indices = diagnostic
14370        .message
14371        .match_indices('\n')
14372        .filter(|_| has_row_limit)
14373        .map(|(ix, _)| ix)
14374        .fuse()
14375        .peekable();
14376
14377    for (quote_ix, _) in diagnostic
14378        .message
14379        .match_indices('`')
14380        .chain([(diagnostic.message.len(), "")])
14381    {
14382        let mut first_newline_ix = None;
14383        let mut last_newline_ix = None;
14384        while let Some(newline_ix) = newline_indices.peek() {
14385            if *newline_ix < quote_ix {
14386                if first_newline_ix.is_none() {
14387                    first_newline_ix = Some(*newline_ix);
14388                }
14389                last_newline_ix = Some(*newline_ix);
14390
14391                if let Some(rows_left) = &mut max_message_rows {
14392                    if *rows_left == 0 {
14393                        break;
14394                    } else {
14395                        *rows_left -= 1;
14396                    }
14397                }
14398                let _ = newline_indices.next();
14399            } else {
14400                break;
14401            }
14402        }
14403        let prev_len = text_without_backticks.len();
14404        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14405        text_without_backticks.push_str(new_text);
14406        if in_code_block {
14407            code_ranges.push(prev_len..text_without_backticks.len());
14408        }
14409        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14410        in_code_block = !in_code_block;
14411        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14412            text_without_backticks.push_str("...");
14413            break;
14414        }
14415    }
14416
14417    (text_without_backticks.into(), code_ranges)
14418}
14419
14420fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14421    match severity {
14422        DiagnosticSeverity::ERROR => colors.error,
14423        DiagnosticSeverity::WARNING => colors.warning,
14424        DiagnosticSeverity::INFORMATION => colors.info,
14425        DiagnosticSeverity::HINT => colors.info,
14426        _ => colors.ignored,
14427    }
14428}
14429
14430pub fn styled_runs_for_code_label<'a>(
14431    label: &'a CodeLabel,
14432    syntax_theme: &'a theme::SyntaxTheme,
14433) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14434    let fade_out = HighlightStyle {
14435        fade_out: Some(0.35),
14436        ..Default::default()
14437    };
14438
14439    let mut prev_end = label.filter_range.end;
14440    label
14441        .runs
14442        .iter()
14443        .enumerate()
14444        .flat_map(move |(ix, (range, highlight_id))| {
14445            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14446                style
14447            } else {
14448                return Default::default();
14449            };
14450            let mut muted_style = style;
14451            muted_style.highlight(fade_out);
14452
14453            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14454            if range.start >= label.filter_range.end {
14455                if range.start > prev_end {
14456                    runs.push((prev_end..range.start, fade_out));
14457                }
14458                runs.push((range.clone(), muted_style));
14459            } else if range.end <= label.filter_range.end {
14460                runs.push((range.clone(), style));
14461            } else {
14462                runs.push((range.start..label.filter_range.end, style));
14463                runs.push((label.filter_range.end..range.end, muted_style));
14464            }
14465            prev_end = cmp::max(prev_end, range.end);
14466
14467            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14468                runs.push((prev_end..label.text.len(), fade_out));
14469            }
14470
14471            runs
14472        })
14473}
14474
14475pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14476    let mut prev_index = 0;
14477    let mut prev_codepoint: Option<char> = None;
14478    text.char_indices()
14479        .chain([(text.len(), '\0')])
14480        .filter_map(move |(index, codepoint)| {
14481            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14482            let is_boundary = index == text.len()
14483                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14484                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14485            if is_boundary {
14486                let chunk = &text[prev_index..index];
14487                prev_index = index;
14488                Some(chunk)
14489            } else {
14490                None
14491            }
14492        })
14493}
14494
14495pub trait RangeToAnchorExt: Sized {
14496    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14497
14498    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14499        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14500        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14501    }
14502}
14503
14504impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14505    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14506        let start_offset = self.start.to_offset(snapshot);
14507        let end_offset = self.end.to_offset(snapshot);
14508        if start_offset == end_offset {
14509            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14510        } else {
14511            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14512        }
14513    }
14514}
14515
14516pub trait RowExt {
14517    fn as_f32(&self) -> f32;
14518
14519    fn next_row(&self) -> Self;
14520
14521    fn previous_row(&self) -> Self;
14522
14523    fn minus(&self, other: Self) -> u32;
14524}
14525
14526impl RowExt for DisplayRow {
14527    fn as_f32(&self) -> f32 {
14528        self.0 as f32
14529    }
14530
14531    fn next_row(&self) -> Self {
14532        Self(self.0 + 1)
14533    }
14534
14535    fn previous_row(&self) -> Self {
14536        Self(self.0.saturating_sub(1))
14537    }
14538
14539    fn minus(&self, other: Self) -> u32 {
14540        self.0 - other.0
14541    }
14542}
14543
14544impl RowExt for MultiBufferRow {
14545    fn as_f32(&self) -> f32 {
14546        self.0 as f32
14547    }
14548
14549    fn next_row(&self) -> Self {
14550        Self(self.0 + 1)
14551    }
14552
14553    fn previous_row(&self) -> Self {
14554        Self(self.0.saturating_sub(1))
14555    }
14556
14557    fn minus(&self, other: Self) -> u32 {
14558        self.0 - other.0
14559    }
14560}
14561
14562trait RowRangeExt {
14563    type Row;
14564
14565    fn len(&self) -> usize;
14566
14567    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14568}
14569
14570impl RowRangeExt for Range<MultiBufferRow> {
14571    type Row = MultiBufferRow;
14572
14573    fn len(&self) -> usize {
14574        (self.end.0 - self.start.0) as usize
14575    }
14576
14577    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14578        (self.start.0..self.end.0).map(MultiBufferRow)
14579    }
14580}
14581
14582impl RowRangeExt for Range<DisplayRow> {
14583    type Row = DisplayRow;
14584
14585    fn len(&self) -> usize {
14586        (self.end.0 - self.start.0) as usize
14587    }
14588
14589    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14590        (self.start.0..self.end.0).map(DisplayRow)
14591    }
14592}
14593
14594fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14595    if hunk.diff_base_byte_range.is_empty() {
14596        DiffHunkStatus::Added
14597    } else if hunk.row_range.is_empty() {
14598        DiffHunkStatus::Removed
14599    } else {
14600        DiffHunkStatus::Modified
14601    }
14602}
14603
14604/// If select range has more than one line, we
14605/// just point the cursor to range.start.
14606fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14607    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14608        range
14609    } else {
14610        range.start..range.start
14611    }
14612}
14613
14614pub struct KillRing(ClipboardItem);
14615impl Global for KillRing {}
14616
14617const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);