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 indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66pub use element::{
   67    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   68};
   69use element::{LineWithInvisibles, PositionMap};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72
   73use code_context_menus::{
   74    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   75    CompletionsMenu, ContextMenuOrigin,
   76};
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
   80    px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
   81    AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
   82    Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
   84    MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
   85    StyledText, Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
  100    IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  101    TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::{find_url, find_url_from_range};
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub fn render_parsed_markdown(
  193    element_id: impl Into<ElementId>,
  194    parsed: &language::ParsedMarkdown,
  195    editor_style: &EditorStyle,
  196    workspace: Option<WeakEntity<Workspace>>,
  197    cx: &mut App,
  198) -> InteractiveText {
  199    let code_span_background_color = cx
  200        .theme()
  201        .colors()
  202        .editor_document_highlight_read_background;
  203
  204    let highlights = gpui::combine_highlights(
  205        parsed.highlights.iter().filter_map(|(range, highlight)| {
  206            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  207            Some((range.clone(), highlight))
  208        }),
  209        parsed
  210            .regions
  211            .iter()
  212            .zip(&parsed.region_ranges)
  213            .filter_map(|(region, range)| {
  214                if region.code {
  215                    Some((
  216                        range.clone(),
  217                        HighlightStyle {
  218                            background_color: Some(code_span_background_color),
  219                            ..Default::default()
  220                        },
  221                    ))
  222                } else {
  223                    None
  224                }
  225            }),
  226    );
  227
  228    let mut links = Vec::new();
  229    let mut link_ranges = Vec::new();
  230    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  231        if let Some(link) = region.link.clone() {
  232            links.push(link);
  233            link_ranges.push(range.clone());
  234        }
  235    }
  236
  237    InteractiveText::new(
  238        element_id,
  239        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  240    )
  241    .on_click(
  242        link_ranges,
  243        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace
  249                            .open_abs_path(path.clone(), false, window, cx)
  250                            .detach();
  251                    });
  252                }
  253            }
  254        },
  255    )
  256}
  257
  258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  259pub enum InlayId {
  260    InlineCompletion(usize),
  261    Hint(usize),
  262}
  263
  264impl InlayId {
  265    fn id(&self) -> usize {
  266        match self {
  267            Self::InlineCompletion(id) => *id,
  268            Self::Hint(id) => *id,
  269        }
  270    }
  271}
  272
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  278pub enum Navigated {
  279    Yes,
  280    No,
  281}
  282
  283impl Navigated {
  284    pub fn from_bool(yes: bool) -> Navigated {
  285        if yes {
  286            Navigated::Yes
  287        } else {
  288            Navigated::No
  289        }
  290    }
  291}
  292
  293pub fn init_settings(cx: &mut App) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut App) {
  298    init_settings(cx);
  299
  300    workspace::register_project_item::<Editor>(cx);
  301    workspace::FollowableViewRegistry::register::<Editor>(cx);
  302    workspace::register_serializable_item::<Editor>(cx);
  303
  304    cx.observe_new(
  305        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  306            workspace.register_action(Editor::new_file);
  307            workspace.register_action(Editor::new_file_vertical);
  308            workspace.register_action(Editor::new_file_horizontal);
  309            workspace.register_action(Editor::cancel_language_server_work);
  310        },
  311    )
  312    .detach();
  313
  314    cx.on_action(move |_: &workspace::NewFile, cx| {
  315        let app_state = workspace::AppState::global(cx);
  316        if let Some(app_state) = app_state.upgrade() {
  317            workspace::open_new(
  318                Default::default(),
  319                app_state,
  320                cx,
  321                |workspace, window, cx| {
  322                    Editor::new_file(workspace, &Default::default(), window, cx)
  323                },
  324            )
  325            .detach();
  326        }
  327    });
  328    cx.on_action(move |_: &workspace::NewWindow, cx| {
  329        let app_state = workspace::AppState::global(cx);
  330        if let Some(app_state) = app_state.upgrade() {
  331            workspace::open_new(
  332                Default::default(),
  333                app_state,
  334                cx,
  335                |workspace, window, cx| {
  336                    cx.activate(true);
  337                    Editor::new_file(workspace, &Default::default(), window, cx)
  338                },
  339            )
  340            .detach();
  341        }
  342    });
  343}
  344
  345pub struct SearchWithinRange;
  346
  347trait InvalidationRegion {
  348    fn ranges(&self) -> &[Range<Anchor>];
  349}
  350
  351#[derive(Clone, Debug, PartialEq)]
  352pub enum SelectPhase {
  353    Begin {
  354        position: DisplayPoint,
  355        add: bool,
  356        click_count: usize,
  357    },
  358    BeginColumnar {
  359        position: DisplayPoint,
  360        reset: bool,
  361        goal_column: u32,
  362    },
  363    Extend {
  364        position: DisplayPoint,
  365        click_count: usize,
  366    },
  367    Update {
  368        position: DisplayPoint,
  369        goal_column: u32,
  370        scroll_delta: gpui::Point<f32>,
  371    },
  372    End,
  373}
  374
  375#[derive(Clone, Debug)]
  376pub enum SelectMode {
  377    Character,
  378    Word(Range<Anchor>),
  379    Line(Range<Anchor>),
  380    All,
  381}
  382
  383#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  384pub enum EditorMode {
  385    SingleLine { auto_width: bool },
  386    AutoHeight { max_lines: usize },
  387    Full,
  388}
  389
  390#[derive(Copy, Clone, Debug)]
  391pub enum SoftWrap {
  392    /// Prefer not to wrap at all.
  393    ///
  394    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  395    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  396    GitDiff,
  397    /// Prefer a single line generally, unless an overly long line is encountered.
  398    None,
  399    /// Soft wrap lines that exceed the editor width.
  400    EditorWidth,
  401    /// Soft wrap lines at the preferred line length.
  402    Column(u32),
  403    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  404    Bounded(u32),
  405}
  406
  407#[derive(Clone)]
  408pub struct EditorStyle {
  409    pub background: Hsla,
  410    pub local_player: PlayerColor,
  411    pub text: TextStyle,
  412    pub scrollbar_width: Pixels,
  413    pub syntax: Arc<SyntaxTheme>,
  414    pub status: StatusColors,
  415    pub inlay_hints_style: HighlightStyle,
  416    pub inline_completion_styles: InlineCompletionStyles,
  417    pub unnecessary_code_fade: f32,
  418}
  419
  420impl Default for EditorStyle {
  421    fn default() -> Self {
  422        Self {
  423            background: Hsla::default(),
  424            local_player: PlayerColor::default(),
  425            text: TextStyle::default(),
  426            scrollbar_width: Pixels::default(),
  427            syntax: Default::default(),
  428            // HACK: Status colors don't have a real default.
  429            // We should look into removing the status colors from the editor
  430            // style and retrieve them directly from the theme.
  431            status: StatusColors::dark(),
  432            inlay_hints_style: HighlightStyle::default(),
  433            inline_completion_styles: InlineCompletionStyles {
  434                insertion: HighlightStyle::default(),
  435                whitespace: HighlightStyle::default(),
  436            },
  437            unnecessary_code_fade: Default::default(),
  438        }
  439    }
  440}
  441
  442pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  443    let show_background = language_settings::language_settings(None, None, cx)
  444        .inlay_hints
  445        .show_background;
  446
  447    HighlightStyle {
  448        color: Some(cx.theme().status().hint),
  449        background_color: show_background.then(|| cx.theme().status().hint_background),
  450        ..HighlightStyle::default()
  451    }
  452}
  453
  454pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  455    InlineCompletionStyles {
  456        insertion: HighlightStyle {
  457            color: Some(cx.theme().status().predictive),
  458            ..HighlightStyle::default()
  459        },
  460        whitespace: HighlightStyle {
  461            background_color: Some(cx.theme().status().created_background),
  462            ..HighlightStyle::default()
  463        },
  464    }
  465}
  466
  467type CompletionId = usize;
  468
  469pub(crate) enum EditDisplayMode {
  470    TabAccept(bool),
  471    DiffPopover,
  472    Inline,
  473}
  474
  475enum InlineCompletion {
  476    Edit {
  477        edits: Vec<(Range<Anchor>, String)>,
  478        edit_preview: Option<EditPreview>,
  479        display_mode: EditDisplayMode,
  480        snapshot: BufferSnapshot,
  481    },
  482    Move {
  483        target: Anchor,
  484        range_around_target: Range<text::Anchor>,
  485        snapshot: BufferSnapshot,
  486    },
  487}
  488
  489struct InlineCompletionState {
  490    inlay_ids: Vec<InlayId>,
  491    completion: InlineCompletion,
  492    invalidation_range: Range<Anchor>,
  493}
  494
  495impl InlineCompletionState {
  496    pub fn is_move(&self) -> bool {
  497        match &self.completion {
  498            InlineCompletion::Move { .. } => true,
  499            _ => false,
  500        }
  501    }
  502}
  503
  504enum InlineCompletionHighlight {}
  505
  506pub enum MenuInlineCompletionsPolicy {
  507    Never,
  508    ByProvider,
  509}
  510
  511#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  512struct EditorActionId(usize);
  513
  514impl EditorActionId {
  515    pub fn post_inc(&mut self) -> Self {
  516        let answer = self.0;
  517
  518        *self = Self(answer + 1);
  519
  520        Self(answer)
  521    }
  522}
  523
  524// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  525// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  526
  527type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  528type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  529
  530#[derive(Default)]
  531struct ScrollbarMarkerState {
  532    scrollbar_size: Size<Pixels>,
  533    dirty: bool,
  534    markers: Arc<[PaintQuad]>,
  535    pending_refresh: Option<Task<Result<()>>>,
  536}
  537
  538impl ScrollbarMarkerState {
  539    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  540        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  541    }
  542}
  543
  544#[derive(Clone, Debug)]
  545struct RunnableTasks {
  546    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  547    offset: MultiBufferOffset,
  548    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  549    column: u32,
  550    // Values of all named captures, including those starting with '_'
  551    extra_variables: HashMap<String, String>,
  552    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  553    context_range: Range<BufferOffset>,
  554}
  555
  556impl RunnableTasks {
  557    fn resolve<'a>(
  558        &'a self,
  559        cx: &'a task::TaskContext,
  560    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  561        self.templates.iter().filter_map(|(kind, template)| {
  562            template
  563                .resolve_task(&kind.to_id_base(), cx)
  564                .map(|task| (kind.clone(), task))
  565        })
  566    }
  567}
  568
  569#[derive(Clone)]
  570struct ResolvedTasks {
  571    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  572    position: Anchor,
  573}
  574#[derive(Copy, Clone, Debug)]
  575struct MultiBufferOffset(usize);
  576#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  577struct BufferOffset(usize);
  578
  579// Addons allow storing per-editor state in other crates (e.g. Vim)
  580pub trait Addon: 'static {
  581    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  582
  583    fn to_any(&self) -> &dyn std::any::Any;
  584}
  585
  586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  587pub enum IsVimMode {
  588    Yes,
  589    No,
  590}
  591
  592/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  593///
  594/// See the [module level documentation](self) for more information.
  595pub struct Editor {
  596    focus_handle: FocusHandle,
  597    last_focused_descendant: Option<WeakFocusHandle>,
  598    /// The text buffer being edited
  599    buffer: Entity<MultiBuffer>,
  600    /// Map of how text in the buffer should be displayed.
  601    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  602    pub display_map: Entity<DisplayMap>,
  603    pub selections: SelectionsCollection,
  604    pub scroll_manager: ScrollManager,
  605    /// When inline assist editors are linked, they all render cursors because
  606    /// typing enters text into each of them, even the ones that aren't focused.
  607    pub(crate) show_cursor_when_unfocused: bool,
  608    columnar_selection_tail: Option<Anchor>,
  609    add_selections_state: Option<AddSelectionsState>,
  610    select_next_state: Option<SelectNextState>,
  611    select_prev_state: Option<SelectNextState>,
  612    selection_history: SelectionHistory,
  613    autoclose_regions: Vec<AutocloseRegion>,
  614    snippet_stack: InvalidationStack<SnippetState>,
  615    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  616    ime_transaction: Option<TransactionId>,
  617    active_diagnostics: Option<ActiveDiagnosticGroup>,
  618    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  619
  620    // TODO: make this a access method
  621    pub project: Option<Entity<Project>>,
  622    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  623    completion_provider: Option<Box<dyn CompletionProvider>>,
  624    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  625    blink_manager: Entity<BlinkManager>,
  626    show_cursor_names: bool,
  627    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  628    pub show_local_selections: bool,
  629    mode: EditorMode,
  630    show_breadcrumbs: bool,
  631    show_gutter: bool,
  632    show_scrollbars: bool,
  633    show_line_numbers: Option<bool>,
  634    use_relative_line_numbers: Option<bool>,
  635    show_git_diff_gutter: Option<bool>,
  636    show_code_actions: Option<bool>,
  637    show_runnables: Option<bool>,
  638    show_wrap_guides: Option<bool>,
  639    show_indent_guides: Option<bool>,
  640    placeholder_text: Option<Arc<str>>,
  641    highlight_order: usize,
  642    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  643    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  644    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  645    scrollbar_marker_state: ScrollbarMarkerState,
  646    active_indent_guides_state: ActiveIndentGuidesState,
  647    nav_history: Option<ItemNavHistory>,
  648    context_menu: RefCell<Option<CodeContextMenu>>,
  649    mouse_context_menu: Option<MouseContextMenu>,
  650    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  651    signature_help_state: SignatureHelpState,
  652    auto_signature_help: Option<bool>,
  653    find_all_references_task_sources: Vec<Anchor>,
  654    next_completion_id: CompletionId,
  655    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  656    code_actions_task: Option<Task<Result<()>>>,
  657    document_highlights_task: Option<Task<()>>,
  658    linked_editing_range_task: Option<Task<Option<()>>>,
  659    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  660    pending_rename: Option<RenameState>,
  661    searchable: bool,
  662    cursor_shape: CursorShape,
  663    current_line_highlight: Option<CurrentLineHighlight>,
  664    collapse_matches: bool,
  665    autoindent_mode: Option<AutoindentMode>,
  666    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  667    input_enabled: bool,
  668    use_modal_editing: bool,
  669    read_only: bool,
  670    leader_peer_id: Option<PeerId>,
  671    remote_id: Option<ViewId>,
  672    hover_state: HoverState,
  673    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  674    gutter_hovered: bool,
  675    hovered_link_state: Option<HoveredLinkState>,
  676    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  677    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  678    active_inline_completion: Option<InlineCompletionState>,
  679    /// Used to prevent flickering as the user types while the menu is open
  680    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  681    // enable_inline_completions is a switch that Vim can use to disable
  682    // edit predictions based on its mode.
  683    enable_inline_completions: bool,
  684    show_inline_completions_override: Option<bool>,
  685    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  686    inlay_hint_cache: InlayHintCache,
  687    next_inlay_id: usize,
  688    _subscriptions: Vec<Subscription>,
  689    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  690    gutter_dimensions: GutterDimensions,
  691    style: Option<EditorStyle>,
  692    text_style_refinement: Option<TextStyleRefinement>,
  693    next_editor_action_id: EditorActionId,
  694    editor_actions:
  695        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  696    use_autoclose: bool,
  697    use_auto_surround: bool,
  698    auto_replace_emoji_shortcode: bool,
  699    show_git_blame_gutter: bool,
  700    show_git_blame_inline: bool,
  701    show_git_blame_inline_delay_task: Option<Task<()>>,
  702    git_blame_inline_enabled: bool,
  703    serialize_dirty_buffers: bool,
  704    show_selection_menu: Option<bool>,
  705    blame: Option<Entity<GitBlame>>,
  706    blame_subscription: Option<Subscription>,
  707    custom_context_menu: Option<
  708        Box<
  709            dyn 'static
  710                + Fn(
  711                    &mut Self,
  712                    DisplayPoint,
  713                    &mut Window,
  714                    &mut Context<Self>,
  715                ) -> Option<Entity<ui::ContextMenu>>,
  716        >,
  717    >,
  718    last_bounds: Option<Bounds<Pixels>>,
  719    last_position_map: Option<Rc<PositionMap>>,
  720    expect_bounds_change: Option<Bounds<Pixels>>,
  721    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  722    tasks_update_task: Option<Task<()>>,
  723    in_project_search: bool,
  724    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  725    breadcrumb_header: Option<String>,
  726    focused_block: Option<FocusedBlock>,
  727    next_scroll_position: NextScrollCursorCenterTopBottom,
  728    addons: HashMap<TypeId, Box<dyn Addon>>,
  729    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  730    selection_mark_mode: bool,
  731    toggle_fold_multiple_buffers: Task<()>,
  732    _scroll_cursor_center_top_bottom_task: Task<()>,
  733}
  734
  735#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  736enum NextScrollCursorCenterTopBottom {
  737    #[default]
  738    Center,
  739    Top,
  740    Bottom,
  741}
  742
  743impl NextScrollCursorCenterTopBottom {
  744    fn next(&self) -> Self {
  745        match self {
  746            Self::Center => Self::Top,
  747            Self::Top => Self::Bottom,
  748            Self::Bottom => Self::Center,
  749        }
  750    }
  751}
  752
  753#[derive(Clone)]
  754pub struct EditorSnapshot {
  755    pub mode: EditorMode,
  756    show_gutter: bool,
  757    show_line_numbers: Option<bool>,
  758    show_git_diff_gutter: Option<bool>,
  759    show_code_actions: Option<bool>,
  760    show_runnables: Option<bool>,
  761    git_blame_gutter_max_author_length: Option<usize>,
  762    pub display_snapshot: DisplaySnapshot,
  763    pub placeholder_text: Option<Arc<str>>,
  764    is_focused: bool,
  765    scroll_anchor: ScrollAnchor,
  766    ongoing_scroll: OngoingScroll,
  767    current_line_highlight: CurrentLineHighlight,
  768    gutter_hovered: bool,
  769}
  770
  771const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  772
  773#[derive(Default, Debug, Clone, Copy)]
  774pub struct GutterDimensions {
  775    pub left_padding: Pixels,
  776    pub right_padding: Pixels,
  777    pub width: Pixels,
  778    pub margin: Pixels,
  779    pub git_blame_entries_width: Option<Pixels>,
  780}
  781
  782impl GutterDimensions {
  783    /// The full width of the space taken up by the gutter.
  784    pub fn full_width(&self) -> Pixels {
  785        self.margin + self.width
  786    }
  787
  788    /// The width of the space reserved for the fold indicators,
  789    /// use alongside 'justify_end' and `gutter_width` to
  790    /// right align content with the line numbers
  791    pub fn fold_area_width(&self) -> Pixels {
  792        self.margin + self.right_padding
  793    }
  794}
  795
  796#[derive(Debug)]
  797pub struct RemoteSelection {
  798    pub replica_id: ReplicaId,
  799    pub selection: Selection<Anchor>,
  800    pub cursor_shape: CursorShape,
  801    pub peer_id: PeerId,
  802    pub line_mode: bool,
  803    pub participant_index: Option<ParticipantIndex>,
  804    pub user_name: Option<SharedString>,
  805}
  806
  807#[derive(Clone, Debug)]
  808struct SelectionHistoryEntry {
  809    selections: Arc<[Selection<Anchor>]>,
  810    select_next_state: Option<SelectNextState>,
  811    select_prev_state: Option<SelectNextState>,
  812    add_selections_state: Option<AddSelectionsState>,
  813}
  814
  815enum SelectionHistoryMode {
  816    Normal,
  817    Undoing,
  818    Redoing,
  819}
  820
  821#[derive(Clone, PartialEq, Eq, Hash)]
  822struct HoveredCursor {
  823    replica_id: u16,
  824    selection_id: usize,
  825}
  826
  827impl Default for SelectionHistoryMode {
  828    fn default() -> Self {
  829        Self::Normal
  830    }
  831}
  832
  833#[derive(Default)]
  834struct SelectionHistory {
  835    #[allow(clippy::type_complexity)]
  836    selections_by_transaction:
  837        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  838    mode: SelectionHistoryMode,
  839    undo_stack: VecDeque<SelectionHistoryEntry>,
  840    redo_stack: VecDeque<SelectionHistoryEntry>,
  841}
  842
  843impl SelectionHistory {
  844    fn insert_transaction(
  845        &mut self,
  846        transaction_id: TransactionId,
  847        selections: Arc<[Selection<Anchor>]>,
  848    ) {
  849        self.selections_by_transaction
  850            .insert(transaction_id, (selections, None));
  851    }
  852
  853    #[allow(clippy::type_complexity)]
  854    fn transaction(
  855        &self,
  856        transaction_id: TransactionId,
  857    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  858        self.selections_by_transaction.get(&transaction_id)
  859    }
  860
  861    #[allow(clippy::type_complexity)]
  862    fn transaction_mut(
  863        &mut self,
  864        transaction_id: TransactionId,
  865    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  866        self.selections_by_transaction.get_mut(&transaction_id)
  867    }
  868
  869    fn push(&mut self, entry: SelectionHistoryEntry) {
  870        if !entry.selections.is_empty() {
  871            match self.mode {
  872                SelectionHistoryMode::Normal => {
  873                    self.push_undo(entry);
  874                    self.redo_stack.clear();
  875                }
  876                SelectionHistoryMode::Undoing => self.push_redo(entry),
  877                SelectionHistoryMode::Redoing => self.push_undo(entry),
  878            }
  879        }
  880    }
  881
  882    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  883        if self
  884            .undo_stack
  885            .back()
  886            .map_or(true, |e| e.selections != entry.selections)
  887        {
  888            self.undo_stack.push_back(entry);
  889            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  890                self.undo_stack.pop_front();
  891            }
  892        }
  893    }
  894
  895    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  896        if self
  897            .redo_stack
  898            .back()
  899            .map_or(true, |e| e.selections != entry.selections)
  900        {
  901            self.redo_stack.push_back(entry);
  902            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  903                self.redo_stack.pop_front();
  904            }
  905        }
  906    }
  907}
  908
  909struct RowHighlight {
  910    index: usize,
  911    range: Range<Anchor>,
  912    color: Hsla,
  913    should_autoscroll: bool,
  914}
  915
  916#[derive(Clone, Debug)]
  917struct AddSelectionsState {
  918    above: bool,
  919    stack: Vec<usize>,
  920}
  921
  922#[derive(Clone)]
  923struct SelectNextState {
  924    query: AhoCorasick,
  925    wordwise: bool,
  926    done: bool,
  927}
  928
  929impl std::fmt::Debug for SelectNextState {
  930    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  931        f.debug_struct(std::any::type_name::<Self>())
  932            .field("wordwise", &self.wordwise)
  933            .field("done", &self.done)
  934            .finish()
  935    }
  936}
  937
  938#[derive(Debug)]
  939struct AutocloseRegion {
  940    selection_id: usize,
  941    range: Range<Anchor>,
  942    pair: BracketPair,
  943}
  944
  945#[derive(Debug)]
  946struct SnippetState {
  947    ranges: Vec<Vec<Range<Anchor>>>,
  948    active_index: usize,
  949    choices: Vec<Option<Vec<String>>>,
  950}
  951
  952#[doc(hidden)]
  953pub struct RenameState {
  954    pub range: Range<Anchor>,
  955    pub old_name: Arc<str>,
  956    pub editor: Entity<Editor>,
  957    block_id: CustomBlockId,
  958}
  959
  960struct InvalidationStack<T>(Vec<T>);
  961
  962struct RegisteredInlineCompletionProvider {
  963    provider: Arc<dyn InlineCompletionProviderHandle>,
  964    _subscription: Subscription,
  965}
  966
  967#[derive(Debug)]
  968struct ActiveDiagnosticGroup {
  969    primary_range: Range<Anchor>,
  970    primary_message: String,
  971    group_id: usize,
  972    blocks: HashMap<CustomBlockId, Diagnostic>,
  973    is_valid: bool,
  974}
  975
  976#[derive(Serialize, Deserialize, Clone, Debug)]
  977pub struct ClipboardSelection {
  978    pub len: usize,
  979    pub is_entire_line: bool,
  980    pub first_line_indent: u32,
  981}
  982
  983#[derive(Debug)]
  984pub(crate) struct NavigationData {
  985    cursor_anchor: Anchor,
  986    cursor_position: Point,
  987    scroll_anchor: ScrollAnchor,
  988    scroll_top_row: u32,
  989}
  990
  991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  992pub enum GotoDefinitionKind {
  993    Symbol,
  994    Declaration,
  995    Type,
  996    Implementation,
  997}
  998
  999#[derive(Debug, Clone)]
 1000enum InlayHintRefreshReason {
 1001    Toggle(bool),
 1002    SettingsChange(InlayHintSettings),
 1003    NewLinesShown,
 1004    BufferEdited(HashSet<Arc<Language>>),
 1005    RefreshRequested,
 1006    ExcerptsRemoved(Vec<ExcerptId>),
 1007}
 1008
 1009impl InlayHintRefreshReason {
 1010    fn description(&self) -> &'static str {
 1011        match self {
 1012            Self::Toggle(_) => "toggle",
 1013            Self::SettingsChange(_) => "settings change",
 1014            Self::NewLinesShown => "new lines shown",
 1015            Self::BufferEdited(_) => "buffer edited",
 1016            Self::RefreshRequested => "refresh requested",
 1017            Self::ExcerptsRemoved(_) => "excerpts removed",
 1018        }
 1019    }
 1020}
 1021
 1022pub enum FormatTarget {
 1023    Buffers,
 1024    Ranges(Vec<Range<MultiBufferPoint>>),
 1025}
 1026
 1027pub(crate) struct FocusedBlock {
 1028    id: BlockId,
 1029    focus_handle: WeakFocusHandle,
 1030}
 1031
 1032#[derive(Clone)]
 1033enum JumpData {
 1034    MultiBufferRow {
 1035        row: MultiBufferRow,
 1036        line_offset_from_top: u32,
 1037    },
 1038    MultiBufferPoint {
 1039        excerpt_id: ExcerptId,
 1040        position: Point,
 1041        anchor: text::Anchor,
 1042        line_offset_from_top: u32,
 1043    },
 1044}
 1045
 1046pub enum MultibufferSelectionMode {
 1047    First,
 1048    All,
 1049}
 1050
 1051impl Editor {
 1052    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1053        let buffer = cx.new(|cx| Buffer::local("", cx));
 1054        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1055        Self::new(
 1056            EditorMode::SingleLine { auto_width: false },
 1057            buffer,
 1058            None,
 1059            false,
 1060            window,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1066        let buffer = cx.new(|cx| Buffer::local("", cx));
 1067        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1068        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1069    }
 1070
 1071    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1072        let buffer = cx.new(|cx| Buffer::local("", cx));
 1073        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(
 1075            EditorMode::SingleLine { auto_width: true },
 1076            buffer,
 1077            None,
 1078            false,
 1079            window,
 1080            cx,
 1081        )
 1082    }
 1083
 1084    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::AutoHeight { max_lines },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn for_buffer(
 1098        buffer: Entity<Buffer>,
 1099        project: Option<Entity<Project>>,
 1100        window: &mut Window,
 1101        cx: &mut Context<Self>,
 1102    ) -> Self {
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1105    }
 1106
 1107    pub fn for_multibuffer(
 1108        buffer: Entity<MultiBuffer>,
 1109        project: Option<Entity<Project>>,
 1110        show_excerpt_controls: bool,
 1111        window: &mut Window,
 1112        cx: &mut Context<Self>,
 1113    ) -> Self {
 1114        Self::new(
 1115            EditorMode::Full,
 1116            buffer,
 1117            project,
 1118            show_excerpt_controls,
 1119            window,
 1120            cx,
 1121        )
 1122    }
 1123
 1124    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1125        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1126        let mut clone = Self::new(
 1127            self.mode,
 1128            self.buffer.clone(),
 1129            self.project.clone(),
 1130            show_excerpt_controls,
 1131            window,
 1132            cx,
 1133        );
 1134        self.display_map.update(cx, |display_map, cx| {
 1135            let snapshot = display_map.snapshot(cx);
 1136            clone.display_map.update(cx, |display_map, cx| {
 1137                display_map.set_state(&snapshot, cx);
 1138            });
 1139        });
 1140        clone.selections.clone_state(&self.selections);
 1141        clone.scroll_manager.clone_state(&self.scroll_manager);
 1142        clone.searchable = self.searchable;
 1143        clone
 1144    }
 1145
 1146    pub fn new(
 1147        mode: EditorMode,
 1148        buffer: Entity<MultiBuffer>,
 1149        project: Option<Entity<Project>>,
 1150        show_excerpt_controls: bool,
 1151        window: &mut Window,
 1152        cx: &mut Context<Self>,
 1153    ) -> Self {
 1154        let style = window.text_style();
 1155        let font_size = style.font_size.to_pixels(window.rem_size());
 1156        let editor = cx.entity().downgrade();
 1157        let fold_placeholder = FoldPlaceholder {
 1158            constrain_width: true,
 1159            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1160                let editor = editor.clone();
 1161                div()
 1162                    .id(fold_id)
 1163                    .bg(cx.theme().colors().ghost_element_background)
 1164                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1165                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1166                    .rounded_sm()
 1167                    .size_full()
 1168                    .cursor_pointer()
 1169                    .child("")
 1170                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1171                    .on_click(move |_, _window, cx| {
 1172                        editor
 1173                            .update(cx, |editor, cx| {
 1174                                editor.unfold_ranges(
 1175                                    &[fold_range.start..fold_range.end],
 1176                                    true,
 1177                                    false,
 1178                                    cx,
 1179                                );
 1180                                cx.stop_propagation();
 1181                            })
 1182                            .ok();
 1183                    })
 1184                    .into_any()
 1185            }),
 1186            merge_adjacent: true,
 1187            ..Default::default()
 1188        };
 1189        let display_map = cx.new(|cx| {
 1190            DisplayMap::new(
 1191                buffer.clone(),
 1192                style.font(),
 1193                font_size,
 1194                None,
 1195                show_excerpt_controls,
 1196                FILE_HEADER_HEIGHT,
 1197                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1198                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1199                fold_placeholder,
 1200                cx,
 1201            )
 1202        });
 1203
 1204        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1205
 1206        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1207
 1208        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1209            .then(|| language_settings::SoftWrap::None);
 1210
 1211        let mut project_subscriptions = Vec::new();
 1212        if mode == EditorMode::Full {
 1213            if let Some(project) = project.as_ref() {
 1214                if buffer.read(cx).is_singleton() {
 1215                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1216                        cx.emit(EditorEvent::TitleChanged);
 1217                    }));
 1218                }
 1219                project_subscriptions.push(cx.subscribe_in(
 1220                    project,
 1221                    window,
 1222                    |editor, _, event, window, cx| {
 1223                        if let project::Event::RefreshInlayHints = event {
 1224                            editor
 1225                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1226                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1227                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1228                                let focus_handle = editor.focus_handle(cx);
 1229                                if focus_handle.is_focused(window) {
 1230                                    let snapshot = buffer.read(cx).snapshot();
 1231                                    for (range, snippet) in snippet_edits {
 1232                                        let editor_range =
 1233                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1234                                        editor
 1235                                            .insert_snippet(
 1236                                                &[editor_range],
 1237                                                snippet.clone(),
 1238                                                window,
 1239                                                cx,
 1240                                            )
 1241                                            .ok();
 1242                                    }
 1243                                }
 1244                            }
 1245                        }
 1246                    },
 1247                ));
 1248                if let Some(task_inventory) = project
 1249                    .read(cx)
 1250                    .task_store()
 1251                    .read(cx)
 1252                    .task_inventory()
 1253                    .cloned()
 1254                {
 1255                    project_subscriptions.push(cx.observe_in(
 1256                        &task_inventory,
 1257                        window,
 1258                        |editor, _, window, cx| {
 1259                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1260                        },
 1261                    ));
 1262                }
 1263            }
 1264        }
 1265
 1266        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1267
 1268        let inlay_hint_settings =
 1269            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1270        let focus_handle = cx.focus_handle();
 1271        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1272            .detach();
 1273        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1274            .detach();
 1275        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1276            .detach();
 1277        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1278            .detach();
 1279
 1280        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1281            Some(false)
 1282        } else {
 1283            None
 1284        };
 1285
 1286        let mut code_action_providers = Vec::new();
 1287        if let Some(project) = project.clone() {
 1288            get_unstaged_changes_for_buffers(
 1289                &project,
 1290                buffer.read(cx).all_buffers(),
 1291                buffer.clone(),
 1292                cx,
 1293            );
 1294            code_action_providers.push(Rc::new(project) as Rc<_>);
 1295        }
 1296
 1297        let mut this = Self {
 1298            focus_handle,
 1299            show_cursor_when_unfocused: false,
 1300            last_focused_descendant: None,
 1301            buffer: buffer.clone(),
 1302            display_map: display_map.clone(),
 1303            selections,
 1304            scroll_manager: ScrollManager::new(cx),
 1305            columnar_selection_tail: None,
 1306            add_selections_state: None,
 1307            select_next_state: None,
 1308            select_prev_state: None,
 1309            selection_history: Default::default(),
 1310            autoclose_regions: Default::default(),
 1311            snippet_stack: Default::default(),
 1312            select_larger_syntax_node_stack: Vec::new(),
 1313            ime_transaction: Default::default(),
 1314            active_diagnostics: None,
 1315            soft_wrap_mode_override,
 1316            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1317            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1318            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1319            project,
 1320            blink_manager: blink_manager.clone(),
 1321            show_local_selections: true,
 1322            show_scrollbars: true,
 1323            mode,
 1324            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1325            show_gutter: mode == EditorMode::Full,
 1326            show_line_numbers: None,
 1327            use_relative_line_numbers: None,
 1328            show_git_diff_gutter: None,
 1329            show_code_actions: None,
 1330            show_runnables: None,
 1331            show_wrap_guides: None,
 1332            show_indent_guides,
 1333            placeholder_text: None,
 1334            highlight_order: 0,
 1335            highlighted_rows: HashMap::default(),
 1336            background_highlights: Default::default(),
 1337            gutter_highlights: TreeMap::default(),
 1338            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1339            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1340            nav_history: None,
 1341            context_menu: RefCell::new(None),
 1342            mouse_context_menu: None,
 1343            completion_tasks: Default::default(),
 1344            signature_help_state: SignatureHelpState::default(),
 1345            auto_signature_help: None,
 1346            find_all_references_task_sources: Vec::new(),
 1347            next_completion_id: 0,
 1348            next_inlay_id: 0,
 1349            code_action_providers,
 1350            available_code_actions: Default::default(),
 1351            code_actions_task: Default::default(),
 1352            document_highlights_task: Default::default(),
 1353            linked_editing_range_task: Default::default(),
 1354            pending_rename: Default::default(),
 1355            searchable: true,
 1356            cursor_shape: EditorSettings::get_global(cx)
 1357                .cursor_shape
 1358                .unwrap_or_default(),
 1359            current_line_highlight: None,
 1360            autoindent_mode: Some(AutoindentMode::EachLine),
 1361            collapse_matches: false,
 1362            workspace: None,
 1363            input_enabled: true,
 1364            use_modal_editing: mode == EditorMode::Full,
 1365            read_only: false,
 1366            use_autoclose: true,
 1367            use_auto_surround: true,
 1368            auto_replace_emoji_shortcode: false,
 1369            leader_peer_id: None,
 1370            remote_id: None,
 1371            hover_state: Default::default(),
 1372            pending_mouse_down: None,
 1373            hovered_link_state: Default::default(),
 1374            inline_completion_provider: None,
 1375            active_inline_completion: None,
 1376            stale_inline_completion_in_menu: None,
 1377            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1378
 1379            gutter_hovered: false,
 1380            pixel_position_of_newest_cursor: None,
 1381            last_bounds: None,
 1382            last_position_map: None,
 1383            expect_bounds_change: None,
 1384            gutter_dimensions: GutterDimensions::default(),
 1385            style: None,
 1386            show_cursor_names: false,
 1387            hovered_cursors: Default::default(),
 1388            next_editor_action_id: EditorActionId::default(),
 1389            editor_actions: Rc::default(),
 1390            show_inline_completions_override: None,
 1391            enable_inline_completions: true,
 1392            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1393            custom_context_menu: None,
 1394            show_git_blame_gutter: false,
 1395            show_git_blame_inline: false,
 1396            show_selection_menu: None,
 1397            show_git_blame_inline_delay_task: None,
 1398            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1399            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1400                .session
 1401                .restore_unsaved_buffers,
 1402            blame: None,
 1403            blame_subscription: None,
 1404            tasks: Default::default(),
 1405            _subscriptions: vec![
 1406                cx.observe(&buffer, Self::on_buffer_changed),
 1407                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1408                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1409                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1410                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1411                cx.observe_window_activation(window, |editor, window, cx| {
 1412                    let active = window.is_window_active();
 1413                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1414                        if active {
 1415                            blink_manager.enable(cx);
 1416                        } else {
 1417                            blink_manager.disable(cx);
 1418                        }
 1419                    });
 1420                }),
 1421            ],
 1422            tasks_update_task: None,
 1423            linked_edit_ranges: Default::default(),
 1424            in_project_search: false,
 1425            previous_search_ranges: None,
 1426            breadcrumb_header: None,
 1427            focused_block: None,
 1428            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1429            addons: HashMap::default(),
 1430            registered_buffers: HashMap::default(),
 1431            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1432            selection_mark_mode: false,
 1433            toggle_fold_multiple_buffers: Task::ready(()),
 1434            text_style_refinement: None,
 1435        };
 1436        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1437        this._subscriptions.extend(project_subscriptions);
 1438
 1439        this.end_selection(window, cx);
 1440        this.scroll_manager.show_scrollbar(window, cx);
 1441
 1442        if mode == EditorMode::Full {
 1443            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1444            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1445
 1446            if this.git_blame_inline_enabled {
 1447                this.git_blame_inline_enabled = true;
 1448                this.start_git_blame_inline(false, window, cx);
 1449            }
 1450
 1451            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1452                if let Some(project) = this.project.as_ref() {
 1453                    let lsp_store = project.read(cx).lsp_store();
 1454                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1455                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1456                    });
 1457                    this.registered_buffers
 1458                        .insert(buffer.read(cx).remote_id(), handle);
 1459                }
 1460            }
 1461        }
 1462
 1463        this.report_editor_event("Editor Opened", None, cx);
 1464        this
 1465    }
 1466
 1467    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1468        self.mouse_context_menu
 1469            .as_ref()
 1470            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1471    }
 1472
 1473    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1474        let mut key_context = KeyContext::new_with_defaults();
 1475        key_context.add("Editor");
 1476        let mode = match self.mode {
 1477            EditorMode::SingleLine { .. } => "single_line",
 1478            EditorMode::AutoHeight { .. } => "auto_height",
 1479            EditorMode::Full => "full",
 1480        };
 1481
 1482        if EditorSettings::jupyter_enabled(cx) {
 1483            key_context.add("jupyter");
 1484        }
 1485
 1486        key_context.set("mode", mode);
 1487        if self.pending_rename.is_some() {
 1488            key_context.add("renaming");
 1489        }
 1490        match self.context_menu.borrow().as_ref() {
 1491            Some(CodeContextMenu::Completions(_)) => {
 1492                key_context.add("menu");
 1493                key_context.add("showing_completions");
 1494            }
 1495            Some(CodeContextMenu::CodeActions(_)) => {
 1496                key_context.add("menu");
 1497                key_context.add("showing_code_actions")
 1498            }
 1499            None => {}
 1500        }
 1501
 1502        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1503        if !self.focus_handle(cx).contains_focused(window, cx)
 1504            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1505        {
 1506            for addon in self.addons.values() {
 1507                addon.extend_key_context(&mut key_context, cx)
 1508            }
 1509        }
 1510
 1511        if let Some(extension) = self
 1512            .buffer
 1513            .read(cx)
 1514            .as_singleton()
 1515            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1516        {
 1517            key_context.set("extension", extension.to_string());
 1518        }
 1519
 1520        if self.has_active_inline_completion() {
 1521            key_context.add("copilot_suggestion");
 1522            key_context.add("inline_completion");
 1523        }
 1524
 1525        if self.selection_mark_mode {
 1526            key_context.add("selection_mode");
 1527        }
 1528
 1529        key_context
 1530    }
 1531
 1532    pub fn new_file(
 1533        workspace: &mut Workspace,
 1534        _: &workspace::NewFile,
 1535        window: &mut Window,
 1536        cx: &mut Context<Workspace>,
 1537    ) {
 1538        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1539            "Failed to create buffer",
 1540            window,
 1541            cx,
 1542            |e, _, _| match e.error_code() {
 1543                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1544                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1545                e.error_tag("required").unwrap_or("the latest version")
 1546            )),
 1547                _ => None,
 1548            },
 1549        );
 1550    }
 1551
 1552    pub fn new_in_workspace(
 1553        workspace: &mut Workspace,
 1554        window: &mut Window,
 1555        cx: &mut Context<Workspace>,
 1556    ) -> Task<Result<Entity<Editor>>> {
 1557        let project = workspace.project().clone();
 1558        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1559
 1560        cx.spawn_in(window, |workspace, mut cx| async move {
 1561            let buffer = create.await?;
 1562            workspace.update_in(&mut cx, |workspace, window, cx| {
 1563                let editor =
 1564                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1565                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1566                editor
 1567            })
 1568        })
 1569    }
 1570
 1571    fn new_file_vertical(
 1572        workspace: &mut Workspace,
 1573        _: &workspace::NewFileSplitVertical,
 1574        window: &mut Window,
 1575        cx: &mut Context<Workspace>,
 1576    ) {
 1577        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1578    }
 1579
 1580    fn new_file_horizontal(
 1581        workspace: &mut Workspace,
 1582        _: &workspace::NewFileSplitHorizontal,
 1583        window: &mut Window,
 1584        cx: &mut Context<Workspace>,
 1585    ) {
 1586        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1587    }
 1588
 1589    fn new_file_in_direction(
 1590        workspace: &mut Workspace,
 1591        direction: SplitDirection,
 1592        window: &mut Window,
 1593        cx: &mut Context<Workspace>,
 1594    ) {
 1595        let project = workspace.project().clone();
 1596        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1597
 1598        cx.spawn_in(window, |workspace, mut cx| async move {
 1599            let buffer = create.await?;
 1600            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1601                workspace.split_item(
 1602                    direction,
 1603                    Box::new(
 1604                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1605                    ),
 1606                    window,
 1607                    cx,
 1608                )
 1609            })?;
 1610            anyhow::Ok(())
 1611        })
 1612        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1613            match e.error_code() {
 1614                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1615                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1616                e.error_tag("required").unwrap_or("the latest version")
 1617            )),
 1618                _ => None,
 1619            }
 1620        });
 1621    }
 1622
 1623    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1624        self.leader_peer_id
 1625    }
 1626
 1627    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1628        &self.buffer
 1629    }
 1630
 1631    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1632        self.workspace.as_ref()?.0.upgrade()
 1633    }
 1634
 1635    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1636        self.buffer().read(cx).title(cx)
 1637    }
 1638
 1639    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1640        let git_blame_gutter_max_author_length = self
 1641            .render_git_blame_gutter(cx)
 1642            .then(|| {
 1643                if let Some(blame) = self.blame.as_ref() {
 1644                    let max_author_length =
 1645                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1646                    Some(max_author_length)
 1647                } else {
 1648                    None
 1649                }
 1650            })
 1651            .flatten();
 1652
 1653        EditorSnapshot {
 1654            mode: self.mode,
 1655            show_gutter: self.show_gutter,
 1656            show_line_numbers: self.show_line_numbers,
 1657            show_git_diff_gutter: self.show_git_diff_gutter,
 1658            show_code_actions: self.show_code_actions,
 1659            show_runnables: self.show_runnables,
 1660            git_blame_gutter_max_author_length,
 1661            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1662            scroll_anchor: self.scroll_manager.anchor(),
 1663            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1664            placeholder_text: self.placeholder_text.clone(),
 1665            is_focused: self.focus_handle.is_focused(window),
 1666            current_line_highlight: self
 1667                .current_line_highlight
 1668                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1669            gutter_hovered: self.gutter_hovered,
 1670        }
 1671    }
 1672
 1673    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1674        self.buffer.read(cx).language_at(point, cx)
 1675    }
 1676
 1677    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1678        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1679    }
 1680
 1681    pub fn active_excerpt(
 1682        &self,
 1683        cx: &App,
 1684    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1685        self.buffer
 1686            .read(cx)
 1687            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1688    }
 1689
 1690    pub fn mode(&self) -> EditorMode {
 1691        self.mode
 1692    }
 1693
 1694    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1695        self.collaboration_hub.as_deref()
 1696    }
 1697
 1698    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1699        self.collaboration_hub = Some(hub);
 1700    }
 1701
 1702    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1703        self.in_project_search = in_project_search;
 1704    }
 1705
 1706    pub fn set_custom_context_menu(
 1707        &mut self,
 1708        f: impl 'static
 1709            + Fn(
 1710                &mut Self,
 1711                DisplayPoint,
 1712                &mut Window,
 1713                &mut Context<Self>,
 1714            ) -> Option<Entity<ui::ContextMenu>>,
 1715    ) {
 1716        self.custom_context_menu = Some(Box::new(f))
 1717    }
 1718
 1719    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1720        self.completion_provider = provider;
 1721    }
 1722
 1723    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1724        self.semantics_provider.clone()
 1725    }
 1726
 1727    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1728        self.semantics_provider = provider;
 1729    }
 1730
 1731    pub fn set_inline_completion_provider<T>(
 1732        &mut self,
 1733        provider: Option<Entity<T>>,
 1734        window: &mut Window,
 1735        cx: &mut Context<Self>,
 1736    ) where
 1737        T: InlineCompletionProvider,
 1738    {
 1739        self.inline_completion_provider =
 1740            provider.map(|provider| RegisteredInlineCompletionProvider {
 1741                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1742                    if this.focus_handle.is_focused(window) {
 1743                        this.update_visible_inline_completion(window, cx);
 1744                    }
 1745                }),
 1746                provider: Arc::new(provider),
 1747            });
 1748        self.refresh_inline_completion(false, false, window, cx);
 1749    }
 1750
 1751    pub fn placeholder_text(&self) -> Option<&str> {
 1752        self.placeholder_text.as_deref()
 1753    }
 1754
 1755    pub fn set_placeholder_text(
 1756        &mut self,
 1757        placeholder_text: impl Into<Arc<str>>,
 1758        cx: &mut Context<Self>,
 1759    ) {
 1760        let placeholder_text = Some(placeholder_text.into());
 1761        if self.placeholder_text != placeholder_text {
 1762            self.placeholder_text = placeholder_text;
 1763            cx.notify();
 1764        }
 1765    }
 1766
 1767    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1768        self.cursor_shape = cursor_shape;
 1769
 1770        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1771        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1772
 1773        cx.notify();
 1774    }
 1775
 1776    pub fn set_current_line_highlight(
 1777        &mut self,
 1778        current_line_highlight: Option<CurrentLineHighlight>,
 1779    ) {
 1780        self.current_line_highlight = current_line_highlight;
 1781    }
 1782
 1783    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1784        self.collapse_matches = collapse_matches;
 1785    }
 1786
 1787    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1788        let buffers = self.buffer.read(cx).all_buffers();
 1789        let Some(lsp_store) = self.lsp_store(cx) else {
 1790            return;
 1791        };
 1792        lsp_store.update(cx, |lsp_store, cx| {
 1793            for buffer in buffers {
 1794                self.registered_buffers
 1795                    .entry(buffer.read(cx).remote_id())
 1796                    .or_insert_with(|| {
 1797                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1798                    });
 1799            }
 1800        })
 1801    }
 1802
 1803    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1804        if self.collapse_matches {
 1805            return range.start..range.start;
 1806        }
 1807        range.clone()
 1808    }
 1809
 1810    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1811        if self.display_map.read(cx).clip_at_line_ends != clip {
 1812            self.display_map
 1813                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1814        }
 1815    }
 1816
 1817    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1818        self.input_enabled = input_enabled;
 1819    }
 1820
 1821    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1822        self.enable_inline_completions = enabled;
 1823        if !self.enable_inline_completions {
 1824            self.take_active_inline_completion(cx);
 1825            cx.notify();
 1826        }
 1827    }
 1828
 1829    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1830        self.menu_inline_completions_policy = value;
 1831    }
 1832
 1833    pub fn set_autoindent(&mut self, autoindent: bool) {
 1834        if autoindent {
 1835            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1836        } else {
 1837            self.autoindent_mode = None;
 1838        }
 1839    }
 1840
 1841    pub fn read_only(&self, cx: &App) -> bool {
 1842        self.read_only || self.buffer.read(cx).read_only()
 1843    }
 1844
 1845    pub fn set_read_only(&mut self, read_only: bool) {
 1846        self.read_only = read_only;
 1847    }
 1848
 1849    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1850        self.use_autoclose = autoclose;
 1851    }
 1852
 1853    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1854        self.use_auto_surround = auto_surround;
 1855    }
 1856
 1857    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1858        self.auto_replace_emoji_shortcode = auto_replace;
 1859    }
 1860
 1861    pub fn toggle_inline_completions(
 1862        &mut self,
 1863        _: &ToggleInlineCompletions,
 1864        window: &mut Window,
 1865        cx: &mut Context<Self>,
 1866    ) {
 1867        if self.show_inline_completions_override.is_some() {
 1868            self.set_show_inline_completions(None, window, cx);
 1869        } else {
 1870            let cursor = self.selections.newest_anchor().head();
 1871            if let Some((buffer, cursor_buffer_position)) =
 1872                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1873            {
 1874                let show_inline_completions =
 1875                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1876                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1877            }
 1878        }
 1879    }
 1880
 1881    pub fn set_show_inline_completions(
 1882        &mut self,
 1883        show_inline_completions: Option<bool>,
 1884        window: &mut Window,
 1885        cx: &mut Context<Self>,
 1886    ) {
 1887        self.show_inline_completions_override = show_inline_completions;
 1888        self.refresh_inline_completion(false, true, window, cx);
 1889    }
 1890
 1891    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1892        let cursor = self.selections.newest_anchor().head();
 1893        if let Some((buffer, buffer_position)) =
 1894            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1895        {
 1896            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1897        } else {
 1898            false
 1899        }
 1900    }
 1901
 1902    fn should_show_inline_completions(
 1903        &self,
 1904        buffer: &Entity<Buffer>,
 1905        buffer_position: language::Anchor,
 1906        cx: &App,
 1907    ) -> bool {
 1908        if !self.snippet_stack.is_empty() {
 1909            return false;
 1910        }
 1911
 1912        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1913            return false;
 1914        }
 1915
 1916        if let Some(provider) = self.inline_completion_provider() {
 1917            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1918                show_inline_completions
 1919            } else {
 1920                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1921            }
 1922        } else {
 1923            false
 1924        }
 1925    }
 1926
 1927    fn inline_completions_disabled_in_scope(
 1928        &self,
 1929        buffer: &Entity<Buffer>,
 1930        buffer_position: language::Anchor,
 1931        cx: &App,
 1932    ) -> bool {
 1933        let snapshot = buffer.read(cx).snapshot();
 1934        let settings = snapshot.settings_at(buffer_position, cx);
 1935
 1936        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1937            return false;
 1938        };
 1939
 1940        scope.override_name().map_or(false, |scope_name| {
 1941            settings
 1942                .inline_completions_disabled_in
 1943                .iter()
 1944                .any(|s| s == scope_name)
 1945        })
 1946    }
 1947
 1948    pub fn set_use_modal_editing(&mut self, to: bool) {
 1949        self.use_modal_editing = to;
 1950    }
 1951
 1952    pub fn use_modal_editing(&self) -> bool {
 1953        self.use_modal_editing
 1954    }
 1955
 1956    fn selections_did_change(
 1957        &mut self,
 1958        local: bool,
 1959        old_cursor_position: &Anchor,
 1960        show_completions: bool,
 1961        window: &mut Window,
 1962        cx: &mut Context<Self>,
 1963    ) {
 1964        window.invalidate_character_coordinates();
 1965
 1966        // Copy selections to primary selection buffer
 1967        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1968        if local {
 1969            let selections = self.selections.all::<usize>(cx);
 1970            let buffer_handle = self.buffer.read(cx).read(cx);
 1971
 1972            let mut text = String::new();
 1973            for (index, selection) in selections.iter().enumerate() {
 1974                let text_for_selection = buffer_handle
 1975                    .text_for_range(selection.start..selection.end)
 1976                    .collect::<String>();
 1977
 1978                text.push_str(&text_for_selection);
 1979                if index != selections.len() - 1 {
 1980                    text.push('\n');
 1981                }
 1982            }
 1983
 1984            if !text.is_empty() {
 1985                cx.write_to_primary(ClipboardItem::new_string(text));
 1986            }
 1987        }
 1988
 1989        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1990            self.buffer.update(cx, |buffer, cx| {
 1991                buffer.set_active_selections(
 1992                    &self.selections.disjoint_anchors(),
 1993                    self.selections.line_mode,
 1994                    self.cursor_shape,
 1995                    cx,
 1996                )
 1997            });
 1998        }
 1999        let display_map = self
 2000            .display_map
 2001            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2002        let buffer = &display_map.buffer_snapshot;
 2003        self.add_selections_state = None;
 2004        self.select_next_state = None;
 2005        self.select_prev_state = None;
 2006        self.select_larger_syntax_node_stack.clear();
 2007        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2008        self.snippet_stack
 2009            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2010        self.take_rename(false, window, cx);
 2011
 2012        let new_cursor_position = self.selections.newest_anchor().head();
 2013
 2014        self.push_to_nav_history(
 2015            *old_cursor_position,
 2016            Some(new_cursor_position.to_point(buffer)),
 2017            cx,
 2018        );
 2019
 2020        if local {
 2021            let new_cursor_position = self.selections.newest_anchor().head();
 2022            let mut context_menu = self.context_menu.borrow_mut();
 2023            let completion_menu = match context_menu.as_ref() {
 2024                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2025                _ => {
 2026                    *context_menu = None;
 2027                    None
 2028                }
 2029            };
 2030
 2031            if let Some(completion_menu) = completion_menu {
 2032                let cursor_position = new_cursor_position.to_offset(buffer);
 2033                let (word_range, kind) =
 2034                    buffer.surrounding_word(completion_menu.initial_position, true);
 2035                if kind == Some(CharKind::Word)
 2036                    && word_range.to_inclusive().contains(&cursor_position)
 2037                {
 2038                    let mut completion_menu = completion_menu.clone();
 2039                    drop(context_menu);
 2040
 2041                    let query = Self::completion_query(buffer, cursor_position);
 2042                    cx.spawn(move |this, mut cx| async move {
 2043                        completion_menu
 2044                            .filter(query.as_deref(), cx.background_executor().clone())
 2045                            .await;
 2046
 2047                        this.update(&mut cx, |this, cx| {
 2048                            let mut context_menu = this.context_menu.borrow_mut();
 2049                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2050                            else {
 2051                                return;
 2052                            };
 2053
 2054                            if menu.id > completion_menu.id {
 2055                                return;
 2056                            }
 2057
 2058                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2059                            drop(context_menu);
 2060                            cx.notify();
 2061                        })
 2062                    })
 2063                    .detach();
 2064
 2065                    if show_completions {
 2066                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2067                    }
 2068                } else {
 2069                    drop(context_menu);
 2070                    self.hide_context_menu(window, cx);
 2071                }
 2072            } else {
 2073                drop(context_menu);
 2074            }
 2075
 2076            hide_hover(self, cx);
 2077
 2078            if old_cursor_position.to_display_point(&display_map).row()
 2079                != new_cursor_position.to_display_point(&display_map).row()
 2080            {
 2081                self.available_code_actions.take();
 2082            }
 2083            self.refresh_code_actions(window, cx);
 2084            self.refresh_document_highlights(cx);
 2085            refresh_matching_bracket_highlights(self, window, cx);
 2086            self.update_visible_inline_completion(window, cx);
 2087            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2088            if self.git_blame_inline_enabled {
 2089                self.start_inline_blame_timer(window, cx);
 2090            }
 2091        }
 2092
 2093        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2094        cx.emit(EditorEvent::SelectionsChanged { local });
 2095
 2096        if self.selections.disjoint_anchors().len() == 1 {
 2097            cx.emit(SearchEvent::ActiveMatchChanged)
 2098        }
 2099        cx.notify();
 2100    }
 2101
 2102    pub fn change_selections<R>(
 2103        &mut self,
 2104        autoscroll: Option<Autoscroll>,
 2105        window: &mut Window,
 2106        cx: &mut Context<Self>,
 2107        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2108    ) -> R {
 2109        self.change_selections_inner(autoscroll, true, window, cx, change)
 2110    }
 2111
 2112    pub fn change_selections_inner<R>(
 2113        &mut self,
 2114        autoscroll: Option<Autoscroll>,
 2115        request_completions: bool,
 2116        window: &mut Window,
 2117        cx: &mut Context<Self>,
 2118        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2119    ) -> R {
 2120        let old_cursor_position = self.selections.newest_anchor().head();
 2121        self.push_to_selection_history();
 2122
 2123        let (changed, result) = self.selections.change_with(cx, change);
 2124
 2125        if changed {
 2126            if let Some(autoscroll) = autoscroll {
 2127                self.request_autoscroll(autoscroll, cx);
 2128            }
 2129            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2130
 2131            if self.should_open_signature_help_automatically(
 2132                &old_cursor_position,
 2133                self.signature_help_state.backspace_pressed(),
 2134                cx,
 2135            ) {
 2136                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2137            }
 2138            self.signature_help_state.set_backspace_pressed(false);
 2139        }
 2140
 2141        result
 2142    }
 2143
 2144    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2145    where
 2146        I: IntoIterator<Item = (Range<S>, T)>,
 2147        S: ToOffset,
 2148        T: Into<Arc<str>>,
 2149    {
 2150        if self.read_only(cx) {
 2151            return;
 2152        }
 2153
 2154        self.buffer
 2155            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2156    }
 2157
 2158    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2159    where
 2160        I: IntoIterator<Item = (Range<S>, T)>,
 2161        S: ToOffset,
 2162        T: Into<Arc<str>>,
 2163    {
 2164        if self.read_only(cx) {
 2165            return;
 2166        }
 2167
 2168        self.buffer.update(cx, |buffer, cx| {
 2169            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2170        });
 2171    }
 2172
 2173    pub fn edit_with_block_indent<I, S, T>(
 2174        &mut self,
 2175        edits: I,
 2176        original_indent_columns: Vec<u32>,
 2177        cx: &mut Context<Self>,
 2178    ) where
 2179        I: IntoIterator<Item = (Range<S>, T)>,
 2180        S: ToOffset,
 2181        T: Into<Arc<str>>,
 2182    {
 2183        if self.read_only(cx) {
 2184            return;
 2185        }
 2186
 2187        self.buffer.update(cx, |buffer, cx| {
 2188            buffer.edit(
 2189                edits,
 2190                Some(AutoindentMode::Block {
 2191                    original_indent_columns,
 2192                }),
 2193                cx,
 2194            )
 2195        });
 2196    }
 2197
 2198    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2199        self.hide_context_menu(window, cx);
 2200
 2201        match phase {
 2202            SelectPhase::Begin {
 2203                position,
 2204                add,
 2205                click_count,
 2206            } => self.begin_selection(position, add, click_count, window, cx),
 2207            SelectPhase::BeginColumnar {
 2208                position,
 2209                goal_column,
 2210                reset,
 2211            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2212            SelectPhase::Extend {
 2213                position,
 2214                click_count,
 2215            } => self.extend_selection(position, click_count, window, cx),
 2216            SelectPhase::Update {
 2217                position,
 2218                goal_column,
 2219                scroll_delta,
 2220            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2221            SelectPhase::End => self.end_selection(window, cx),
 2222        }
 2223    }
 2224
 2225    fn extend_selection(
 2226        &mut self,
 2227        position: DisplayPoint,
 2228        click_count: usize,
 2229        window: &mut Window,
 2230        cx: &mut Context<Self>,
 2231    ) {
 2232        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2233        let tail = self.selections.newest::<usize>(cx).tail();
 2234        self.begin_selection(position, false, click_count, window, cx);
 2235
 2236        let position = position.to_offset(&display_map, Bias::Left);
 2237        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2238
 2239        let mut pending_selection = self
 2240            .selections
 2241            .pending_anchor()
 2242            .expect("extend_selection not called with pending selection");
 2243        if position >= tail {
 2244            pending_selection.start = tail_anchor;
 2245        } else {
 2246            pending_selection.end = tail_anchor;
 2247            pending_selection.reversed = true;
 2248        }
 2249
 2250        let mut pending_mode = self.selections.pending_mode().unwrap();
 2251        match &mut pending_mode {
 2252            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2253            _ => {}
 2254        }
 2255
 2256        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2257            s.set_pending(pending_selection, pending_mode)
 2258        });
 2259    }
 2260
 2261    fn begin_selection(
 2262        &mut self,
 2263        position: DisplayPoint,
 2264        add: bool,
 2265        click_count: usize,
 2266        window: &mut Window,
 2267        cx: &mut Context<Self>,
 2268    ) {
 2269        if !self.focus_handle.is_focused(window) {
 2270            self.last_focused_descendant = None;
 2271            window.focus(&self.focus_handle);
 2272        }
 2273
 2274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2275        let buffer = &display_map.buffer_snapshot;
 2276        let newest_selection = self.selections.newest_anchor().clone();
 2277        let position = display_map.clip_point(position, Bias::Left);
 2278
 2279        let start;
 2280        let end;
 2281        let mode;
 2282        let mut auto_scroll;
 2283        match click_count {
 2284            1 => {
 2285                start = buffer.anchor_before(position.to_point(&display_map));
 2286                end = start;
 2287                mode = SelectMode::Character;
 2288                auto_scroll = true;
 2289            }
 2290            2 => {
 2291                let range = movement::surrounding_word(&display_map, position);
 2292                start = buffer.anchor_before(range.start.to_point(&display_map));
 2293                end = buffer.anchor_before(range.end.to_point(&display_map));
 2294                mode = SelectMode::Word(start..end);
 2295                auto_scroll = true;
 2296            }
 2297            3 => {
 2298                let position = display_map
 2299                    .clip_point(position, Bias::Left)
 2300                    .to_point(&display_map);
 2301                let line_start = display_map.prev_line_boundary(position).0;
 2302                let next_line_start = buffer.clip_point(
 2303                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2304                    Bias::Left,
 2305                );
 2306                start = buffer.anchor_before(line_start);
 2307                end = buffer.anchor_before(next_line_start);
 2308                mode = SelectMode::Line(start..end);
 2309                auto_scroll = true;
 2310            }
 2311            _ => {
 2312                start = buffer.anchor_before(0);
 2313                end = buffer.anchor_before(buffer.len());
 2314                mode = SelectMode::All;
 2315                auto_scroll = false;
 2316            }
 2317        }
 2318        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2319
 2320        let point_to_delete: Option<usize> = {
 2321            let selected_points: Vec<Selection<Point>> =
 2322                self.selections.disjoint_in_range(start..end, cx);
 2323
 2324            if !add || click_count > 1 {
 2325                None
 2326            } else if !selected_points.is_empty() {
 2327                Some(selected_points[0].id)
 2328            } else {
 2329                let clicked_point_already_selected =
 2330                    self.selections.disjoint.iter().find(|selection| {
 2331                        selection.start.to_point(buffer) == start.to_point(buffer)
 2332                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2333                    });
 2334
 2335                clicked_point_already_selected.map(|selection| selection.id)
 2336            }
 2337        };
 2338
 2339        let selections_count = self.selections.count();
 2340
 2341        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2342            if let Some(point_to_delete) = point_to_delete {
 2343                s.delete(point_to_delete);
 2344
 2345                if selections_count == 1 {
 2346                    s.set_pending_anchor_range(start..end, mode);
 2347                }
 2348            } else {
 2349                if !add {
 2350                    s.clear_disjoint();
 2351                } else if click_count > 1 {
 2352                    s.delete(newest_selection.id)
 2353                }
 2354
 2355                s.set_pending_anchor_range(start..end, mode);
 2356            }
 2357        });
 2358    }
 2359
 2360    fn begin_columnar_selection(
 2361        &mut self,
 2362        position: DisplayPoint,
 2363        goal_column: u32,
 2364        reset: bool,
 2365        window: &mut Window,
 2366        cx: &mut Context<Self>,
 2367    ) {
 2368        if !self.focus_handle.is_focused(window) {
 2369            self.last_focused_descendant = None;
 2370            window.focus(&self.focus_handle);
 2371        }
 2372
 2373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2374
 2375        if reset {
 2376            let pointer_position = display_map
 2377                .buffer_snapshot
 2378                .anchor_before(position.to_point(&display_map));
 2379
 2380            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2381                s.clear_disjoint();
 2382                s.set_pending_anchor_range(
 2383                    pointer_position..pointer_position,
 2384                    SelectMode::Character,
 2385                );
 2386            });
 2387        }
 2388
 2389        let tail = self.selections.newest::<Point>(cx).tail();
 2390        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2391
 2392        if !reset {
 2393            self.select_columns(
 2394                tail.to_display_point(&display_map),
 2395                position,
 2396                goal_column,
 2397                &display_map,
 2398                window,
 2399                cx,
 2400            );
 2401        }
 2402    }
 2403
 2404    fn update_selection(
 2405        &mut self,
 2406        position: DisplayPoint,
 2407        goal_column: u32,
 2408        scroll_delta: gpui::Point<f32>,
 2409        window: &mut Window,
 2410        cx: &mut Context<Self>,
 2411    ) {
 2412        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2413
 2414        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2415            let tail = tail.to_display_point(&display_map);
 2416            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2417        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2418            let buffer = self.buffer.read(cx).snapshot(cx);
 2419            let head;
 2420            let tail;
 2421            let mode = self.selections.pending_mode().unwrap();
 2422            match &mode {
 2423                SelectMode::Character => {
 2424                    head = position.to_point(&display_map);
 2425                    tail = pending.tail().to_point(&buffer);
 2426                }
 2427                SelectMode::Word(original_range) => {
 2428                    let original_display_range = original_range.start.to_display_point(&display_map)
 2429                        ..original_range.end.to_display_point(&display_map);
 2430                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2431                        ..original_display_range.end.to_point(&display_map);
 2432                    if movement::is_inside_word(&display_map, position)
 2433                        || original_display_range.contains(&position)
 2434                    {
 2435                        let word_range = movement::surrounding_word(&display_map, position);
 2436                        if word_range.start < original_display_range.start {
 2437                            head = word_range.start.to_point(&display_map);
 2438                        } else {
 2439                            head = word_range.end.to_point(&display_map);
 2440                        }
 2441                    } else {
 2442                        head = position.to_point(&display_map);
 2443                    }
 2444
 2445                    if head <= original_buffer_range.start {
 2446                        tail = original_buffer_range.end;
 2447                    } else {
 2448                        tail = original_buffer_range.start;
 2449                    }
 2450                }
 2451                SelectMode::Line(original_range) => {
 2452                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2453
 2454                    let position = display_map
 2455                        .clip_point(position, Bias::Left)
 2456                        .to_point(&display_map);
 2457                    let line_start = display_map.prev_line_boundary(position).0;
 2458                    let next_line_start = buffer.clip_point(
 2459                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2460                        Bias::Left,
 2461                    );
 2462
 2463                    if line_start < original_range.start {
 2464                        head = line_start
 2465                    } else {
 2466                        head = next_line_start
 2467                    }
 2468
 2469                    if head <= original_range.start {
 2470                        tail = original_range.end;
 2471                    } else {
 2472                        tail = original_range.start;
 2473                    }
 2474                }
 2475                SelectMode::All => {
 2476                    return;
 2477                }
 2478            };
 2479
 2480            if head < tail {
 2481                pending.start = buffer.anchor_before(head);
 2482                pending.end = buffer.anchor_before(tail);
 2483                pending.reversed = true;
 2484            } else {
 2485                pending.start = buffer.anchor_before(tail);
 2486                pending.end = buffer.anchor_before(head);
 2487                pending.reversed = false;
 2488            }
 2489
 2490            self.change_selections(None, window, cx, |s| {
 2491                s.set_pending(pending, mode);
 2492            });
 2493        } else {
 2494            log::error!("update_selection dispatched with no pending selection");
 2495            return;
 2496        }
 2497
 2498        self.apply_scroll_delta(scroll_delta, window, cx);
 2499        cx.notify();
 2500    }
 2501
 2502    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2503        self.columnar_selection_tail.take();
 2504        if self.selections.pending_anchor().is_some() {
 2505            let selections = self.selections.all::<usize>(cx);
 2506            self.change_selections(None, window, cx, |s| {
 2507                s.select(selections);
 2508                s.clear_pending();
 2509            });
 2510        }
 2511    }
 2512
 2513    fn select_columns(
 2514        &mut self,
 2515        tail: DisplayPoint,
 2516        head: DisplayPoint,
 2517        goal_column: u32,
 2518        display_map: &DisplaySnapshot,
 2519        window: &mut Window,
 2520        cx: &mut Context<Self>,
 2521    ) {
 2522        let start_row = cmp::min(tail.row(), head.row());
 2523        let end_row = cmp::max(tail.row(), head.row());
 2524        let start_column = cmp::min(tail.column(), goal_column);
 2525        let end_column = cmp::max(tail.column(), goal_column);
 2526        let reversed = start_column < tail.column();
 2527
 2528        let selection_ranges = (start_row.0..=end_row.0)
 2529            .map(DisplayRow)
 2530            .filter_map(|row| {
 2531                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2532                    let start = display_map
 2533                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2534                        .to_point(display_map);
 2535                    let end = display_map
 2536                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2537                        .to_point(display_map);
 2538                    if reversed {
 2539                        Some(end..start)
 2540                    } else {
 2541                        Some(start..end)
 2542                    }
 2543                } else {
 2544                    None
 2545                }
 2546            })
 2547            .collect::<Vec<_>>();
 2548
 2549        self.change_selections(None, window, cx, |s| {
 2550            s.select_ranges(selection_ranges);
 2551        });
 2552        cx.notify();
 2553    }
 2554
 2555    pub fn has_pending_nonempty_selection(&self) -> bool {
 2556        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2557            Some(Selection { start, end, .. }) => start != end,
 2558            None => false,
 2559        };
 2560
 2561        pending_nonempty_selection
 2562            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2563    }
 2564
 2565    pub fn has_pending_selection(&self) -> bool {
 2566        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2567    }
 2568
 2569    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2570        self.selection_mark_mode = false;
 2571
 2572        if self.clear_expanded_diff_hunks(cx) {
 2573            cx.notify();
 2574            return;
 2575        }
 2576        if self.dismiss_menus_and_popups(true, window, cx) {
 2577            return;
 2578        }
 2579
 2580        if self.mode == EditorMode::Full
 2581            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2582        {
 2583            return;
 2584        }
 2585
 2586        cx.propagate();
 2587    }
 2588
 2589    pub fn dismiss_menus_and_popups(
 2590        &mut self,
 2591        should_report_inline_completion_event: bool,
 2592        window: &mut Window,
 2593        cx: &mut Context<Self>,
 2594    ) -> bool {
 2595        if self.take_rename(false, window, cx).is_some() {
 2596            return true;
 2597        }
 2598
 2599        if hide_hover(self, cx) {
 2600            return true;
 2601        }
 2602
 2603        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2604            return true;
 2605        }
 2606
 2607        if self.hide_context_menu(window, cx).is_some() {
 2608            return true;
 2609        }
 2610
 2611        if self.mouse_context_menu.take().is_some() {
 2612            return true;
 2613        }
 2614
 2615        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2616            return true;
 2617        }
 2618
 2619        if self.snippet_stack.pop().is_some() {
 2620            return true;
 2621        }
 2622
 2623        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2624            self.dismiss_diagnostics(cx);
 2625            return true;
 2626        }
 2627
 2628        false
 2629    }
 2630
 2631    fn linked_editing_ranges_for(
 2632        &self,
 2633        selection: Range<text::Anchor>,
 2634        cx: &App,
 2635    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2636        if self.linked_edit_ranges.is_empty() {
 2637            return None;
 2638        }
 2639        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2640            selection.end.buffer_id.and_then(|end_buffer_id| {
 2641                if selection.start.buffer_id != Some(end_buffer_id) {
 2642                    return None;
 2643                }
 2644                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2645                let snapshot = buffer.read(cx).snapshot();
 2646                self.linked_edit_ranges
 2647                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2648                    .map(|ranges| (ranges, snapshot, buffer))
 2649            })?;
 2650        use text::ToOffset as TO;
 2651        // find offset from the start of current range to current cursor position
 2652        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2653
 2654        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2655        let start_difference = start_offset - start_byte_offset;
 2656        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2657        let end_difference = end_offset - start_byte_offset;
 2658        // Current range has associated linked ranges.
 2659        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2660        for range in linked_ranges.iter() {
 2661            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2662            let end_offset = start_offset + end_difference;
 2663            let start_offset = start_offset + start_difference;
 2664            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2665                continue;
 2666            }
 2667            if self.selections.disjoint_anchor_ranges().any(|s| {
 2668                if s.start.buffer_id != selection.start.buffer_id
 2669                    || s.end.buffer_id != selection.end.buffer_id
 2670                {
 2671                    return false;
 2672                }
 2673                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2674                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2675            }) {
 2676                continue;
 2677            }
 2678            let start = buffer_snapshot.anchor_after(start_offset);
 2679            let end = buffer_snapshot.anchor_after(end_offset);
 2680            linked_edits
 2681                .entry(buffer.clone())
 2682                .or_default()
 2683                .push(start..end);
 2684        }
 2685        Some(linked_edits)
 2686    }
 2687
 2688    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2689        let text: Arc<str> = text.into();
 2690
 2691        if self.read_only(cx) {
 2692            return;
 2693        }
 2694
 2695        let selections = self.selections.all_adjusted(cx);
 2696        let mut bracket_inserted = false;
 2697        let mut edits = Vec::new();
 2698        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2699        let mut new_selections = Vec::with_capacity(selections.len());
 2700        let mut new_autoclose_regions = Vec::new();
 2701        let snapshot = self.buffer.read(cx).read(cx);
 2702
 2703        for (selection, autoclose_region) in
 2704            self.selections_with_autoclose_regions(selections, &snapshot)
 2705        {
 2706            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2707                // Determine if the inserted text matches the opening or closing
 2708                // bracket of any of this language's bracket pairs.
 2709                let mut bracket_pair = None;
 2710                let mut is_bracket_pair_start = false;
 2711                let mut is_bracket_pair_end = false;
 2712                if !text.is_empty() {
 2713                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2714                    //  and they are removing the character that triggered IME popup.
 2715                    for (pair, enabled) in scope.brackets() {
 2716                        if !pair.close && !pair.surround {
 2717                            continue;
 2718                        }
 2719
 2720                        if enabled && pair.start.ends_with(text.as_ref()) {
 2721                            let prefix_len = pair.start.len() - text.len();
 2722                            let preceding_text_matches_prefix = prefix_len == 0
 2723                                || (selection.start.column >= (prefix_len as u32)
 2724                                    && snapshot.contains_str_at(
 2725                                        Point::new(
 2726                                            selection.start.row,
 2727                                            selection.start.column - (prefix_len as u32),
 2728                                        ),
 2729                                        &pair.start[..prefix_len],
 2730                                    ));
 2731                            if preceding_text_matches_prefix {
 2732                                bracket_pair = Some(pair.clone());
 2733                                is_bracket_pair_start = true;
 2734                                break;
 2735                            }
 2736                        }
 2737                        if pair.end.as_str() == text.as_ref() {
 2738                            bracket_pair = Some(pair.clone());
 2739                            is_bracket_pair_end = true;
 2740                            break;
 2741                        }
 2742                    }
 2743                }
 2744
 2745                if let Some(bracket_pair) = bracket_pair {
 2746                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2747                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2748                    let auto_surround =
 2749                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2750                    if selection.is_empty() {
 2751                        if is_bracket_pair_start {
 2752                            // If the inserted text is a suffix of an opening bracket and the
 2753                            // selection is preceded by the rest of the opening bracket, then
 2754                            // insert the closing bracket.
 2755                            let following_text_allows_autoclose = snapshot
 2756                                .chars_at(selection.start)
 2757                                .next()
 2758                                .map_or(true, |c| scope.should_autoclose_before(c));
 2759
 2760                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2761                                && bracket_pair.start.len() == 1
 2762                            {
 2763                                let target = bracket_pair.start.chars().next().unwrap();
 2764                                let current_line_count = snapshot
 2765                                    .reversed_chars_at(selection.start)
 2766                                    .take_while(|&c| c != '\n')
 2767                                    .filter(|&c| c == target)
 2768                                    .count();
 2769                                current_line_count % 2 == 1
 2770                            } else {
 2771                                false
 2772                            };
 2773
 2774                            if autoclose
 2775                                && bracket_pair.close
 2776                                && following_text_allows_autoclose
 2777                                && !is_closing_quote
 2778                            {
 2779                                let anchor = snapshot.anchor_before(selection.end);
 2780                                new_selections.push((selection.map(|_| anchor), text.len()));
 2781                                new_autoclose_regions.push((
 2782                                    anchor,
 2783                                    text.len(),
 2784                                    selection.id,
 2785                                    bracket_pair.clone(),
 2786                                ));
 2787                                edits.push((
 2788                                    selection.range(),
 2789                                    format!("{}{}", text, bracket_pair.end).into(),
 2790                                ));
 2791                                bracket_inserted = true;
 2792                                continue;
 2793                            }
 2794                        }
 2795
 2796                        if let Some(region) = autoclose_region {
 2797                            // If the selection is followed by an auto-inserted closing bracket,
 2798                            // then don't insert that closing bracket again; just move the selection
 2799                            // past the closing bracket.
 2800                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2801                                && text.as_ref() == region.pair.end.as_str();
 2802                            if should_skip {
 2803                                let anchor = snapshot.anchor_after(selection.end);
 2804                                new_selections
 2805                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2806                                continue;
 2807                            }
 2808                        }
 2809
 2810                        let always_treat_brackets_as_autoclosed = snapshot
 2811                            .settings_at(selection.start, cx)
 2812                            .always_treat_brackets_as_autoclosed;
 2813                        if always_treat_brackets_as_autoclosed
 2814                            && is_bracket_pair_end
 2815                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2816                        {
 2817                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2818                            // and the inserted text is a closing bracket and the selection is followed
 2819                            // by the closing bracket then move the selection past the closing bracket.
 2820                            let anchor = snapshot.anchor_after(selection.end);
 2821                            new_selections.push((selection.map(|_| anchor), text.len()));
 2822                            continue;
 2823                        }
 2824                    }
 2825                    // If an opening bracket is 1 character long and is typed while
 2826                    // text is selected, then surround that text with the bracket pair.
 2827                    else if auto_surround
 2828                        && bracket_pair.surround
 2829                        && is_bracket_pair_start
 2830                        && bracket_pair.start.chars().count() == 1
 2831                    {
 2832                        edits.push((selection.start..selection.start, text.clone()));
 2833                        edits.push((
 2834                            selection.end..selection.end,
 2835                            bracket_pair.end.as_str().into(),
 2836                        ));
 2837                        bracket_inserted = true;
 2838                        new_selections.push((
 2839                            Selection {
 2840                                id: selection.id,
 2841                                start: snapshot.anchor_after(selection.start),
 2842                                end: snapshot.anchor_before(selection.end),
 2843                                reversed: selection.reversed,
 2844                                goal: selection.goal,
 2845                            },
 2846                            0,
 2847                        ));
 2848                        continue;
 2849                    }
 2850                }
 2851            }
 2852
 2853            if self.auto_replace_emoji_shortcode
 2854                && selection.is_empty()
 2855                && text.as_ref().ends_with(':')
 2856            {
 2857                if let Some(possible_emoji_short_code) =
 2858                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2859                {
 2860                    if !possible_emoji_short_code.is_empty() {
 2861                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2862                            let emoji_shortcode_start = Point::new(
 2863                                selection.start.row,
 2864                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2865                            );
 2866
 2867                            // Remove shortcode from buffer
 2868                            edits.push((
 2869                                emoji_shortcode_start..selection.start,
 2870                                "".to_string().into(),
 2871                            ));
 2872                            new_selections.push((
 2873                                Selection {
 2874                                    id: selection.id,
 2875                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2876                                    end: snapshot.anchor_before(selection.start),
 2877                                    reversed: selection.reversed,
 2878                                    goal: selection.goal,
 2879                                },
 2880                                0,
 2881                            ));
 2882
 2883                            // Insert emoji
 2884                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2885                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2886                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2887
 2888                            continue;
 2889                        }
 2890                    }
 2891                }
 2892            }
 2893
 2894            // If not handling any auto-close operation, then just replace the selected
 2895            // text with the given input and move the selection to the end of the
 2896            // newly inserted text.
 2897            let anchor = snapshot.anchor_after(selection.end);
 2898            if !self.linked_edit_ranges.is_empty() {
 2899                let start_anchor = snapshot.anchor_before(selection.start);
 2900
 2901                let is_word_char = text.chars().next().map_or(true, |char| {
 2902                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2903                    classifier.is_word(char)
 2904                });
 2905
 2906                if is_word_char {
 2907                    if let Some(ranges) = self
 2908                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2909                    {
 2910                        for (buffer, edits) in ranges {
 2911                            linked_edits
 2912                                .entry(buffer.clone())
 2913                                .or_default()
 2914                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2915                        }
 2916                    }
 2917                }
 2918            }
 2919
 2920            new_selections.push((selection.map(|_| anchor), 0));
 2921            edits.push((selection.start..selection.end, text.clone()));
 2922        }
 2923
 2924        drop(snapshot);
 2925
 2926        self.transact(window, cx, |this, window, cx| {
 2927            this.buffer.update(cx, |buffer, cx| {
 2928                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2929            });
 2930            for (buffer, edits) in linked_edits {
 2931                buffer.update(cx, |buffer, cx| {
 2932                    let snapshot = buffer.snapshot();
 2933                    let edits = edits
 2934                        .into_iter()
 2935                        .map(|(range, text)| {
 2936                            use text::ToPoint as TP;
 2937                            let end_point = TP::to_point(&range.end, &snapshot);
 2938                            let start_point = TP::to_point(&range.start, &snapshot);
 2939                            (start_point..end_point, text)
 2940                        })
 2941                        .sorted_by_key(|(range, _)| range.start)
 2942                        .collect::<Vec<_>>();
 2943                    buffer.edit(edits, None, cx);
 2944                })
 2945            }
 2946            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2947            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2948            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2949            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2950                .zip(new_selection_deltas)
 2951                .map(|(selection, delta)| Selection {
 2952                    id: selection.id,
 2953                    start: selection.start + delta,
 2954                    end: selection.end + delta,
 2955                    reversed: selection.reversed,
 2956                    goal: SelectionGoal::None,
 2957                })
 2958                .collect::<Vec<_>>();
 2959
 2960            let mut i = 0;
 2961            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2962                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2963                let start = map.buffer_snapshot.anchor_before(position);
 2964                let end = map.buffer_snapshot.anchor_after(position);
 2965                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2966                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2967                        Ordering::Less => i += 1,
 2968                        Ordering::Greater => break,
 2969                        Ordering::Equal => {
 2970                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2971                                Ordering::Less => i += 1,
 2972                                Ordering::Equal => break,
 2973                                Ordering::Greater => break,
 2974                            }
 2975                        }
 2976                    }
 2977                }
 2978                this.autoclose_regions.insert(
 2979                    i,
 2980                    AutocloseRegion {
 2981                        selection_id,
 2982                        range: start..end,
 2983                        pair,
 2984                    },
 2985                );
 2986            }
 2987
 2988            let had_active_inline_completion = this.has_active_inline_completion();
 2989            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2990                s.select(new_selections)
 2991            });
 2992
 2993            if !bracket_inserted {
 2994                if let Some(on_type_format_task) =
 2995                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2996                {
 2997                    on_type_format_task.detach_and_log_err(cx);
 2998                }
 2999            }
 3000
 3001            let editor_settings = EditorSettings::get_global(cx);
 3002            if bracket_inserted
 3003                && (editor_settings.auto_signature_help
 3004                    || editor_settings.show_signature_help_after_edits)
 3005            {
 3006                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3007            }
 3008
 3009            let trigger_in_words =
 3010                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3011            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3012            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3013            this.refresh_inline_completion(true, false, window, cx);
 3014        });
 3015    }
 3016
 3017    fn find_possible_emoji_shortcode_at_position(
 3018        snapshot: &MultiBufferSnapshot,
 3019        position: Point,
 3020    ) -> Option<String> {
 3021        let mut chars = Vec::new();
 3022        let mut found_colon = false;
 3023        for char in snapshot.reversed_chars_at(position).take(100) {
 3024            // Found a possible emoji shortcode in the middle of the buffer
 3025            if found_colon {
 3026                if char.is_whitespace() {
 3027                    chars.reverse();
 3028                    return Some(chars.iter().collect());
 3029                }
 3030                // If the previous character is not a whitespace, we are in the middle of a word
 3031                // and we only want to complete the shortcode if the word is made up of other emojis
 3032                let mut containing_word = String::new();
 3033                for ch in snapshot
 3034                    .reversed_chars_at(position)
 3035                    .skip(chars.len() + 1)
 3036                    .take(100)
 3037                {
 3038                    if ch.is_whitespace() {
 3039                        break;
 3040                    }
 3041                    containing_word.push(ch);
 3042                }
 3043                let containing_word = containing_word.chars().rev().collect::<String>();
 3044                if util::word_consists_of_emojis(containing_word.as_str()) {
 3045                    chars.reverse();
 3046                    return Some(chars.iter().collect());
 3047                }
 3048            }
 3049
 3050            if char.is_whitespace() || !char.is_ascii() {
 3051                return None;
 3052            }
 3053            if char == ':' {
 3054                found_colon = true;
 3055            } else {
 3056                chars.push(char);
 3057            }
 3058        }
 3059        // Found a possible emoji shortcode at the beginning of the buffer
 3060        chars.reverse();
 3061        Some(chars.iter().collect())
 3062    }
 3063
 3064    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3065        self.transact(window, cx, |this, window, cx| {
 3066            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3067                let selections = this.selections.all::<usize>(cx);
 3068                let multi_buffer = this.buffer.read(cx);
 3069                let buffer = multi_buffer.snapshot(cx);
 3070                selections
 3071                    .iter()
 3072                    .map(|selection| {
 3073                        let start_point = selection.start.to_point(&buffer);
 3074                        let mut indent =
 3075                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3076                        indent.len = cmp::min(indent.len, start_point.column);
 3077                        let start = selection.start;
 3078                        let end = selection.end;
 3079                        let selection_is_empty = start == end;
 3080                        let language_scope = buffer.language_scope_at(start);
 3081                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3082                            &language_scope
 3083                        {
 3084                            let leading_whitespace_len = buffer
 3085                                .reversed_chars_at(start)
 3086                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3087                                .map(|c| c.len_utf8())
 3088                                .sum::<usize>();
 3089
 3090                            let trailing_whitespace_len = buffer
 3091                                .chars_at(end)
 3092                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3093                                .map(|c| c.len_utf8())
 3094                                .sum::<usize>();
 3095
 3096                            let insert_extra_newline =
 3097                                language.brackets().any(|(pair, enabled)| {
 3098                                    let pair_start = pair.start.trim_end();
 3099                                    let pair_end = pair.end.trim_start();
 3100
 3101                                    enabled
 3102                                        && pair.newline
 3103                                        && buffer.contains_str_at(
 3104                                            end + trailing_whitespace_len,
 3105                                            pair_end,
 3106                                        )
 3107                                        && buffer.contains_str_at(
 3108                                            (start - leading_whitespace_len)
 3109                                                .saturating_sub(pair_start.len()),
 3110                                            pair_start,
 3111                                        )
 3112                                });
 3113
 3114                            // Comment extension on newline is allowed only for cursor selections
 3115                            let comment_delimiter = maybe!({
 3116                                if !selection_is_empty {
 3117                                    return None;
 3118                                }
 3119
 3120                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3121                                    return None;
 3122                                }
 3123
 3124                                let delimiters = language.line_comment_prefixes();
 3125                                let max_len_of_delimiter =
 3126                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3127                                let (snapshot, range) =
 3128                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3129
 3130                                let mut index_of_first_non_whitespace = 0;
 3131                                let comment_candidate = snapshot
 3132                                    .chars_for_range(range)
 3133                                    .skip_while(|c| {
 3134                                        let should_skip = c.is_whitespace();
 3135                                        if should_skip {
 3136                                            index_of_first_non_whitespace += 1;
 3137                                        }
 3138                                        should_skip
 3139                                    })
 3140                                    .take(max_len_of_delimiter)
 3141                                    .collect::<String>();
 3142                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3143                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3144                                })?;
 3145                                let cursor_is_placed_after_comment_marker =
 3146                                    index_of_first_non_whitespace + comment_prefix.len()
 3147                                        <= start_point.column as usize;
 3148                                if cursor_is_placed_after_comment_marker {
 3149                                    Some(comment_prefix.clone())
 3150                                } else {
 3151                                    None
 3152                                }
 3153                            });
 3154                            (comment_delimiter, insert_extra_newline)
 3155                        } else {
 3156                            (None, false)
 3157                        };
 3158
 3159                        let capacity_for_delimiter = comment_delimiter
 3160                            .as_deref()
 3161                            .map(str::len)
 3162                            .unwrap_or_default();
 3163                        let mut new_text =
 3164                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3165                        new_text.push('\n');
 3166                        new_text.extend(indent.chars());
 3167                        if let Some(delimiter) = &comment_delimiter {
 3168                            new_text.push_str(delimiter);
 3169                        }
 3170                        if insert_extra_newline {
 3171                            new_text = new_text.repeat(2);
 3172                        }
 3173
 3174                        let anchor = buffer.anchor_after(end);
 3175                        let new_selection = selection.map(|_| anchor);
 3176                        (
 3177                            (start..end, new_text),
 3178                            (insert_extra_newline, new_selection),
 3179                        )
 3180                    })
 3181                    .unzip()
 3182            };
 3183
 3184            this.edit_with_autoindent(edits, cx);
 3185            let buffer = this.buffer.read(cx).snapshot(cx);
 3186            let new_selections = selection_fixup_info
 3187                .into_iter()
 3188                .map(|(extra_newline_inserted, new_selection)| {
 3189                    let mut cursor = new_selection.end.to_point(&buffer);
 3190                    if extra_newline_inserted {
 3191                        cursor.row -= 1;
 3192                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3193                    }
 3194                    new_selection.map(|_| cursor)
 3195                })
 3196                .collect();
 3197
 3198            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3199                s.select(new_selections)
 3200            });
 3201            this.refresh_inline_completion(true, false, window, cx);
 3202        });
 3203    }
 3204
 3205    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3206        let buffer = self.buffer.read(cx);
 3207        let snapshot = buffer.snapshot(cx);
 3208
 3209        let mut edits = Vec::new();
 3210        let mut rows = Vec::new();
 3211
 3212        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3213            let cursor = selection.head();
 3214            let row = cursor.row;
 3215
 3216            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3217
 3218            let newline = "\n".to_string();
 3219            edits.push((start_of_line..start_of_line, newline));
 3220
 3221            rows.push(row + rows_inserted as u32);
 3222        }
 3223
 3224        self.transact(window, cx, |editor, window, cx| {
 3225            editor.edit(edits, cx);
 3226
 3227            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3228                let mut index = 0;
 3229                s.move_cursors_with(|map, _, _| {
 3230                    let row = rows[index];
 3231                    index += 1;
 3232
 3233                    let point = Point::new(row, 0);
 3234                    let boundary = map.next_line_boundary(point).1;
 3235                    let clipped = map.clip_point(boundary, Bias::Left);
 3236
 3237                    (clipped, SelectionGoal::None)
 3238                });
 3239            });
 3240
 3241            let mut indent_edits = Vec::new();
 3242            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3243            for row in rows {
 3244                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3245                for (row, indent) in indents {
 3246                    if indent.len == 0 {
 3247                        continue;
 3248                    }
 3249
 3250                    let text = match indent.kind {
 3251                        IndentKind::Space => " ".repeat(indent.len as usize),
 3252                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3253                    };
 3254                    let point = Point::new(row.0, 0);
 3255                    indent_edits.push((point..point, text));
 3256                }
 3257            }
 3258            editor.edit(indent_edits, cx);
 3259        });
 3260    }
 3261
 3262    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3263        let buffer = self.buffer.read(cx);
 3264        let snapshot = buffer.snapshot(cx);
 3265
 3266        let mut edits = Vec::new();
 3267        let mut rows = Vec::new();
 3268        let mut rows_inserted = 0;
 3269
 3270        for selection in self.selections.all_adjusted(cx) {
 3271            let cursor = selection.head();
 3272            let row = cursor.row;
 3273
 3274            let point = Point::new(row + 1, 0);
 3275            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3276
 3277            let newline = "\n".to_string();
 3278            edits.push((start_of_line..start_of_line, newline));
 3279
 3280            rows_inserted += 1;
 3281            rows.push(row + rows_inserted);
 3282        }
 3283
 3284        self.transact(window, cx, |editor, window, cx| {
 3285            editor.edit(edits, cx);
 3286
 3287            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3288                let mut index = 0;
 3289                s.move_cursors_with(|map, _, _| {
 3290                    let row = rows[index];
 3291                    index += 1;
 3292
 3293                    let point = Point::new(row, 0);
 3294                    let boundary = map.next_line_boundary(point).1;
 3295                    let clipped = map.clip_point(boundary, Bias::Left);
 3296
 3297                    (clipped, SelectionGoal::None)
 3298                });
 3299            });
 3300
 3301            let mut indent_edits = Vec::new();
 3302            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3303            for row in rows {
 3304                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3305                for (row, indent) in indents {
 3306                    if indent.len == 0 {
 3307                        continue;
 3308                    }
 3309
 3310                    let text = match indent.kind {
 3311                        IndentKind::Space => " ".repeat(indent.len as usize),
 3312                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3313                    };
 3314                    let point = Point::new(row.0, 0);
 3315                    indent_edits.push((point..point, text));
 3316                }
 3317            }
 3318            editor.edit(indent_edits, cx);
 3319        });
 3320    }
 3321
 3322    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3323        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3324            original_indent_columns: Vec::new(),
 3325        });
 3326        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3327    }
 3328
 3329    fn insert_with_autoindent_mode(
 3330        &mut self,
 3331        text: &str,
 3332        autoindent_mode: Option<AutoindentMode>,
 3333        window: &mut Window,
 3334        cx: &mut Context<Self>,
 3335    ) {
 3336        if self.read_only(cx) {
 3337            return;
 3338        }
 3339
 3340        let text: Arc<str> = text.into();
 3341        self.transact(window, cx, |this, window, cx| {
 3342            let old_selections = this.selections.all_adjusted(cx);
 3343            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3344                let anchors = {
 3345                    let snapshot = buffer.read(cx);
 3346                    old_selections
 3347                        .iter()
 3348                        .map(|s| {
 3349                            let anchor = snapshot.anchor_after(s.head());
 3350                            s.map(|_| anchor)
 3351                        })
 3352                        .collect::<Vec<_>>()
 3353                };
 3354                buffer.edit(
 3355                    old_selections
 3356                        .iter()
 3357                        .map(|s| (s.start..s.end, text.clone())),
 3358                    autoindent_mode,
 3359                    cx,
 3360                );
 3361                anchors
 3362            });
 3363
 3364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3365                s.select_anchors(selection_anchors);
 3366            });
 3367
 3368            cx.notify();
 3369        });
 3370    }
 3371
 3372    fn trigger_completion_on_input(
 3373        &mut self,
 3374        text: &str,
 3375        trigger_in_words: bool,
 3376        window: &mut Window,
 3377        cx: &mut Context<Self>,
 3378    ) {
 3379        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3380            self.show_completions(
 3381                &ShowCompletions {
 3382                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3383                },
 3384                window,
 3385                cx,
 3386            );
 3387        } else {
 3388            self.hide_context_menu(window, cx);
 3389        }
 3390    }
 3391
 3392    fn is_completion_trigger(
 3393        &self,
 3394        text: &str,
 3395        trigger_in_words: bool,
 3396        cx: &mut Context<Self>,
 3397    ) -> bool {
 3398        let position = self.selections.newest_anchor().head();
 3399        let multibuffer = self.buffer.read(cx);
 3400        let Some(buffer) = position
 3401            .buffer_id
 3402            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3403        else {
 3404            return false;
 3405        };
 3406
 3407        if let Some(completion_provider) = &self.completion_provider {
 3408            completion_provider.is_completion_trigger(
 3409                &buffer,
 3410                position.text_anchor,
 3411                text,
 3412                trigger_in_words,
 3413                cx,
 3414            )
 3415        } else {
 3416            false
 3417        }
 3418    }
 3419
 3420    /// If any empty selections is touching the start of its innermost containing autoclose
 3421    /// region, expand it to select the brackets.
 3422    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3423        let selections = self.selections.all::<usize>(cx);
 3424        let buffer = self.buffer.read(cx).read(cx);
 3425        let new_selections = self
 3426            .selections_with_autoclose_regions(selections, &buffer)
 3427            .map(|(mut selection, region)| {
 3428                if !selection.is_empty() {
 3429                    return selection;
 3430                }
 3431
 3432                if let Some(region) = region {
 3433                    let mut range = region.range.to_offset(&buffer);
 3434                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3435                        range.start -= region.pair.start.len();
 3436                        if buffer.contains_str_at(range.start, &region.pair.start)
 3437                            && buffer.contains_str_at(range.end, &region.pair.end)
 3438                        {
 3439                            range.end += region.pair.end.len();
 3440                            selection.start = range.start;
 3441                            selection.end = range.end;
 3442
 3443                            return selection;
 3444                        }
 3445                    }
 3446                }
 3447
 3448                let always_treat_brackets_as_autoclosed = buffer
 3449                    .settings_at(selection.start, cx)
 3450                    .always_treat_brackets_as_autoclosed;
 3451
 3452                if !always_treat_brackets_as_autoclosed {
 3453                    return selection;
 3454                }
 3455
 3456                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3457                    for (pair, enabled) in scope.brackets() {
 3458                        if !enabled || !pair.close {
 3459                            continue;
 3460                        }
 3461
 3462                        if buffer.contains_str_at(selection.start, &pair.end) {
 3463                            let pair_start_len = pair.start.len();
 3464                            if buffer.contains_str_at(
 3465                                selection.start.saturating_sub(pair_start_len),
 3466                                &pair.start,
 3467                            ) {
 3468                                selection.start -= pair_start_len;
 3469                                selection.end += pair.end.len();
 3470
 3471                                return selection;
 3472                            }
 3473                        }
 3474                    }
 3475                }
 3476
 3477                selection
 3478            })
 3479            .collect();
 3480
 3481        drop(buffer);
 3482        self.change_selections(None, window, cx, |selections| {
 3483            selections.select(new_selections)
 3484        });
 3485    }
 3486
 3487    /// Iterate the given selections, and for each one, find the smallest surrounding
 3488    /// autoclose region. This uses the ordering of the selections and the autoclose
 3489    /// regions to avoid repeated comparisons.
 3490    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3491        &'a self,
 3492        selections: impl IntoIterator<Item = Selection<D>>,
 3493        buffer: &'a MultiBufferSnapshot,
 3494    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3495        let mut i = 0;
 3496        let mut regions = self.autoclose_regions.as_slice();
 3497        selections.into_iter().map(move |selection| {
 3498            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3499
 3500            let mut enclosing = None;
 3501            while let Some(pair_state) = regions.get(i) {
 3502                if pair_state.range.end.to_offset(buffer) < range.start {
 3503                    regions = &regions[i + 1..];
 3504                    i = 0;
 3505                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3506                    break;
 3507                } else {
 3508                    if pair_state.selection_id == selection.id {
 3509                        enclosing = Some(pair_state);
 3510                    }
 3511                    i += 1;
 3512                }
 3513            }
 3514
 3515            (selection, enclosing)
 3516        })
 3517    }
 3518
 3519    /// Remove any autoclose regions that no longer contain their selection.
 3520    fn invalidate_autoclose_regions(
 3521        &mut self,
 3522        mut selections: &[Selection<Anchor>],
 3523        buffer: &MultiBufferSnapshot,
 3524    ) {
 3525        self.autoclose_regions.retain(|state| {
 3526            let mut i = 0;
 3527            while let Some(selection) = selections.get(i) {
 3528                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3529                    selections = &selections[1..];
 3530                    continue;
 3531                }
 3532                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3533                    break;
 3534                }
 3535                if selection.id == state.selection_id {
 3536                    return true;
 3537                } else {
 3538                    i += 1;
 3539                }
 3540            }
 3541            false
 3542        });
 3543    }
 3544
 3545    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3546        let offset = position.to_offset(buffer);
 3547        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3548        if offset > word_range.start && kind == Some(CharKind::Word) {
 3549            Some(
 3550                buffer
 3551                    .text_for_range(word_range.start..offset)
 3552                    .collect::<String>(),
 3553            )
 3554        } else {
 3555            None
 3556        }
 3557    }
 3558
 3559    pub fn toggle_inlay_hints(
 3560        &mut self,
 3561        _: &ToggleInlayHints,
 3562        _: &mut Window,
 3563        cx: &mut Context<Self>,
 3564    ) {
 3565        self.refresh_inlay_hints(
 3566            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3567            cx,
 3568        );
 3569    }
 3570
 3571    pub fn inlay_hints_enabled(&self) -> bool {
 3572        self.inlay_hint_cache.enabled
 3573    }
 3574
 3575    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3576        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3577            return;
 3578        }
 3579
 3580        let reason_description = reason.description();
 3581        let ignore_debounce = matches!(
 3582            reason,
 3583            InlayHintRefreshReason::SettingsChange(_)
 3584                | InlayHintRefreshReason::Toggle(_)
 3585                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3586        );
 3587        let (invalidate_cache, required_languages) = match reason {
 3588            InlayHintRefreshReason::Toggle(enabled) => {
 3589                self.inlay_hint_cache.enabled = enabled;
 3590                if enabled {
 3591                    (InvalidationStrategy::RefreshRequested, None)
 3592                } else {
 3593                    self.inlay_hint_cache.clear();
 3594                    self.splice_inlays(
 3595                        &self
 3596                            .visible_inlay_hints(cx)
 3597                            .iter()
 3598                            .map(|inlay| inlay.id)
 3599                            .collect::<Vec<InlayId>>(),
 3600                        Vec::new(),
 3601                        cx,
 3602                    );
 3603                    return;
 3604                }
 3605            }
 3606            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3607                match self.inlay_hint_cache.update_settings(
 3608                    &self.buffer,
 3609                    new_settings,
 3610                    self.visible_inlay_hints(cx),
 3611                    cx,
 3612                ) {
 3613                    ControlFlow::Break(Some(InlaySplice {
 3614                        to_remove,
 3615                        to_insert,
 3616                    })) => {
 3617                        self.splice_inlays(&to_remove, to_insert, cx);
 3618                        return;
 3619                    }
 3620                    ControlFlow::Break(None) => return,
 3621                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3622                }
 3623            }
 3624            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3625                if let Some(InlaySplice {
 3626                    to_remove,
 3627                    to_insert,
 3628                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3629                {
 3630                    self.splice_inlays(&to_remove, to_insert, cx);
 3631                }
 3632                return;
 3633            }
 3634            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3635            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3636                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3637            }
 3638            InlayHintRefreshReason::RefreshRequested => {
 3639                (InvalidationStrategy::RefreshRequested, None)
 3640            }
 3641        };
 3642
 3643        if let Some(InlaySplice {
 3644            to_remove,
 3645            to_insert,
 3646        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3647            reason_description,
 3648            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3649            invalidate_cache,
 3650            ignore_debounce,
 3651            cx,
 3652        ) {
 3653            self.splice_inlays(&to_remove, to_insert, cx);
 3654        }
 3655    }
 3656
 3657    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3658        self.display_map
 3659            .read(cx)
 3660            .current_inlays()
 3661            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3662            .cloned()
 3663            .collect()
 3664    }
 3665
 3666    pub fn excerpts_for_inlay_hints_query(
 3667        &self,
 3668        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3669        cx: &mut Context<Editor>,
 3670    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3671        let Some(project) = self.project.as_ref() else {
 3672            return HashMap::default();
 3673        };
 3674        let project = project.read(cx);
 3675        let multi_buffer = self.buffer().read(cx);
 3676        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3677        let multi_buffer_visible_start = self
 3678            .scroll_manager
 3679            .anchor()
 3680            .anchor
 3681            .to_point(&multi_buffer_snapshot);
 3682        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3683            multi_buffer_visible_start
 3684                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3685            Bias::Left,
 3686        );
 3687        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3688        multi_buffer_snapshot
 3689            .range_to_buffer_ranges(multi_buffer_visible_range)
 3690            .into_iter()
 3691            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3692            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3693                let buffer_file = project::File::from_dyn(buffer.file())?;
 3694                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3695                let worktree_entry = buffer_worktree
 3696                    .read(cx)
 3697                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3698                if worktree_entry.is_ignored {
 3699                    return None;
 3700                }
 3701
 3702                let language = buffer.language()?;
 3703                if let Some(restrict_to_languages) = restrict_to_languages {
 3704                    if !restrict_to_languages.contains(language) {
 3705                        return None;
 3706                    }
 3707                }
 3708                Some((
 3709                    excerpt_id,
 3710                    (
 3711                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3712                        buffer.version().clone(),
 3713                        excerpt_visible_range,
 3714                    ),
 3715                ))
 3716            })
 3717            .collect()
 3718    }
 3719
 3720    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3721        TextLayoutDetails {
 3722            text_system: window.text_system().clone(),
 3723            editor_style: self.style.clone().unwrap(),
 3724            rem_size: window.rem_size(),
 3725            scroll_anchor: self.scroll_manager.anchor(),
 3726            visible_rows: self.visible_line_count(),
 3727            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3728        }
 3729    }
 3730
 3731    pub fn splice_inlays(
 3732        &self,
 3733        to_remove: &[InlayId],
 3734        to_insert: Vec<Inlay>,
 3735        cx: &mut Context<Self>,
 3736    ) {
 3737        self.display_map.update(cx, |display_map, cx| {
 3738            display_map.splice_inlays(to_remove, to_insert, cx)
 3739        });
 3740        cx.notify();
 3741    }
 3742
 3743    fn trigger_on_type_formatting(
 3744        &self,
 3745        input: String,
 3746        window: &mut Window,
 3747        cx: &mut Context<Self>,
 3748    ) -> Option<Task<Result<()>>> {
 3749        if input.len() != 1 {
 3750            return None;
 3751        }
 3752
 3753        let project = self.project.as_ref()?;
 3754        let position = self.selections.newest_anchor().head();
 3755        let (buffer, buffer_position) = self
 3756            .buffer
 3757            .read(cx)
 3758            .text_anchor_for_position(position, cx)?;
 3759
 3760        let settings = language_settings::language_settings(
 3761            buffer
 3762                .read(cx)
 3763                .language_at(buffer_position)
 3764                .map(|l| l.name()),
 3765            buffer.read(cx).file(),
 3766            cx,
 3767        );
 3768        if !settings.use_on_type_format {
 3769            return None;
 3770        }
 3771
 3772        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3773        // hence we do LSP request & edit on host side only — add formats to host's history.
 3774        let push_to_lsp_host_history = true;
 3775        // If this is not the host, append its history with new edits.
 3776        let push_to_client_history = project.read(cx).is_via_collab();
 3777
 3778        let on_type_formatting = project.update(cx, |project, cx| {
 3779            project.on_type_format(
 3780                buffer.clone(),
 3781                buffer_position,
 3782                input,
 3783                push_to_lsp_host_history,
 3784                cx,
 3785            )
 3786        });
 3787        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3788            if let Some(transaction) = on_type_formatting.await? {
 3789                if push_to_client_history {
 3790                    buffer
 3791                        .update(&mut cx, |buffer, _| {
 3792                            buffer.push_transaction(transaction, Instant::now());
 3793                        })
 3794                        .ok();
 3795                }
 3796                editor.update(&mut cx, |editor, cx| {
 3797                    editor.refresh_document_highlights(cx);
 3798                })?;
 3799            }
 3800            Ok(())
 3801        }))
 3802    }
 3803
 3804    pub fn show_completions(
 3805        &mut self,
 3806        options: &ShowCompletions,
 3807        window: &mut Window,
 3808        cx: &mut Context<Self>,
 3809    ) {
 3810        if self.pending_rename.is_some() {
 3811            return;
 3812        }
 3813
 3814        let Some(provider) = self.completion_provider.as_ref() else {
 3815            return;
 3816        };
 3817
 3818        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3819            return;
 3820        }
 3821
 3822        let position = self.selections.newest_anchor().head();
 3823        if position.diff_base_anchor.is_some() {
 3824            return;
 3825        }
 3826        let (buffer, buffer_position) =
 3827            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3828                output
 3829            } else {
 3830                return;
 3831            };
 3832        let show_completion_documentation = buffer
 3833            .read(cx)
 3834            .snapshot()
 3835            .settings_at(buffer_position, cx)
 3836            .show_completion_documentation;
 3837
 3838        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3839
 3840        let trigger_kind = match &options.trigger {
 3841            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3842                CompletionTriggerKind::TRIGGER_CHARACTER
 3843            }
 3844            _ => CompletionTriggerKind::INVOKED,
 3845        };
 3846        let completion_context = CompletionContext {
 3847            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3848                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3849                    Some(String::from(trigger))
 3850                } else {
 3851                    None
 3852                }
 3853            }),
 3854            trigger_kind,
 3855        };
 3856        let completions =
 3857            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3858        let sort_completions = provider.sort_completions();
 3859
 3860        let id = post_inc(&mut self.next_completion_id);
 3861        let task = cx.spawn_in(window, |editor, mut cx| {
 3862            async move {
 3863                editor.update(&mut cx, |this, _| {
 3864                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3865                })?;
 3866                let completions = completions.await.log_err();
 3867                let menu = if let Some(completions) = completions {
 3868                    let mut menu = CompletionsMenu::new(
 3869                        id,
 3870                        sort_completions,
 3871                        show_completion_documentation,
 3872                        position,
 3873                        buffer.clone(),
 3874                        completions.into(),
 3875                    );
 3876
 3877                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3878                        .await;
 3879
 3880                    menu.visible().then_some(menu)
 3881                } else {
 3882                    None
 3883                };
 3884
 3885                editor.update_in(&mut cx, |editor, window, cx| {
 3886                    match editor.context_menu.borrow().as_ref() {
 3887                        None => {}
 3888                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3889                            if prev_menu.id > id {
 3890                                return;
 3891                            }
 3892                        }
 3893                        _ => return,
 3894                    }
 3895
 3896                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3897                        let mut menu = menu.unwrap();
 3898                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3899
 3900                        *editor.context_menu.borrow_mut() =
 3901                            Some(CodeContextMenu::Completions(menu));
 3902
 3903                        if editor.show_inline_completions_in_menu(cx) {
 3904                            editor.update_visible_inline_completion(window, cx);
 3905                        } else {
 3906                            editor.discard_inline_completion(false, cx);
 3907                        }
 3908
 3909                        cx.notify();
 3910                    } else if editor.completion_tasks.len() <= 1 {
 3911                        // If there are no more completion tasks and the last menu was
 3912                        // empty, we should hide it.
 3913                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3914                        // If it was already hidden and we don't show inline
 3915                        // completions in the menu, we should also show the
 3916                        // inline-completion when available.
 3917                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3918                            editor.update_visible_inline_completion(window, cx);
 3919                        }
 3920                    }
 3921                })?;
 3922
 3923                Ok::<_, anyhow::Error>(())
 3924            }
 3925            .log_err()
 3926        });
 3927
 3928        self.completion_tasks.push((id, task));
 3929    }
 3930
 3931    pub fn confirm_completion(
 3932        &mut self,
 3933        action: &ConfirmCompletion,
 3934        window: &mut Window,
 3935        cx: &mut Context<Self>,
 3936    ) -> Option<Task<Result<()>>> {
 3937        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3938    }
 3939
 3940    pub fn compose_completion(
 3941        &mut self,
 3942        action: &ComposeCompletion,
 3943        window: &mut Window,
 3944        cx: &mut Context<Self>,
 3945    ) -> Option<Task<Result<()>>> {
 3946        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3947    }
 3948
 3949    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3950        window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
 3951    }
 3952
 3953    fn do_completion(
 3954        &mut self,
 3955        item_ix: Option<usize>,
 3956        intent: CompletionIntent,
 3957        window: &mut Window,
 3958        cx: &mut Context<Editor>,
 3959    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3960        use language::ToOffset as _;
 3961
 3962        let completions_menu =
 3963            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3964                menu
 3965            } else {
 3966                return None;
 3967            };
 3968
 3969        let entries = completions_menu.entries.borrow();
 3970        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3971        if self.show_inline_completions_in_menu(cx) {
 3972            self.discard_inline_completion(true, cx);
 3973        }
 3974        let candidate_id = mat.candidate_id;
 3975        drop(entries);
 3976
 3977        let buffer_handle = completions_menu.buffer;
 3978        let completion = completions_menu
 3979            .completions
 3980            .borrow()
 3981            .get(candidate_id)?
 3982            .clone();
 3983        cx.stop_propagation();
 3984
 3985        let snippet;
 3986        let text;
 3987
 3988        if completion.is_snippet() {
 3989            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3990            text = snippet.as_ref().unwrap().text.clone();
 3991        } else {
 3992            snippet = None;
 3993            text = completion.new_text.clone();
 3994        };
 3995        let selections = self.selections.all::<usize>(cx);
 3996        let buffer = buffer_handle.read(cx);
 3997        let old_range = completion.old_range.to_offset(buffer);
 3998        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3999
 4000        let newest_selection = self.selections.newest_anchor();
 4001        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4002            return None;
 4003        }
 4004
 4005        let lookbehind = newest_selection
 4006            .start
 4007            .text_anchor
 4008            .to_offset(buffer)
 4009            .saturating_sub(old_range.start);
 4010        let lookahead = old_range
 4011            .end
 4012            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4013        let mut common_prefix_len = old_text
 4014            .bytes()
 4015            .zip(text.bytes())
 4016            .take_while(|(a, b)| a == b)
 4017            .count();
 4018
 4019        let snapshot = self.buffer.read(cx).snapshot(cx);
 4020        let mut range_to_replace: Option<Range<isize>> = None;
 4021        let mut ranges = Vec::new();
 4022        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4023        for selection in &selections {
 4024            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4025                let start = selection.start.saturating_sub(lookbehind);
 4026                let end = selection.end + lookahead;
 4027                if selection.id == newest_selection.id {
 4028                    range_to_replace = Some(
 4029                        ((start + common_prefix_len) as isize - selection.start as isize)
 4030                            ..(end as isize - selection.start as isize),
 4031                    );
 4032                }
 4033                ranges.push(start + common_prefix_len..end);
 4034            } else {
 4035                common_prefix_len = 0;
 4036                ranges.clear();
 4037                ranges.extend(selections.iter().map(|s| {
 4038                    if s.id == newest_selection.id {
 4039                        range_to_replace = Some(
 4040                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4041                                - selection.start as isize
 4042                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4043                                    - selection.start as isize,
 4044                        );
 4045                        old_range.clone()
 4046                    } else {
 4047                        s.start..s.end
 4048                    }
 4049                }));
 4050                break;
 4051            }
 4052            if !self.linked_edit_ranges.is_empty() {
 4053                let start_anchor = snapshot.anchor_before(selection.head());
 4054                let end_anchor = snapshot.anchor_after(selection.tail());
 4055                if let Some(ranges) = self
 4056                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4057                {
 4058                    for (buffer, edits) in ranges {
 4059                        linked_edits.entry(buffer.clone()).or_default().extend(
 4060                            edits
 4061                                .into_iter()
 4062                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4063                        );
 4064                    }
 4065                }
 4066            }
 4067        }
 4068        let text = &text[common_prefix_len..];
 4069
 4070        cx.emit(EditorEvent::InputHandled {
 4071            utf16_range_to_replace: range_to_replace,
 4072            text: text.into(),
 4073        });
 4074
 4075        self.transact(window, cx, |this, window, cx| {
 4076            if let Some(mut snippet) = snippet {
 4077                snippet.text = text.to_string();
 4078                for tabstop in snippet
 4079                    .tabstops
 4080                    .iter_mut()
 4081                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4082                {
 4083                    tabstop.start -= common_prefix_len as isize;
 4084                    tabstop.end -= common_prefix_len as isize;
 4085                }
 4086
 4087                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4088            } else {
 4089                this.buffer.update(cx, |buffer, cx| {
 4090                    buffer.edit(
 4091                        ranges.iter().map(|range| (range.clone(), text)),
 4092                        this.autoindent_mode.clone(),
 4093                        cx,
 4094                    );
 4095                });
 4096            }
 4097            for (buffer, edits) in linked_edits {
 4098                buffer.update(cx, |buffer, cx| {
 4099                    let snapshot = buffer.snapshot();
 4100                    let edits = edits
 4101                        .into_iter()
 4102                        .map(|(range, text)| {
 4103                            use text::ToPoint as TP;
 4104                            let end_point = TP::to_point(&range.end, &snapshot);
 4105                            let start_point = TP::to_point(&range.start, &snapshot);
 4106                            (start_point..end_point, text)
 4107                        })
 4108                        .sorted_by_key(|(range, _)| range.start)
 4109                        .collect::<Vec<_>>();
 4110                    buffer.edit(edits, None, cx);
 4111                })
 4112            }
 4113
 4114            this.refresh_inline_completion(true, false, window, cx);
 4115        });
 4116
 4117        let show_new_completions_on_confirm = completion
 4118            .confirm
 4119            .as_ref()
 4120            .map_or(false, |confirm| confirm(intent, window, cx));
 4121        if show_new_completions_on_confirm {
 4122            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4123        }
 4124
 4125        let provider = self.completion_provider.as_ref()?;
 4126        drop(completion);
 4127        let apply_edits = provider.apply_additional_edits_for_completion(
 4128            buffer_handle,
 4129            completions_menu.completions.clone(),
 4130            candidate_id,
 4131            true,
 4132            cx,
 4133        );
 4134
 4135        let editor_settings = EditorSettings::get_global(cx);
 4136        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4137            // After the code completion is finished, users often want to know what signatures are needed.
 4138            // so we should automatically call signature_help
 4139            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4140        }
 4141
 4142        Some(cx.foreground_executor().spawn(async move {
 4143            apply_edits.await?;
 4144            Ok(())
 4145        }))
 4146    }
 4147
 4148    pub fn toggle_code_actions(
 4149        &mut self,
 4150        action: &ToggleCodeActions,
 4151        window: &mut Window,
 4152        cx: &mut Context<Self>,
 4153    ) {
 4154        let mut context_menu = self.context_menu.borrow_mut();
 4155        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4156            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4157                // Toggle if we're selecting the same one
 4158                *context_menu = None;
 4159                cx.notify();
 4160                return;
 4161            } else {
 4162                // Otherwise, clear it and start a new one
 4163                *context_menu = None;
 4164                cx.notify();
 4165            }
 4166        }
 4167        drop(context_menu);
 4168        let snapshot = self.snapshot(window, cx);
 4169        let deployed_from_indicator = action.deployed_from_indicator;
 4170        let mut task = self.code_actions_task.take();
 4171        let action = action.clone();
 4172        cx.spawn_in(window, |editor, mut cx| async move {
 4173            while let Some(prev_task) = task {
 4174                prev_task.await.log_err();
 4175                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4176            }
 4177
 4178            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4179                if editor.focus_handle.is_focused(window) {
 4180                    let multibuffer_point = action
 4181                        .deployed_from_indicator
 4182                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4183                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4184                    let (buffer, buffer_row) = snapshot
 4185                        .buffer_snapshot
 4186                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4187                        .and_then(|(buffer_snapshot, range)| {
 4188                            editor
 4189                                .buffer
 4190                                .read(cx)
 4191                                .buffer(buffer_snapshot.remote_id())
 4192                                .map(|buffer| (buffer, range.start.row))
 4193                        })?;
 4194                    let (_, code_actions) = editor
 4195                        .available_code_actions
 4196                        .clone()
 4197                        .and_then(|(location, code_actions)| {
 4198                            let snapshot = location.buffer.read(cx).snapshot();
 4199                            let point_range = location.range.to_point(&snapshot);
 4200                            let point_range = point_range.start.row..=point_range.end.row;
 4201                            if point_range.contains(&buffer_row) {
 4202                                Some((location, code_actions))
 4203                            } else {
 4204                                None
 4205                            }
 4206                        })
 4207                        .unzip();
 4208                    let buffer_id = buffer.read(cx).remote_id();
 4209                    let tasks = editor
 4210                        .tasks
 4211                        .get(&(buffer_id, buffer_row))
 4212                        .map(|t| Arc::new(t.to_owned()));
 4213                    if tasks.is_none() && code_actions.is_none() {
 4214                        return None;
 4215                    }
 4216
 4217                    editor.completion_tasks.clear();
 4218                    editor.discard_inline_completion(false, cx);
 4219                    let task_context =
 4220                        tasks
 4221                            .as_ref()
 4222                            .zip(editor.project.clone())
 4223                            .map(|(tasks, project)| {
 4224                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4225                            });
 4226
 4227                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4228                        let task_context = match task_context {
 4229                            Some(task_context) => task_context.await,
 4230                            None => None,
 4231                        };
 4232                        let resolved_tasks =
 4233                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4234                                Rc::new(ResolvedTasks {
 4235                                    templates: tasks.resolve(&task_context).collect(),
 4236                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4237                                        multibuffer_point.row,
 4238                                        tasks.column,
 4239                                    )),
 4240                                })
 4241                            });
 4242                        let spawn_straight_away = resolved_tasks
 4243                            .as_ref()
 4244                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4245                            && code_actions
 4246                                .as_ref()
 4247                                .map_or(true, |actions| actions.is_empty());
 4248                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4249                            *editor.context_menu.borrow_mut() =
 4250                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4251                                    buffer,
 4252                                    actions: CodeActionContents {
 4253                                        tasks: resolved_tasks,
 4254                                        actions: code_actions,
 4255                                    },
 4256                                    selected_item: Default::default(),
 4257                                    scroll_handle: UniformListScrollHandle::default(),
 4258                                    deployed_from_indicator,
 4259                                }));
 4260                            if spawn_straight_away {
 4261                                if let Some(task) = editor.confirm_code_action(
 4262                                    &ConfirmCodeAction { item_ix: Some(0) },
 4263                                    window,
 4264                                    cx,
 4265                                ) {
 4266                                    cx.notify();
 4267                                    return task;
 4268                                }
 4269                            }
 4270                            cx.notify();
 4271                            Task::ready(Ok(()))
 4272                        }) {
 4273                            task.await
 4274                        } else {
 4275                            Ok(())
 4276                        }
 4277                    }))
 4278                } else {
 4279                    Some(Task::ready(Ok(())))
 4280                }
 4281            })?;
 4282            if let Some(task) = spawned_test_task {
 4283                task.await?;
 4284            }
 4285
 4286            Ok::<_, anyhow::Error>(())
 4287        })
 4288        .detach_and_log_err(cx);
 4289    }
 4290
 4291    pub fn confirm_code_action(
 4292        &mut self,
 4293        action: &ConfirmCodeAction,
 4294        window: &mut Window,
 4295        cx: &mut Context<Self>,
 4296    ) -> Option<Task<Result<()>>> {
 4297        let actions_menu =
 4298            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4299                menu
 4300            } else {
 4301                return None;
 4302            };
 4303        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4304        let action = actions_menu.actions.get(action_ix)?;
 4305        let title = action.label();
 4306        let buffer = actions_menu.buffer;
 4307        let workspace = self.workspace()?;
 4308
 4309        match action {
 4310            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4311                workspace.update(cx, |workspace, cx| {
 4312                    workspace::tasks::schedule_resolved_task(
 4313                        workspace,
 4314                        task_source_kind,
 4315                        resolved_task,
 4316                        false,
 4317                        cx,
 4318                    );
 4319
 4320                    Some(Task::ready(Ok(())))
 4321                })
 4322            }
 4323            CodeActionsItem::CodeAction {
 4324                excerpt_id,
 4325                action,
 4326                provider,
 4327            } => {
 4328                let apply_code_action =
 4329                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4330                let workspace = workspace.downgrade();
 4331                Some(cx.spawn_in(window, |editor, cx| async move {
 4332                    let project_transaction = apply_code_action.await?;
 4333                    Self::open_project_transaction(
 4334                        &editor,
 4335                        workspace,
 4336                        project_transaction,
 4337                        title,
 4338                        cx,
 4339                    )
 4340                    .await
 4341                }))
 4342            }
 4343        }
 4344    }
 4345
 4346    pub async fn open_project_transaction(
 4347        this: &WeakEntity<Editor>,
 4348        workspace: WeakEntity<Workspace>,
 4349        transaction: ProjectTransaction,
 4350        title: String,
 4351        mut cx: AsyncWindowContext,
 4352    ) -> Result<()> {
 4353        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4354        cx.update(|_, cx| {
 4355            entries.sort_unstable_by_key(|(buffer, _)| {
 4356                buffer.read(cx).file().map(|f| f.path().clone())
 4357            });
 4358        })?;
 4359
 4360        // If the project transaction's edits are all contained within this editor, then
 4361        // avoid opening a new editor to display them.
 4362
 4363        if let Some((buffer, transaction)) = entries.first() {
 4364            if entries.len() == 1 {
 4365                let excerpt = this.update(&mut cx, |editor, cx| {
 4366                    editor
 4367                        .buffer()
 4368                        .read(cx)
 4369                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4370                })?;
 4371                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4372                    if excerpted_buffer == *buffer {
 4373                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4374                            let excerpt_range = excerpt_range.to_offset(buffer);
 4375                            buffer
 4376                                .edited_ranges_for_transaction::<usize>(transaction)
 4377                                .all(|range| {
 4378                                    excerpt_range.start <= range.start
 4379                                        && excerpt_range.end >= range.end
 4380                                })
 4381                        })?;
 4382
 4383                        if all_edits_within_excerpt {
 4384                            return Ok(());
 4385                        }
 4386                    }
 4387                }
 4388            }
 4389        } else {
 4390            return Ok(());
 4391        }
 4392
 4393        let mut ranges_to_highlight = Vec::new();
 4394        let excerpt_buffer = cx.new(|cx| {
 4395            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4396            for (buffer_handle, transaction) in &entries {
 4397                let buffer = buffer_handle.read(cx);
 4398                ranges_to_highlight.extend(
 4399                    multibuffer.push_excerpts_with_context_lines(
 4400                        buffer_handle.clone(),
 4401                        buffer
 4402                            .edited_ranges_for_transaction::<usize>(transaction)
 4403                            .collect(),
 4404                        DEFAULT_MULTIBUFFER_CONTEXT,
 4405                        cx,
 4406                    ),
 4407                );
 4408            }
 4409            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4410            multibuffer
 4411        })?;
 4412
 4413        workspace.update_in(&mut cx, |workspace, window, cx| {
 4414            let project = workspace.project().clone();
 4415            let editor = cx
 4416                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4417            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4418            editor.update(cx, |editor, cx| {
 4419                editor.highlight_background::<Self>(
 4420                    &ranges_to_highlight,
 4421                    |theme| theme.editor_highlighted_line_background,
 4422                    cx,
 4423                );
 4424            });
 4425        })?;
 4426
 4427        Ok(())
 4428    }
 4429
 4430    pub fn clear_code_action_providers(&mut self) {
 4431        self.code_action_providers.clear();
 4432        self.available_code_actions.take();
 4433    }
 4434
 4435    pub fn add_code_action_provider(
 4436        &mut self,
 4437        provider: Rc<dyn CodeActionProvider>,
 4438        window: &mut Window,
 4439        cx: &mut Context<Self>,
 4440    ) {
 4441        if self
 4442            .code_action_providers
 4443            .iter()
 4444            .any(|existing_provider| existing_provider.id() == provider.id())
 4445        {
 4446            return;
 4447        }
 4448
 4449        self.code_action_providers.push(provider);
 4450        self.refresh_code_actions(window, cx);
 4451    }
 4452
 4453    pub fn remove_code_action_provider(
 4454        &mut self,
 4455        id: Arc<str>,
 4456        window: &mut Window,
 4457        cx: &mut Context<Self>,
 4458    ) {
 4459        self.code_action_providers
 4460            .retain(|provider| provider.id() != id);
 4461        self.refresh_code_actions(window, cx);
 4462    }
 4463
 4464    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4465        let buffer = self.buffer.read(cx);
 4466        let newest_selection = self.selections.newest_anchor().clone();
 4467        if newest_selection.head().diff_base_anchor.is_some() {
 4468            return None;
 4469        }
 4470        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4471        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4472        if start_buffer != end_buffer {
 4473            return None;
 4474        }
 4475
 4476        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4477            cx.background_executor()
 4478                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4479                .await;
 4480
 4481            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4482                let providers = this.code_action_providers.clone();
 4483                let tasks = this
 4484                    .code_action_providers
 4485                    .iter()
 4486                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4487                    .collect::<Vec<_>>();
 4488                (providers, tasks)
 4489            })?;
 4490
 4491            let mut actions = Vec::new();
 4492            for (provider, provider_actions) in
 4493                providers.into_iter().zip(future::join_all(tasks).await)
 4494            {
 4495                if let Some(provider_actions) = provider_actions.log_err() {
 4496                    actions.extend(provider_actions.into_iter().map(|action| {
 4497                        AvailableCodeAction {
 4498                            excerpt_id: newest_selection.start.excerpt_id,
 4499                            action,
 4500                            provider: provider.clone(),
 4501                        }
 4502                    }));
 4503                }
 4504            }
 4505
 4506            this.update(&mut cx, |this, cx| {
 4507                this.available_code_actions = if actions.is_empty() {
 4508                    None
 4509                } else {
 4510                    Some((
 4511                        Location {
 4512                            buffer: start_buffer,
 4513                            range: start..end,
 4514                        },
 4515                        actions.into(),
 4516                    ))
 4517                };
 4518                cx.notify();
 4519            })
 4520        }));
 4521        None
 4522    }
 4523
 4524    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4525        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4526            self.show_git_blame_inline = false;
 4527
 4528            self.show_git_blame_inline_delay_task =
 4529                Some(cx.spawn_in(window, |this, mut cx| async move {
 4530                    cx.background_executor().timer(delay).await;
 4531
 4532                    this.update(&mut cx, |this, cx| {
 4533                        this.show_git_blame_inline = true;
 4534                        cx.notify();
 4535                    })
 4536                    .log_err();
 4537                }));
 4538        }
 4539    }
 4540
 4541    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4542        if self.pending_rename.is_some() {
 4543            return None;
 4544        }
 4545
 4546        let provider = self.semantics_provider.clone()?;
 4547        let buffer = self.buffer.read(cx);
 4548        let newest_selection = self.selections.newest_anchor().clone();
 4549        let cursor_position = newest_selection.head();
 4550        let (cursor_buffer, cursor_buffer_position) =
 4551            buffer.text_anchor_for_position(cursor_position, cx)?;
 4552        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4553        if cursor_buffer != tail_buffer {
 4554            return None;
 4555        }
 4556        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4557        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4558            cx.background_executor()
 4559                .timer(Duration::from_millis(debounce))
 4560                .await;
 4561
 4562            let highlights = if let Some(highlights) = cx
 4563                .update(|cx| {
 4564                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4565                })
 4566                .ok()
 4567                .flatten()
 4568            {
 4569                highlights.await.log_err()
 4570            } else {
 4571                None
 4572            };
 4573
 4574            if let Some(highlights) = highlights {
 4575                this.update(&mut cx, |this, cx| {
 4576                    if this.pending_rename.is_some() {
 4577                        return;
 4578                    }
 4579
 4580                    let buffer_id = cursor_position.buffer_id;
 4581                    let buffer = this.buffer.read(cx);
 4582                    if !buffer
 4583                        .text_anchor_for_position(cursor_position, cx)
 4584                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4585                    {
 4586                        return;
 4587                    }
 4588
 4589                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4590                    let mut write_ranges = Vec::new();
 4591                    let mut read_ranges = Vec::new();
 4592                    for highlight in highlights {
 4593                        for (excerpt_id, excerpt_range) in
 4594                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4595                        {
 4596                            let start = highlight
 4597                                .range
 4598                                .start
 4599                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4600                            let end = highlight
 4601                                .range
 4602                                .end
 4603                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4604                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4605                                continue;
 4606                            }
 4607
 4608                            let range = Anchor {
 4609                                buffer_id,
 4610                                excerpt_id,
 4611                                text_anchor: start,
 4612                                diff_base_anchor: None,
 4613                            }..Anchor {
 4614                                buffer_id,
 4615                                excerpt_id,
 4616                                text_anchor: end,
 4617                                diff_base_anchor: None,
 4618                            };
 4619                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4620                                write_ranges.push(range);
 4621                            } else {
 4622                                read_ranges.push(range);
 4623                            }
 4624                        }
 4625                    }
 4626
 4627                    this.highlight_background::<DocumentHighlightRead>(
 4628                        &read_ranges,
 4629                        |theme| theme.editor_document_highlight_read_background,
 4630                        cx,
 4631                    );
 4632                    this.highlight_background::<DocumentHighlightWrite>(
 4633                        &write_ranges,
 4634                        |theme| theme.editor_document_highlight_write_background,
 4635                        cx,
 4636                    );
 4637                    cx.notify();
 4638                })
 4639                .log_err();
 4640            }
 4641        }));
 4642        None
 4643    }
 4644
 4645    pub fn refresh_inline_completion(
 4646        &mut self,
 4647        debounce: bool,
 4648        user_requested: bool,
 4649        window: &mut Window,
 4650        cx: &mut Context<Self>,
 4651    ) -> Option<()> {
 4652        let provider = self.inline_completion_provider()?;
 4653        let cursor = self.selections.newest_anchor().head();
 4654        let (buffer, cursor_buffer_position) =
 4655            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4656
 4657        if !user_requested
 4658            && (!self.enable_inline_completions
 4659                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4660                || !self.is_focused(window)
 4661                || buffer.read(cx).is_empty())
 4662        {
 4663            self.discard_inline_completion(false, cx);
 4664            return None;
 4665        }
 4666
 4667        self.update_visible_inline_completion(window, cx);
 4668        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4669        Some(())
 4670    }
 4671
 4672    fn cycle_inline_completion(
 4673        &mut self,
 4674        direction: Direction,
 4675        window: &mut Window,
 4676        cx: &mut Context<Self>,
 4677    ) -> Option<()> {
 4678        let provider = self.inline_completion_provider()?;
 4679        let cursor = self.selections.newest_anchor().head();
 4680        let (buffer, cursor_buffer_position) =
 4681            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4682        if !self.enable_inline_completions
 4683            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4684        {
 4685            return None;
 4686        }
 4687
 4688        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4689        self.update_visible_inline_completion(window, cx);
 4690
 4691        Some(())
 4692    }
 4693
 4694    pub fn show_inline_completion(
 4695        &mut self,
 4696        _: &ShowInlineCompletion,
 4697        window: &mut Window,
 4698        cx: &mut Context<Self>,
 4699    ) {
 4700        if !self.has_active_inline_completion() {
 4701            self.refresh_inline_completion(false, true, window, cx);
 4702            return;
 4703        }
 4704
 4705        self.update_visible_inline_completion(window, cx);
 4706    }
 4707
 4708    pub fn display_cursor_names(
 4709        &mut self,
 4710        _: &DisplayCursorNames,
 4711        window: &mut Window,
 4712        cx: &mut Context<Self>,
 4713    ) {
 4714        self.show_cursor_names(window, cx);
 4715    }
 4716
 4717    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4718        self.show_cursor_names = true;
 4719        cx.notify();
 4720        cx.spawn_in(window, |this, mut cx| async move {
 4721            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4722            this.update(&mut cx, |this, cx| {
 4723                this.show_cursor_names = false;
 4724                cx.notify()
 4725            })
 4726            .ok()
 4727        })
 4728        .detach();
 4729    }
 4730
 4731    pub fn next_inline_completion(
 4732        &mut self,
 4733        _: &NextInlineCompletion,
 4734        window: &mut Window,
 4735        cx: &mut Context<Self>,
 4736    ) {
 4737        if self.has_active_inline_completion() {
 4738            self.cycle_inline_completion(Direction::Next, window, cx);
 4739        } else {
 4740            let is_copilot_disabled = self
 4741                .refresh_inline_completion(false, true, window, cx)
 4742                .is_none();
 4743            if is_copilot_disabled {
 4744                cx.propagate();
 4745            }
 4746        }
 4747    }
 4748
 4749    pub fn previous_inline_completion(
 4750        &mut self,
 4751        _: &PreviousInlineCompletion,
 4752        window: &mut Window,
 4753        cx: &mut Context<Self>,
 4754    ) {
 4755        if self.has_active_inline_completion() {
 4756            self.cycle_inline_completion(Direction::Prev, window, cx);
 4757        } else {
 4758            let is_copilot_disabled = self
 4759                .refresh_inline_completion(false, true, window, cx)
 4760                .is_none();
 4761            if is_copilot_disabled {
 4762                cx.propagate();
 4763            }
 4764        }
 4765    }
 4766
 4767    pub fn accept_inline_completion(
 4768        &mut self,
 4769        _: &AcceptInlineCompletion,
 4770        window: &mut Window,
 4771        cx: &mut Context<Self>,
 4772    ) {
 4773        let buffer = self.buffer.read(cx);
 4774        let snapshot = buffer.snapshot(cx);
 4775        let selection = self.selections.newest_adjusted(cx);
 4776        let cursor = selection.head();
 4777        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4778        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4779        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4780        {
 4781            if cursor.column < suggested_indent.len
 4782                && cursor.column <= current_indent.len
 4783                && current_indent.len <= suggested_indent.len
 4784            {
 4785                self.tab(&Default::default(), window, cx);
 4786                return;
 4787            }
 4788        }
 4789
 4790        if self.show_inline_completions_in_menu(cx) {
 4791            self.hide_context_menu(window, cx);
 4792        }
 4793
 4794        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4795            return;
 4796        };
 4797
 4798        self.report_inline_completion_event(true, cx);
 4799
 4800        match &active_inline_completion.completion {
 4801            InlineCompletion::Move { target, .. } => {
 4802                let target = *target;
 4803                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4804                    selections.select_anchor_ranges([target..target]);
 4805                });
 4806            }
 4807            InlineCompletion::Edit { edits, .. } => {
 4808                if let Some(provider) = self.inline_completion_provider() {
 4809                    provider.accept(cx);
 4810                }
 4811
 4812                let snapshot = self.buffer.read(cx).snapshot(cx);
 4813                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4814
 4815                self.buffer.update(cx, |buffer, cx| {
 4816                    buffer.edit(edits.iter().cloned(), None, cx)
 4817                });
 4818
 4819                self.change_selections(None, window, cx, |s| {
 4820                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4821                });
 4822
 4823                self.update_visible_inline_completion(window, cx);
 4824                if self.active_inline_completion.is_none() {
 4825                    self.refresh_inline_completion(true, true, window, cx);
 4826                }
 4827
 4828                cx.notify();
 4829            }
 4830        }
 4831    }
 4832
 4833    pub fn accept_partial_inline_completion(
 4834        &mut self,
 4835        _: &AcceptPartialInlineCompletion,
 4836        window: &mut Window,
 4837        cx: &mut Context<Self>,
 4838    ) {
 4839        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4840            return;
 4841        };
 4842        if self.selections.count() != 1 {
 4843            return;
 4844        }
 4845
 4846        self.report_inline_completion_event(true, cx);
 4847
 4848        match &active_inline_completion.completion {
 4849            InlineCompletion::Move { target, .. } => {
 4850                let target = *target;
 4851                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4852                    selections.select_anchor_ranges([target..target]);
 4853                });
 4854            }
 4855            InlineCompletion::Edit { edits, .. } => {
 4856                // Find an insertion that starts at the cursor position.
 4857                let snapshot = self.buffer.read(cx).snapshot(cx);
 4858                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4859                let insertion = edits.iter().find_map(|(range, text)| {
 4860                    let range = range.to_offset(&snapshot);
 4861                    if range.is_empty() && range.start == cursor_offset {
 4862                        Some(text)
 4863                    } else {
 4864                        None
 4865                    }
 4866                });
 4867
 4868                if let Some(text) = insertion {
 4869                    let mut partial_completion = text
 4870                        .chars()
 4871                        .by_ref()
 4872                        .take_while(|c| c.is_alphabetic())
 4873                        .collect::<String>();
 4874                    if partial_completion.is_empty() {
 4875                        partial_completion = text
 4876                            .chars()
 4877                            .by_ref()
 4878                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4879                            .collect::<String>();
 4880                    }
 4881
 4882                    cx.emit(EditorEvent::InputHandled {
 4883                        utf16_range_to_replace: None,
 4884                        text: partial_completion.clone().into(),
 4885                    });
 4886
 4887                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4888
 4889                    self.refresh_inline_completion(true, true, window, cx);
 4890                    cx.notify();
 4891                } else {
 4892                    self.accept_inline_completion(&Default::default(), window, cx);
 4893                }
 4894            }
 4895        }
 4896    }
 4897
 4898    fn discard_inline_completion(
 4899        &mut self,
 4900        should_report_inline_completion_event: bool,
 4901        cx: &mut Context<Self>,
 4902    ) -> bool {
 4903        if should_report_inline_completion_event {
 4904            self.report_inline_completion_event(false, cx);
 4905        }
 4906
 4907        if let Some(provider) = self.inline_completion_provider() {
 4908            provider.discard(cx);
 4909        }
 4910
 4911        self.take_active_inline_completion(cx)
 4912    }
 4913
 4914    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4915        let Some(provider) = self.inline_completion_provider() else {
 4916            return;
 4917        };
 4918
 4919        let Some((_, buffer, _)) = self
 4920            .buffer
 4921            .read(cx)
 4922            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4923        else {
 4924            return;
 4925        };
 4926
 4927        let extension = buffer
 4928            .read(cx)
 4929            .file()
 4930            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4931
 4932        let event_type = match accepted {
 4933            true => "Edit Prediction Accepted",
 4934            false => "Edit Prediction Discarded",
 4935        };
 4936        telemetry::event!(
 4937            event_type,
 4938            provider = provider.name(),
 4939            suggestion_accepted = accepted,
 4940            file_extension = extension,
 4941        );
 4942    }
 4943
 4944    pub fn has_active_inline_completion(&self) -> bool {
 4945        self.active_inline_completion.is_some()
 4946    }
 4947
 4948    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 4949        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 4950            return false;
 4951        };
 4952
 4953        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 4954        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4955        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 4956        true
 4957    }
 4958
 4959    pub fn is_previewing_inline_completion(&self) -> bool {
 4960        matches!(
 4961            self.context_menu.borrow().as_ref(),
 4962            Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
 4963        )
 4964    }
 4965
 4966    fn update_inline_completion_preview(
 4967        &mut self,
 4968        modifiers: &Modifiers,
 4969        window: &mut Window,
 4970        cx: &mut Context<Self>,
 4971    ) {
 4972        // Moves jump directly with a preview step
 4973
 4974        if self
 4975            .active_inline_completion
 4976            .as_ref()
 4977            .map_or(true, |c| c.is_move())
 4978        {
 4979            cx.notify();
 4980            return;
 4981        }
 4982
 4983        if !self.show_inline_completions_in_menu(cx) {
 4984            return;
 4985        }
 4986
 4987        let mut menu_borrow = self.context_menu.borrow_mut();
 4988
 4989        let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
 4990            return;
 4991        };
 4992
 4993        if completions_menu.is_empty()
 4994            || completions_menu.previewing_inline_completion == modifiers.alt
 4995        {
 4996            return;
 4997        }
 4998
 4999        completions_menu.set_previewing_inline_completion(modifiers.alt);
 5000        drop(menu_borrow);
 5001        self.update_visible_inline_completion(window, cx);
 5002    }
 5003
 5004    fn update_visible_inline_completion(
 5005        &mut self,
 5006        _window: &mut Window,
 5007        cx: &mut Context<Self>,
 5008    ) -> Option<()> {
 5009        let selection = self.selections.newest_anchor();
 5010        let cursor = selection.head();
 5011        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5012        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5013        let excerpt_id = cursor.excerpt_id;
 5014
 5015        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5016        let completions_menu_has_precedence = !show_in_menu
 5017            && (self.context_menu.borrow().is_some()
 5018                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5019        if completions_menu_has_precedence
 5020            || !offset_selection.is_empty()
 5021            || !self.enable_inline_completions
 5022            || self
 5023                .active_inline_completion
 5024                .as_ref()
 5025                .map_or(false, |completion| {
 5026                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5027                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5028                    !invalidation_range.contains(&offset_selection.head())
 5029                })
 5030        {
 5031            self.discard_inline_completion(false, cx);
 5032            return None;
 5033        }
 5034
 5035        self.take_active_inline_completion(cx);
 5036        let provider = self.inline_completion_provider()?;
 5037
 5038        let (buffer, cursor_buffer_position) =
 5039            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5040
 5041        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5042        let edits = inline_completion
 5043            .edits
 5044            .into_iter()
 5045            .flat_map(|(range, new_text)| {
 5046                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5047                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5048                Some((start..end, new_text))
 5049            })
 5050            .collect::<Vec<_>>();
 5051        if edits.is_empty() {
 5052            return None;
 5053        }
 5054
 5055        let first_edit_start = edits.first().unwrap().0.start;
 5056        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5057        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5058
 5059        let last_edit_end = edits.last().unwrap().0.end;
 5060        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5061        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5062
 5063        let cursor_row = cursor.to_point(&multibuffer).row;
 5064
 5065        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5066
 5067        let mut inlay_ids = Vec::new();
 5068        let invalidation_row_range;
 5069        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5070            Some(cursor_row..edit_end_row)
 5071        } else if cursor_row > edit_end_row {
 5072            Some(edit_start_row..cursor_row)
 5073        } else {
 5074            None
 5075        };
 5076        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5077            invalidation_row_range = move_invalidation_row_range;
 5078            let target = first_edit_start;
 5079            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5080            // TODO: Base this off of TreeSitter or word boundaries?
 5081            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5082                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5083                Bias::Left,
 5084            ));
 5085            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5086                Point::new(target_point.row, target_point.column + 20),
 5087                Bias::Right,
 5088            ));
 5089            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5090            InlineCompletion::Move {
 5091                target,
 5092                range_around_target,
 5093                snapshot,
 5094            }
 5095        } else {
 5096            if !show_in_menu || !self.has_active_completions_menu() {
 5097                if edits
 5098                    .iter()
 5099                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5100                {
 5101                    let mut inlays = Vec::new();
 5102                    for (range, new_text) in &edits {
 5103                        let inlay = Inlay::inline_completion(
 5104                            post_inc(&mut self.next_inlay_id),
 5105                            range.start,
 5106                            new_text.as_str(),
 5107                        );
 5108                        inlay_ids.push(inlay.id);
 5109                        inlays.push(inlay);
 5110                    }
 5111
 5112                    self.splice_inlays(&[], inlays, cx);
 5113                } else {
 5114                    let background_color = cx.theme().status().deleted_background;
 5115                    self.highlight_text::<InlineCompletionHighlight>(
 5116                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5117                        HighlightStyle {
 5118                            background_color: Some(background_color),
 5119                            ..Default::default()
 5120                        },
 5121                        cx,
 5122                    );
 5123                }
 5124            }
 5125
 5126            invalidation_row_range = edit_start_row..edit_end_row;
 5127
 5128            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5129                if provider.show_tab_accept_marker() {
 5130                    EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
 5131                } else {
 5132                    EditDisplayMode::Inline
 5133                }
 5134            } else {
 5135                EditDisplayMode::DiffPopover
 5136            };
 5137
 5138            InlineCompletion::Edit {
 5139                edits,
 5140                edit_preview: inline_completion.edit_preview,
 5141                display_mode,
 5142                snapshot,
 5143            }
 5144        };
 5145
 5146        let invalidation_range = multibuffer
 5147            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5148            ..multibuffer.anchor_after(Point::new(
 5149                invalidation_row_range.end,
 5150                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5151            ));
 5152
 5153        self.stale_inline_completion_in_menu = None;
 5154        self.active_inline_completion = Some(InlineCompletionState {
 5155            inlay_ids,
 5156            completion,
 5157            invalidation_range,
 5158        });
 5159
 5160        cx.notify();
 5161
 5162        Some(())
 5163    }
 5164
 5165    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5166        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5167    }
 5168
 5169    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5170        let by_provider = matches!(
 5171            self.menu_inline_completions_policy,
 5172            MenuInlineCompletionsPolicy::ByProvider
 5173        );
 5174
 5175        by_provider
 5176            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5177            && self
 5178                .inline_completion_provider()
 5179                .map_or(false, |provider| provider.show_completions_in_menu())
 5180    }
 5181
 5182    fn render_code_actions_indicator(
 5183        &self,
 5184        _style: &EditorStyle,
 5185        row: DisplayRow,
 5186        is_active: bool,
 5187        cx: &mut Context<Self>,
 5188    ) -> Option<IconButton> {
 5189        if self.available_code_actions.is_some() {
 5190            Some(
 5191                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5192                    .shape(ui::IconButtonShape::Square)
 5193                    .icon_size(IconSize::XSmall)
 5194                    .icon_color(Color::Muted)
 5195                    .toggle_state(is_active)
 5196                    .tooltip({
 5197                        let focus_handle = self.focus_handle.clone();
 5198                        move |window, cx| {
 5199                            Tooltip::for_action_in(
 5200                                "Toggle Code Actions",
 5201                                &ToggleCodeActions {
 5202                                    deployed_from_indicator: None,
 5203                                },
 5204                                &focus_handle,
 5205                                window,
 5206                                cx,
 5207                            )
 5208                        }
 5209                    })
 5210                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5211                        window.focus(&editor.focus_handle(cx));
 5212                        editor.toggle_code_actions(
 5213                            &ToggleCodeActions {
 5214                                deployed_from_indicator: Some(row),
 5215                            },
 5216                            window,
 5217                            cx,
 5218                        );
 5219                    })),
 5220            )
 5221        } else {
 5222            None
 5223        }
 5224    }
 5225
 5226    fn clear_tasks(&mut self) {
 5227        self.tasks.clear()
 5228    }
 5229
 5230    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5231        if self.tasks.insert(key, value).is_some() {
 5232            // This case should hopefully be rare, but just in case...
 5233            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5234        }
 5235    }
 5236
 5237    fn build_tasks_context(
 5238        project: &Entity<Project>,
 5239        buffer: &Entity<Buffer>,
 5240        buffer_row: u32,
 5241        tasks: &Arc<RunnableTasks>,
 5242        cx: &mut Context<Self>,
 5243    ) -> Task<Option<task::TaskContext>> {
 5244        let position = Point::new(buffer_row, tasks.column);
 5245        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5246        let location = Location {
 5247            buffer: buffer.clone(),
 5248            range: range_start..range_start,
 5249        };
 5250        // Fill in the environmental variables from the tree-sitter captures
 5251        let mut captured_task_variables = TaskVariables::default();
 5252        for (capture_name, value) in tasks.extra_variables.clone() {
 5253            captured_task_variables.insert(
 5254                task::VariableName::Custom(capture_name.into()),
 5255                value.clone(),
 5256            );
 5257        }
 5258        project.update(cx, |project, cx| {
 5259            project.task_store().update(cx, |task_store, cx| {
 5260                task_store.task_context_for_location(captured_task_variables, location, cx)
 5261            })
 5262        })
 5263    }
 5264
 5265    pub fn spawn_nearest_task(
 5266        &mut self,
 5267        action: &SpawnNearestTask,
 5268        window: &mut Window,
 5269        cx: &mut Context<Self>,
 5270    ) {
 5271        let Some((workspace, _)) = self.workspace.clone() else {
 5272            return;
 5273        };
 5274        let Some(project) = self.project.clone() else {
 5275            return;
 5276        };
 5277
 5278        // Try to find a closest, enclosing node using tree-sitter that has a
 5279        // task
 5280        let Some((buffer, buffer_row, tasks)) = self
 5281            .find_enclosing_node_task(cx)
 5282            // Or find the task that's closest in row-distance.
 5283            .or_else(|| self.find_closest_task(cx))
 5284        else {
 5285            return;
 5286        };
 5287
 5288        let reveal_strategy = action.reveal;
 5289        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5290        cx.spawn_in(window, |_, mut cx| async move {
 5291            let context = task_context.await?;
 5292            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5293
 5294            let resolved = resolved_task.resolved.as_mut()?;
 5295            resolved.reveal = reveal_strategy;
 5296
 5297            workspace
 5298                .update(&mut cx, |workspace, cx| {
 5299                    workspace::tasks::schedule_resolved_task(
 5300                        workspace,
 5301                        task_source_kind,
 5302                        resolved_task,
 5303                        false,
 5304                        cx,
 5305                    );
 5306                })
 5307                .ok()
 5308        })
 5309        .detach();
 5310    }
 5311
 5312    fn find_closest_task(
 5313        &mut self,
 5314        cx: &mut Context<Self>,
 5315    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5316        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5317
 5318        let ((buffer_id, row), tasks) = self
 5319            .tasks
 5320            .iter()
 5321            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5322
 5323        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5324        let tasks = Arc::new(tasks.to_owned());
 5325        Some((buffer, *row, tasks))
 5326    }
 5327
 5328    fn find_enclosing_node_task(
 5329        &mut self,
 5330        cx: &mut Context<Self>,
 5331    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5332        let snapshot = self.buffer.read(cx).snapshot(cx);
 5333        let offset = self.selections.newest::<usize>(cx).head();
 5334        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5335        let buffer_id = excerpt.buffer().remote_id();
 5336
 5337        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5338        let mut cursor = layer.node().walk();
 5339
 5340        while cursor.goto_first_child_for_byte(offset).is_some() {
 5341            if cursor.node().end_byte() == offset {
 5342                cursor.goto_next_sibling();
 5343            }
 5344        }
 5345
 5346        // Ascend to the smallest ancestor that contains the range and has a task.
 5347        loop {
 5348            let node = cursor.node();
 5349            let node_range = node.byte_range();
 5350            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5351
 5352            // Check if this node contains our offset
 5353            if node_range.start <= offset && node_range.end >= offset {
 5354                // If it contains offset, check for task
 5355                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5356                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5357                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5358                }
 5359            }
 5360
 5361            if !cursor.goto_parent() {
 5362                break;
 5363            }
 5364        }
 5365        None
 5366    }
 5367
 5368    fn render_run_indicator(
 5369        &self,
 5370        _style: &EditorStyle,
 5371        is_active: bool,
 5372        row: DisplayRow,
 5373        cx: &mut Context<Self>,
 5374    ) -> IconButton {
 5375        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5376            .shape(ui::IconButtonShape::Square)
 5377            .icon_size(IconSize::XSmall)
 5378            .icon_color(Color::Muted)
 5379            .toggle_state(is_active)
 5380            .on_click(cx.listener(move |editor, _e, window, cx| {
 5381                window.focus(&editor.focus_handle(cx));
 5382                editor.toggle_code_actions(
 5383                    &ToggleCodeActions {
 5384                        deployed_from_indicator: Some(row),
 5385                    },
 5386                    window,
 5387                    cx,
 5388                );
 5389            }))
 5390    }
 5391
 5392    pub fn context_menu_visible(&self) -> bool {
 5393        self.context_menu
 5394            .borrow()
 5395            .as_ref()
 5396            .map_or(false, |menu| menu.visible())
 5397    }
 5398
 5399    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5400        self.context_menu
 5401            .borrow()
 5402            .as_ref()
 5403            .map(|menu| menu.origin())
 5404    }
 5405
 5406    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5407        px(32.)
 5408    }
 5409
 5410    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5411        if self.read_only(cx) {
 5412            cx.theme().players().read_only()
 5413        } else {
 5414            self.style.as_ref().unwrap().local_player
 5415        }
 5416    }
 5417
 5418    #[allow(clippy::too_many_arguments)]
 5419    fn render_edit_prediction_cursor_popover(
 5420        &self,
 5421        min_width: Pixels,
 5422        max_width: Pixels,
 5423        cursor_point: Point,
 5424        line_layouts: &[LineWithInvisibles],
 5425        style: &EditorStyle,
 5426        accept_keystroke: &gpui::Keystroke,
 5427        window: &Window,
 5428        cx: &mut Context<Editor>,
 5429    ) -> Option<AnyElement> {
 5430        let provider = self.inline_completion_provider.as_ref()?;
 5431
 5432        if provider.provider.needs_terms_acceptance(cx) {
 5433            return Some(
 5434                h_flex()
 5435                    .h(self.edit_prediction_cursor_popover_height())
 5436                    .min_w(min_width)
 5437                    .flex_1()
 5438                    .px_2()
 5439                    .gap_3()
 5440                    .elevation_2(cx)
 5441                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5442                    .id("accept-terms")
 5443                    .cursor_pointer()
 5444                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5445                    .on_click(cx.listener(|this, _event, window, cx| {
 5446                        cx.stop_propagation();
 5447                        this.toggle_zed_predict_onboarding(window, cx)
 5448                    }))
 5449                    .child(
 5450                        h_flex()
 5451                            .w_full()
 5452                            .gap_2()
 5453                            .child(Icon::new(IconName::ZedPredict))
 5454                            .child(Label::new("Accept Terms of Service"))
 5455                            .child(div().w_full())
 5456                            .child(Icon::new(IconName::ArrowUpRight))
 5457                            .into_any_element(),
 5458                    )
 5459                    .into_any(),
 5460            );
 5461        }
 5462
 5463        let is_refreshing = provider.provider.is_refreshing(cx);
 5464
 5465        fn pending_completion_container() -> Div {
 5466            h_flex()
 5467                .flex_1()
 5468                .gap_3()
 5469                .child(Icon::new(IconName::ZedPredict))
 5470        }
 5471
 5472        let completion = match &self.active_inline_completion {
 5473            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5474                completion,
 5475                cursor_point,
 5476                line_layouts,
 5477                style,
 5478                cx,
 5479            )?,
 5480
 5481            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5482                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5483                    stale_completion,
 5484                    cursor_point,
 5485                    line_layouts,
 5486                    style,
 5487                    cx,
 5488                )?,
 5489
 5490                None => {
 5491                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5492                }
 5493            },
 5494
 5495            None => pending_completion_container().child(Label::new("No Prediction")),
 5496        };
 5497
 5498        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5499        let completion = completion.font(buffer_font.clone());
 5500
 5501        let completion = if is_refreshing {
 5502            completion
 5503                .with_animation(
 5504                    "loading-completion",
 5505                    Animation::new(Duration::from_secs(2))
 5506                        .repeat()
 5507                        .with_easing(pulsating_between(0.4, 0.8)),
 5508                    |label, delta| label.opacity(delta),
 5509                )
 5510                .into_any_element()
 5511        } else {
 5512            completion.into_any_element()
 5513        };
 5514
 5515        let has_completion = self.active_inline_completion.is_some();
 5516
 5517        let is_move = self
 5518            .active_inline_completion
 5519            .as_ref()
 5520            .map_or(false, |c| c.is_move());
 5521
 5522        Some(
 5523            h_flex()
 5524                .h(self.edit_prediction_cursor_popover_height())
 5525                .min_w(min_width)
 5526                .max_w(max_width)
 5527                .flex_1()
 5528                .px_2()
 5529                .gap_3()
 5530                .elevation_2(cx)
 5531                .child(completion)
 5532                .child(
 5533                    h_flex()
 5534                        .border_l_1()
 5535                        .border_color(cx.theme().colors().border_variant)
 5536                        .pl_2()
 5537                        .child(
 5538                            h_flex()
 5539                                .font(buffer_font.clone())
 5540                                .p_1()
 5541                                .rounded_sm()
 5542                                .children(ui::render_modifiers(
 5543                                    &accept_keystroke.modifiers,
 5544                                    PlatformStyle::platform(),
 5545                                    if window.modifiers() == accept_keystroke.modifiers {
 5546                                        Some(Color::Accent)
 5547                                    } else {
 5548                                        None
 5549                                    },
 5550                                    !is_move,
 5551                                )),
 5552                        )
 5553                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5554                        .child(if is_move {
 5555                            div()
 5556                                .child(ui::Key::new(&accept_keystroke.key, None))
 5557                                .font(buffer_font.clone())
 5558                                .into_any()
 5559                        } else {
 5560                            Label::new("Preview").color(Color::Muted).into_any_element()
 5561                        }),
 5562                )
 5563                .into_any(),
 5564        )
 5565    }
 5566
 5567    fn render_edit_prediction_cursor_popover_preview(
 5568        &self,
 5569        completion: &InlineCompletionState,
 5570        cursor_point: Point,
 5571        line_layouts: &[LineWithInvisibles],
 5572        style: &EditorStyle,
 5573        cx: &mut Context<Editor>,
 5574    ) -> Option<Div> {
 5575        use text::ToPoint as _;
 5576
 5577        fn render_relative_row_jump(
 5578            prefix: impl Into<String>,
 5579            current_row: u32,
 5580            target_row: u32,
 5581        ) -> Div {
 5582            let (row_diff, arrow) = if target_row < current_row {
 5583                (current_row - target_row, IconName::ArrowUp)
 5584            } else {
 5585                (target_row - current_row, IconName::ArrowDown)
 5586            };
 5587
 5588            h_flex()
 5589                .child(
 5590                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5591                        .color(Color::Muted)
 5592                        .size(LabelSize::Small),
 5593                )
 5594                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5595        }
 5596
 5597        match &completion.completion {
 5598            InlineCompletion::Edit {
 5599                edits,
 5600                edit_preview,
 5601                snapshot,
 5602                display_mode: _,
 5603            } => {
 5604                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5605
 5606                let highlighted_edits = crate::inline_completion_edit_text(
 5607                    &snapshot,
 5608                    &edits,
 5609                    edit_preview.as_ref()?,
 5610                    true,
 5611                    cx,
 5612                );
 5613
 5614                let len_total = highlighted_edits.text.len();
 5615                let first_line = &highlighted_edits.text
 5616                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5617                let first_line_len = first_line.len();
 5618
 5619                let first_highlight_start = highlighted_edits
 5620                    .highlights
 5621                    .first()
 5622                    .map_or(0, |(range, _)| range.start);
 5623                let drop_prefix_len = first_line
 5624                    .char_indices()
 5625                    .find(|(_, c)| !c.is_whitespace())
 5626                    .map_or(first_highlight_start, |(ix, _)| {
 5627                        ix.min(first_highlight_start)
 5628                    });
 5629
 5630                let preview_text = &first_line[drop_prefix_len..];
 5631                let preview_len = preview_text.len();
 5632                let highlights = highlighted_edits
 5633                    .highlights
 5634                    .into_iter()
 5635                    .take_until(|(range, _)| range.start > first_line_len)
 5636                    .map(|(range, style)| {
 5637                        (
 5638                            range.start - drop_prefix_len
 5639                                ..(range.end - drop_prefix_len).min(preview_len),
 5640                            style,
 5641                        )
 5642                    });
 5643
 5644                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5645                    .with_highlights(&style.text, highlights);
 5646
 5647                let preview = h_flex()
 5648                    .gap_1()
 5649                    .child(styled_text)
 5650                    .when(len_total > first_line_len, |parent| parent.child(""));
 5651
 5652                let left = if first_edit_row != cursor_point.row {
 5653                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5654                        .into_any_element()
 5655                } else {
 5656                    Icon::new(IconName::ZedPredict).into_any_element()
 5657                };
 5658
 5659                Some(h_flex().flex_1().gap_3().child(left).child(preview))
 5660            }
 5661
 5662            InlineCompletion::Move {
 5663                target,
 5664                range_around_target,
 5665                snapshot,
 5666            } => {
 5667                let highlighted_text = snapshot.highlighted_text_for_range(
 5668                    range_around_target.clone(),
 5669                    None,
 5670                    &style.syntax,
 5671                );
 5672                let cursor_color = self.current_user_player_color(cx).cursor;
 5673
 5674                let start_point = range_around_target.start.to_point(&snapshot);
 5675                let end_point = range_around_target.end.to_point(&snapshot);
 5676                let target_point = target.text_anchor.to_point(&snapshot);
 5677
 5678                let start_column_x =
 5679                    line_layouts[start_point.row as usize].x_for_index(start_point.column as usize);
 5680                let target_column_x = line_layouts[target_point.row as usize]
 5681                    .x_for_index(target_point.column as usize);
 5682                let cursor_relative_position = target_column_x - start_column_x;
 5683
 5684                let fade_before = start_point.column > 0;
 5685                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5686
 5687                let background = cx.theme().colors().elevated_surface_background;
 5688
 5689                Some(
 5690                    h_flex()
 5691                        .gap_3()
 5692                        .flex_1()
 5693                        .child(render_relative_row_jump(
 5694                            "Jump ",
 5695                            cursor_point.row,
 5696                            target.text_anchor.to_point(&snapshot).row,
 5697                        ))
 5698                        .when(!highlighted_text.text.is_empty(), |parent| {
 5699                            parent.child(
 5700                                h_flex()
 5701                                    .relative()
 5702                                    .child(highlighted_text.to_styled_text(&style.text))
 5703                                    .when(fade_before, |parent| {
 5704                                        parent.child(
 5705                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5706                                                linear_gradient(
 5707                                                    90.,
 5708                                                    linear_color_stop(background, 0.),
 5709                                                    linear_color_stop(background.opacity(0.), 1.),
 5710                                                ),
 5711                                            ),
 5712                                        )
 5713                                    })
 5714                                    .when(fade_after, |parent| {
 5715                                        parent.child(
 5716                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5717                                                linear_gradient(
 5718                                                    -90.,
 5719                                                    linear_color_stop(background, 0.),
 5720                                                    linear_color_stop(background.opacity(0.), 1.),
 5721                                                ),
 5722                                            ),
 5723                                        )
 5724                                    })
 5725                                    .child(
 5726                                        div()
 5727                                            .w(px(2.))
 5728                                            .h_full()
 5729                                            .bg(cursor_color)
 5730                                            .absolute()
 5731                                            .top_0()
 5732                                            .left(cursor_relative_position),
 5733                                    ),
 5734                            )
 5735                        }),
 5736                )
 5737            }
 5738        }
 5739    }
 5740
 5741    fn render_context_menu(
 5742        &self,
 5743        style: &EditorStyle,
 5744        max_height_in_lines: u32,
 5745        y_flipped: bool,
 5746        window: &mut Window,
 5747        cx: &mut Context<Editor>,
 5748    ) -> Option<AnyElement> {
 5749        let menu = self.context_menu.borrow();
 5750        let menu = menu.as_ref()?;
 5751        if !menu.visible() {
 5752            return None;
 5753        };
 5754        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5755    }
 5756
 5757    fn render_context_menu_aside(
 5758        &self,
 5759        style: &EditorStyle,
 5760        max_size: Size<Pixels>,
 5761        cx: &mut Context<Editor>,
 5762    ) -> Option<AnyElement> {
 5763        self.context_menu.borrow().as_ref().and_then(|menu| {
 5764            if menu.visible() {
 5765                menu.render_aside(
 5766                    style,
 5767                    max_size,
 5768                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5769                    cx,
 5770                )
 5771            } else {
 5772                None
 5773            }
 5774        })
 5775    }
 5776
 5777    fn hide_context_menu(
 5778        &mut self,
 5779        window: &mut Window,
 5780        cx: &mut Context<Self>,
 5781    ) -> Option<CodeContextMenu> {
 5782        cx.notify();
 5783        self.completion_tasks.clear();
 5784        let context_menu = self.context_menu.borrow_mut().take();
 5785        self.stale_inline_completion_in_menu.take();
 5786        if context_menu.is_some() {
 5787            self.update_visible_inline_completion(window, cx);
 5788        }
 5789        context_menu
 5790    }
 5791
 5792    fn show_snippet_choices(
 5793        &mut self,
 5794        choices: &Vec<String>,
 5795        selection: Range<Anchor>,
 5796        cx: &mut Context<Self>,
 5797    ) {
 5798        if selection.start.buffer_id.is_none() {
 5799            return;
 5800        }
 5801        let buffer_id = selection.start.buffer_id.unwrap();
 5802        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5803        let id = post_inc(&mut self.next_completion_id);
 5804
 5805        if let Some(buffer) = buffer {
 5806            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5807                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5808            ));
 5809        }
 5810    }
 5811
 5812    pub fn insert_snippet(
 5813        &mut self,
 5814        insertion_ranges: &[Range<usize>],
 5815        snippet: Snippet,
 5816        window: &mut Window,
 5817        cx: &mut Context<Self>,
 5818    ) -> Result<()> {
 5819        struct Tabstop<T> {
 5820            is_end_tabstop: bool,
 5821            ranges: Vec<Range<T>>,
 5822            choices: Option<Vec<String>>,
 5823        }
 5824
 5825        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5826            let snippet_text: Arc<str> = snippet.text.clone().into();
 5827            buffer.edit(
 5828                insertion_ranges
 5829                    .iter()
 5830                    .cloned()
 5831                    .map(|range| (range, snippet_text.clone())),
 5832                Some(AutoindentMode::EachLine),
 5833                cx,
 5834            );
 5835
 5836            let snapshot = &*buffer.read(cx);
 5837            let snippet = &snippet;
 5838            snippet
 5839                .tabstops
 5840                .iter()
 5841                .map(|tabstop| {
 5842                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5843                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5844                    });
 5845                    let mut tabstop_ranges = tabstop
 5846                        .ranges
 5847                        .iter()
 5848                        .flat_map(|tabstop_range| {
 5849                            let mut delta = 0_isize;
 5850                            insertion_ranges.iter().map(move |insertion_range| {
 5851                                let insertion_start = insertion_range.start as isize + delta;
 5852                                delta +=
 5853                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5854
 5855                                let start = ((insertion_start + tabstop_range.start) as usize)
 5856                                    .min(snapshot.len());
 5857                                let end = ((insertion_start + tabstop_range.end) as usize)
 5858                                    .min(snapshot.len());
 5859                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5860                            })
 5861                        })
 5862                        .collect::<Vec<_>>();
 5863                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5864
 5865                    Tabstop {
 5866                        is_end_tabstop,
 5867                        ranges: tabstop_ranges,
 5868                        choices: tabstop.choices.clone(),
 5869                    }
 5870                })
 5871                .collect::<Vec<_>>()
 5872        });
 5873        if let Some(tabstop) = tabstops.first() {
 5874            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5875                s.select_ranges(tabstop.ranges.iter().cloned());
 5876            });
 5877
 5878            if let Some(choices) = &tabstop.choices {
 5879                if let Some(selection) = tabstop.ranges.first() {
 5880                    self.show_snippet_choices(choices, selection.clone(), cx)
 5881                }
 5882            }
 5883
 5884            // If we're already at the last tabstop and it's at the end of the snippet,
 5885            // we're done, we don't need to keep the state around.
 5886            if !tabstop.is_end_tabstop {
 5887                let choices = tabstops
 5888                    .iter()
 5889                    .map(|tabstop| tabstop.choices.clone())
 5890                    .collect();
 5891
 5892                let ranges = tabstops
 5893                    .into_iter()
 5894                    .map(|tabstop| tabstop.ranges)
 5895                    .collect::<Vec<_>>();
 5896
 5897                self.snippet_stack.push(SnippetState {
 5898                    active_index: 0,
 5899                    ranges,
 5900                    choices,
 5901                });
 5902            }
 5903
 5904            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5905            if self.autoclose_regions.is_empty() {
 5906                let snapshot = self.buffer.read(cx).snapshot(cx);
 5907                for selection in &mut self.selections.all::<Point>(cx) {
 5908                    let selection_head = selection.head();
 5909                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5910                        continue;
 5911                    };
 5912
 5913                    let mut bracket_pair = None;
 5914                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5915                    let prev_chars = snapshot
 5916                        .reversed_chars_at(selection_head)
 5917                        .collect::<String>();
 5918                    for (pair, enabled) in scope.brackets() {
 5919                        if enabled
 5920                            && pair.close
 5921                            && prev_chars.starts_with(pair.start.as_str())
 5922                            && next_chars.starts_with(pair.end.as_str())
 5923                        {
 5924                            bracket_pair = Some(pair.clone());
 5925                            break;
 5926                        }
 5927                    }
 5928                    if let Some(pair) = bracket_pair {
 5929                        let start = snapshot.anchor_after(selection_head);
 5930                        let end = snapshot.anchor_after(selection_head);
 5931                        self.autoclose_regions.push(AutocloseRegion {
 5932                            selection_id: selection.id,
 5933                            range: start..end,
 5934                            pair,
 5935                        });
 5936                    }
 5937                }
 5938            }
 5939        }
 5940        Ok(())
 5941    }
 5942
 5943    pub fn move_to_next_snippet_tabstop(
 5944        &mut self,
 5945        window: &mut Window,
 5946        cx: &mut Context<Self>,
 5947    ) -> bool {
 5948        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5949    }
 5950
 5951    pub fn move_to_prev_snippet_tabstop(
 5952        &mut self,
 5953        window: &mut Window,
 5954        cx: &mut Context<Self>,
 5955    ) -> bool {
 5956        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5957    }
 5958
 5959    pub fn move_to_snippet_tabstop(
 5960        &mut self,
 5961        bias: Bias,
 5962        window: &mut Window,
 5963        cx: &mut Context<Self>,
 5964    ) -> bool {
 5965        if let Some(mut snippet) = self.snippet_stack.pop() {
 5966            match bias {
 5967                Bias::Left => {
 5968                    if snippet.active_index > 0 {
 5969                        snippet.active_index -= 1;
 5970                    } else {
 5971                        self.snippet_stack.push(snippet);
 5972                        return false;
 5973                    }
 5974                }
 5975                Bias::Right => {
 5976                    if snippet.active_index + 1 < snippet.ranges.len() {
 5977                        snippet.active_index += 1;
 5978                    } else {
 5979                        self.snippet_stack.push(snippet);
 5980                        return false;
 5981                    }
 5982                }
 5983            }
 5984            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5985                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5986                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5987                });
 5988
 5989                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5990                    if let Some(selection) = current_ranges.first() {
 5991                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5992                    }
 5993                }
 5994
 5995                // If snippet state is not at the last tabstop, push it back on the stack
 5996                if snippet.active_index + 1 < snippet.ranges.len() {
 5997                    self.snippet_stack.push(snippet);
 5998                }
 5999                return true;
 6000            }
 6001        }
 6002
 6003        false
 6004    }
 6005
 6006    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6007        self.transact(window, cx, |this, window, cx| {
 6008            this.select_all(&SelectAll, window, cx);
 6009            this.insert("", window, cx);
 6010        });
 6011    }
 6012
 6013    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6014        self.transact(window, cx, |this, window, cx| {
 6015            this.select_autoclose_pair(window, cx);
 6016            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6017            if !this.linked_edit_ranges.is_empty() {
 6018                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6019                let snapshot = this.buffer.read(cx).snapshot(cx);
 6020
 6021                for selection in selections.iter() {
 6022                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6023                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6024                    if selection_start.buffer_id != selection_end.buffer_id {
 6025                        continue;
 6026                    }
 6027                    if let Some(ranges) =
 6028                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6029                    {
 6030                        for (buffer, entries) in ranges {
 6031                            linked_ranges.entry(buffer).or_default().extend(entries);
 6032                        }
 6033                    }
 6034                }
 6035            }
 6036
 6037            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6038            if !this.selections.line_mode {
 6039                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6040                for selection in &mut selections {
 6041                    if selection.is_empty() {
 6042                        let old_head = selection.head();
 6043                        let mut new_head =
 6044                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6045                                .to_point(&display_map);
 6046                        if let Some((buffer, line_buffer_range)) = display_map
 6047                            .buffer_snapshot
 6048                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6049                        {
 6050                            let indent_size =
 6051                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6052                            let indent_len = match indent_size.kind {
 6053                                IndentKind::Space => {
 6054                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6055                                }
 6056                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6057                            };
 6058                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6059                                let indent_len = indent_len.get();
 6060                                new_head = cmp::min(
 6061                                    new_head,
 6062                                    MultiBufferPoint::new(
 6063                                        old_head.row,
 6064                                        ((old_head.column - 1) / indent_len) * indent_len,
 6065                                    ),
 6066                                );
 6067                            }
 6068                        }
 6069
 6070                        selection.set_head(new_head, SelectionGoal::None);
 6071                    }
 6072                }
 6073            }
 6074
 6075            this.signature_help_state.set_backspace_pressed(true);
 6076            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6077                s.select(selections)
 6078            });
 6079            this.insert("", window, cx);
 6080            let empty_str: Arc<str> = Arc::from("");
 6081            for (buffer, edits) in linked_ranges {
 6082                let snapshot = buffer.read(cx).snapshot();
 6083                use text::ToPoint as TP;
 6084
 6085                let edits = edits
 6086                    .into_iter()
 6087                    .map(|range| {
 6088                        let end_point = TP::to_point(&range.end, &snapshot);
 6089                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6090
 6091                        if end_point == start_point {
 6092                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6093                                .saturating_sub(1);
 6094                            start_point =
 6095                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6096                        };
 6097
 6098                        (start_point..end_point, empty_str.clone())
 6099                    })
 6100                    .sorted_by_key(|(range, _)| range.start)
 6101                    .collect::<Vec<_>>();
 6102                buffer.update(cx, |this, cx| {
 6103                    this.edit(edits, None, cx);
 6104                })
 6105            }
 6106            this.refresh_inline_completion(true, false, window, cx);
 6107            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6108        });
 6109    }
 6110
 6111    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6112        self.transact(window, cx, |this, window, cx| {
 6113            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6114                let line_mode = s.line_mode;
 6115                s.move_with(|map, selection| {
 6116                    if selection.is_empty() && !line_mode {
 6117                        let cursor = movement::right(map, selection.head());
 6118                        selection.end = cursor;
 6119                        selection.reversed = true;
 6120                        selection.goal = SelectionGoal::None;
 6121                    }
 6122                })
 6123            });
 6124            this.insert("", window, cx);
 6125            this.refresh_inline_completion(true, false, window, cx);
 6126        });
 6127    }
 6128
 6129    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6130        if self.move_to_prev_snippet_tabstop(window, cx) {
 6131            return;
 6132        }
 6133
 6134        self.outdent(&Outdent, window, cx);
 6135    }
 6136
 6137    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6138        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6139            return;
 6140        }
 6141
 6142        let mut selections = self.selections.all_adjusted(cx);
 6143        let buffer = self.buffer.read(cx);
 6144        let snapshot = buffer.snapshot(cx);
 6145        let rows_iter = selections.iter().map(|s| s.head().row);
 6146        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6147
 6148        let mut edits = Vec::new();
 6149        let mut prev_edited_row = 0;
 6150        let mut row_delta = 0;
 6151        for selection in &mut selections {
 6152            if selection.start.row != prev_edited_row {
 6153                row_delta = 0;
 6154            }
 6155            prev_edited_row = selection.end.row;
 6156
 6157            // If the selection is non-empty, then increase the indentation of the selected lines.
 6158            if !selection.is_empty() {
 6159                row_delta =
 6160                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6161                continue;
 6162            }
 6163
 6164            // If the selection is empty and the cursor is in the leading whitespace before the
 6165            // suggested indentation, then auto-indent the line.
 6166            let cursor = selection.head();
 6167            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6168            if let Some(suggested_indent) =
 6169                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6170            {
 6171                if cursor.column < suggested_indent.len
 6172                    && cursor.column <= current_indent.len
 6173                    && current_indent.len <= suggested_indent.len
 6174                {
 6175                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6176                    selection.end = selection.start;
 6177                    if row_delta == 0 {
 6178                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6179                            cursor.row,
 6180                            current_indent,
 6181                            suggested_indent,
 6182                        ));
 6183                        row_delta = suggested_indent.len - current_indent.len;
 6184                    }
 6185                    continue;
 6186                }
 6187            }
 6188
 6189            // Otherwise, insert a hard or soft tab.
 6190            let settings = buffer.settings_at(cursor, cx);
 6191            let tab_size = if settings.hard_tabs {
 6192                IndentSize::tab()
 6193            } else {
 6194                let tab_size = settings.tab_size.get();
 6195                let char_column = snapshot
 6196                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6197                    .flat_map(str::chars)
 6198                    .count()
 6199                    + row_delta as usize;
 6200                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6201                IndentSize::spaces(chars_to_next_tab_stop)
 6202            };
 6203            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6204            selection.end = selection.start;
 6205            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6206            row_delta += tab_size.len;
 6207        }
 6208
 6209        self.transact(window, cx, |this, window, cx| {
 6210            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6211            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6212                s.select(selections)
 6213            });
 6214            this.refresh_inline_completion(true, false, window, cx);
 6215        });
 6216    }
 6217
 6218    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6219        if self.read_only(cx) {
 6220            return;
 6221        }
 6222        let mut selections = self.selections.all::<Point>(cx);
 6223        let mut prev_edited_row = 0;
 6224        let mut row_delta = 0;
 6225        let mut edits = Vec::new();
 6226        let buffer = self.buffer.read(cx);
 6227        let snapshot = buffer.snapshot(cx);
 6228        for selection in &mut selections {
 6229            if selection.start.row != prev_edited_row {
 6230                row_delta = 0;
 6231            }
 6232            prev_edited_row = selection.end.row;
 6233
 6234            row_delta =
 6235                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6236        }
 6237
 6238        self.transact(window, cx, |this, window, cx| {
 6239            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6240            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6241                s.select(selections)
 6242            });
 6243        });
 6244    }
 6245
 6246    fn indent_selection(
 6247        buffer: &MultiBuffer,
 6248        snapshot: &MultiBufferSnapshot,
 6249        selection: &mut Selection<Point>,
 6250        edits: &mut Vec<(Range<Point>, String)>,
 6251        delta_for_start_row: u32,
 6252        cx: &App,
 6253    ) -> u32 {
 6254        let settings = buffer.settings_at(selection.start, cx);
 6255        let tab_size = settings.tab_size.get();
 6256        let indent_kind = if settings.hard_tabs {
 6257            IndentKind::Tab
 6258        } else {
 6259            IndentKind::Space
 6260        };
 6261        let mut start_row = selection.start.row;
 6262        let mut end_row = selection.end.row + 1;
 6263
 6264        // If a selection ends at the beginning of a line, don't indent
 6265        // that last line.
 6266        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6267            end_row -= 1;
 6268        }
 6269
 6270        // Avoid re-indenting a row that has already been indented by a
 6271        // previous selection, but still update this selection's column
 6272        // to reflect that indentation.
 6273        if delta_for_start_row > 0 {
 6274            start_row += 1;
 6275            selection.start.column += delta_for_start_row;
 6276            if selection.end.row == selection.start.row {
 6277                selection.end.column += delta_for_start_row;
 6278            }
 6279        }
 6280
 6281        let mut delta_for_end_row = 0;
 6282        let has_multiple_rows = start_row + 1 != end_row;
 6283        for row in start_row..end_row {
 6284            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6285            let indent_delta = match (current_indent.kind, indent_kind) {
 6286                (IndentKind::Space, IndentKind::Space) => {
 6287                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6288                    IndentSize::spaces(columns_to_next_tab_stop)
 6289                }
 6290                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6291                (_, IndentKind::Tab) => IndentSize::tab(),
 6292            };
 6293
 6294            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6295                0
 6296            } else {
 6297                selection.start.column
 6298            };
 6299            let row_start = Point::new(row, start);
 6300            edits.push((
 6301                row_start..row_start,
 6302                indent_delta.chars().collect::<String>(),
 6303            ));
 6304
 6305            // Update this selection's endpoints to reflect the indentation.
 6306            if row == selection.start.row {
 6307                selection.start.column += indent_delta.len;
 6308            }
 6309            if row == selection.end.row {
 6310                selection.end.column += indent_delta.len;
 6311                delta_for_end_row = indent_delta.len;
 6312            }
 6313        }
 6314
 6315        if selection.start.row == selection.end.row {
 6316            delta_for_start_row + delta_for_end_row
 6317        } else {
 6318            delta_for_end_row
 6319        }
 6320    }
 6321
 6322    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6323        if self.read_only(cx) {
 6324            return;
 6325        }
 6326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6327        let selections = self.selections.all::<Point>(cx);
 6328        let mut deletion_ranges = Vec::new();
 6329        let mut last_outdent = None;
 6330        {
 6331            let buffer = self.buffer.read(cx);
 6332            let snapshot = buffer.snapshot(cx);
 6333            for selection in &selections {
 6334                let settings = buffer.settings_at(selection.start, cx);
 6335                let tab_size = settings.tab_size.get();
 6336                let mut rows = selection.spanned_rows(false, &display_map);
 6337
 6338                // Avoid re-outdenting a row that has already been outdented by a
 6339                // previous selection.
 6340                if let Some(last_row) = last_outdent {
 6341                    if last_row == rows.start {
 6342                        rows.start = rows.start.next_row();
 6343                    }
 6344                }
 6345                let has_multiple_rows = rows.len() > 1;
 6346                for row in rows.iter_rows() {
 6347                    let indent_size = snapshot.indent_size_for_line(row);
 6348                    if indent_size.len > 0 {
 6349                        let deletion_len = match indent_size.kind {
 6350                            IndentKind::Space => {
 6351                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6352                                if columns_to_prev_tab_stop == 0 {
 6353                                    tab_size
 6354                                } else {
 6355                                    columns_to_prev_tab_stop
 6356                                }
 6357                            }
 6358                            IndentKind::Tab => 1,
 6359                        };
 6360                        let start = if has_multiple_rows
 6361                            || deletion_len > selection.start.column
 6362                            || indent_size.len < selection.start.column
 6363                        {
 6364                            0
 6365                        } else {
 6366                            selection.start.column - deletion_len
 6367                        };
 6368                        deletion_ranges.push(
 6369                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6370                        );
 6371                        last_outdent = Some(row);
 6372                    }
 6373                }
 6374            }
 6375        }
 6376
 6377        self.transact(window, cx, |this, window, cx| {
 6378            this.buffer.update(cx, |buffer, cx| {
 6379                let empty_str: Arc<str> = Arc::default();
 6380                buffer.edit(
 6381                    deletion_ranges
 6382                        .into_iter()
 6383                        .map(|range| (range, empty_str.clone())),
 6384                    None,
 6385                    cx,
 6386                );
 6387            });
 6388            let selections = this.selections.all::<usize>(cx);
 6389            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6390                s.select(selections)
 6391            });
 6392        });
 6393    }
 6394
 6395    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6396        if self.read_only(cx) {
 6397            return;
 6398        }
 6399        let selections = self
 6400            .selections
 6401            .all::<usize>(cx)
 6402            .into_iter()
 6403            .map(|s| s.range());
 6404
 6405        self.transact(window, cx, |this, window, cx| {
 6406            this.buffer.update(cx, |buffer, cx| {
 6407                buffer.autoindent_ranges(selections, cx);
 6408            });
 6409            let selections = this.selections.all::<usize>(cx);
 6410            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6411                s.select(selections)
 6412            });
 6413        });
 6414    }
 6415
 6416    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6417        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6418        let selections = self.selections.all::<Point>(cx);
 6419
 6420        let mut new_cursors = Vec::new();
 6421        let mut edit_ranges = Vec::new();
 6422        let mut selections = selections.iter().peekable();
 6423        while let Some(selection) = selections.next() {
 6424            let mut rows = selection.spanned_rows(false, &display_map);
 6425            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6426
 6427            // Accumulate contiguous regions of rows that we want to delete.
 6428            while let Some(next_selection) = selections.peek() {
 6429                let next_rows = next_selection.spanned_rows(false, &display_map);
 6430                if next_rows.start <= rows.end {
 6431                    rows.end = next_rows.end;
 6432                    selections.next().unwrap();
 6433                } else {
 6434                    break;
 6435                }
 6436            }
 6437
 6438            let buffer = &display_map.buffer_snapshot;
 6439            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6440            let edit_end;
 6441            let cursor_buffer_row;
 6442            if buffer.max_point().row >= rows.end.0 {
 6443                // If there's a line after the range, delete the \n from the end of the row range
 6444                // and position the cursor on the next line.
 6445                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6446                cursor_buffer_row = rows.end;
 6447            } else {
 6448                // If there isn't a line after the range, delete the \n from the line before the
 6449                // start of the row range and position the cursor there.
 6450                edit_start = edit_start.saturating_sub(1);
 6451                edit_end = buffer.len();
 6452                cursor_buffer_row = rows.start.previous_row();
 6453            }
 6454
 6455            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6456            *cursor.column_mut() =
 6457                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6458
 6459            new_cursors.push((
 6460                selection.id,
 6461                buffer.anchor_after(cursor.to_point(&display_map)),
 6462            ));
 6463            edit_ranges.push(edit_start..edit_end);
 6464        }
 6465
 6466        self.transact(window, cx, |this, window, cx| {
 6467            let buffer = this.buffer.update(cx, |buffer, cx| {
 6468                let empty_str: Arc<str> = Arc::default();
 6469                buffer.edit(
 6470                    edit_ranges
 6471                        .into_iter()
 6472                        .map(|range| (range, empty_str.clone())),
 6473                    None,
 6474                    cx,
 6475                );
 6476                buffer.snapshot(cx)
 6477            });
 6478            let new_selections = new_cursors
 6479                .into_iter()
 6480                .map(|(id, cursor)| {
 6481                    let cursor = cursor.to_point(&buffer);
 6482                    Selection {
 6483                        id,
 6484                        start: cursor,
 6485                        end: cursor,
 6486                        reversed: false,
 6487                        goal: SelectionGoal::None,
 6488                    }
 6489                })
 6490                .collect();
 6491
 6492            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6493                s.select(new_selections);
 6494            });
 6495        });
 6496    }
 6497
 6498    pub fn join_lines_impl(
 6499        &mut self,
 6500        insert_whitespace: bool,
 6501        window: &mut Window,
 6502        cx: &mut Context<Self>,
 6503    ) {
 6504        if self.read_only(cx) {
 6505            return;
 6506        }
 6507        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6508        for selection in self.selections.all::<Point>(cx) {
 6509            let start = MultiBufferRow(selection.start.row);
 6510            // Treat single line selections as if they include the next line. Otherwise this action
 6511            // would do nothing for single line selections individual cursors.
 6512            let end = if selection.start.row == selection.end.row {
 6513                MultiBufferRow(selection.start.row + 1)
 6514            } else {
 6515                MultiBufferRow(selection.end.row)
 6516            };
 6517
 6518            if let Some(last_row_range) = row_ranges.last_mut() {
 6519                if start <= last_row_range.end {
 6520                    last_row_range.end = end;
 6521                    continue;
 6522                }
 6523            }
 6524            row_ranges.push(start..end);
 6525        }
 6526
 6527        let snapshot = self.buffer.read(cx).snapshot(cx);
 6528        let mut cursor_positions = Vec::new();
 6529        for row_range in &row_ranges {
 6530            let anchor = snapshot.anchor_before(Point::new(
 6531                row_range.end.previous_row().0,
 6532                snapshot.line_len(row_range.end.previous_row()),
 6533            ));
 6534            cursor_positions.push(anchor..anchor);
 6535        }
 6536
 6537        self.transact(window, cx, |this, window, cx| {
 6538            for row_range in row_ranges.into_iter().rev() {
 6539                for row in row_range.iter_rows().rev() {
 6540                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6541                    let next_line_row = row.next_row();
 6542                    let indent = snapshot.indent_size_for_line(next_line_row);
 6543                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6544
 6545                    let replace =
 6546                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6547                            " "
 6548                        } else {
 6549                            ""
 6550                        };
 6551
 6552                    this.buffer.update(cx, |buffer, cx| {
 6553                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6554                    });
 6555                }
 6556            }
 6557
 6558            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6559                s.select_anchor_ranges(cursor_positions)
 6560            });
 6561        });
 6562    }
 6563
 6564    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6565        self.join_lines_impl(true, window, cx);
 6566    }
 6567
 6568    pub fn sort_lines_case_sensitive(
 6569        &mut self,
 6570        _: &SortLinesCaseSensitive,
 6571        window: &mut Window,
 6572        cx: &mut Context<Self>,
 6573    ) {
 6574        self.manipulate_lines(window, cx, |lines| lines.sort())
 6575    }
 6576
 6577    pub fn sort_lines_case_insensitive(
 6578        &mut self,
 6579        _: &SortLinesCaseInsensitive,
 6580        window: &mut Window,
 6581        cx: &mut Context<Self>,
 6582    ) {
 6583        self.manipulate_lines(window, cx, |lines| {
 6584            lines.sort_by_key(|line| line.to_lowercase())
 6585        })
 6586    }
 6587
 6588    pub fn unique_lines_case_insensitive(
 6589        &mut self,
 6590        _: &UniqueLinesCaseInsensitive,
 6591        window: &mut Window,
 6592        cx: &mut Context<Self>,
 6593    ) {
 6594        self.manipulate_lines(window, cx, |lines| {
 6595            let mut seen = HashSet::default();
 6596            lines.retain(|line| seen.insert(line.to_lowercase()));
 6597        })
 6598    }
 6599
 6600    pub fn unique_lines_case_sensitive(
 6601        &mut self,
 6602        _: &UniqueLinesCaseSensitive,
 6603        window: &mut Window,
 6604        cx: &mut Context<Self>,
 6605    ) {
 6606        self.manipulate_lines(window, cx, |lines| {
 6607            let mut seen = HashSet::default();
 6608            lines.retain(|line| seen.insert(*line));
 6609        })
 6610    }
 6611
 6612    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6613        let mut revert_changes = HashMap::default();
 6614        let snapshot = self.snapshot(window, cx);
 6615        for hunk in snapshot
 6616            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6617        {
 6618            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6619        }
 6620        if !revert_changes.is_empty() {
 6621            self.transact(window, cx, |editor, window, cx| {
 6622                editor.revert(revert_changes, window, cx);
 6623            });
 6624        }
 6625    }
 6626
 6627    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6628        let Some(project) = self.project.clone() else {
 6629            return;
 6630        };
 6631        self.reload(project, window, cx)
 6632            .detach_and_notify_err(window, cx);
 6633    }
 6634
 6635    pub fn revert_selected_hunks(
 6636        &mut self,
 6637        _: &RevertSelectedHunks,
 6638        window: &mut Window,
 6639        cx: &mut Context<Self>,
 6640    ) {
 6641        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6642        self.revert_hunks_in_ranges(selections, window, cx);
 6643    }
 6644
 6645    fn revert_hunks_in_ranges(
 6646        &mut self,
 6647        ranges: impl Iterator<Item = Range<Point>>,
 6648        window: &mut Window,
 6649        cx: &mut Context<Editor>,
 6650    ) {
 6651        let mut revert_changes = HashMap::default();
 6652        let snapshot = self.snapshot(window, cx);
 6653        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6654            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6655        }
 6656        if !revert_changes.is_empty() {
 6657            self.transact(window, cx, |editor, window, cx| {
 6658                editor.revert(revert_changes, window, cx);
 6659            });
 6660        }
 6661    }
 6662
 6663    pub fn open_active_item_in_terminal(
 6664        &mut self,
 6665        _: &OpenInTerminal,
 6666        window: &mut Window,
 6667        cx: &mut Context<Self>,
 6668    ) {
 6669        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6670            let project_path = buffer.read(cx).project_path(cx)?;
 6671            let project = self.project.as_ref()?.read(cx);
 6672            let entry = project.entry_for_path(&project_path, cx)?;
 6673            let parent = match &entry.canonical_path {
 6674                Some(canonical_path) => canonical_path.to_path_buf(),
 6675                None => project.absolute_path(&project_path, cx)?,
 6676            }
 6677            .parent()?
 6678            .to_path_buf();
 6679            Some(parent)
 6680        }) {
 6681            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6682        }
 6683    }
 6684
 6685    pub fn prepare_revert_change(
 6686        &self,
 6687        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6688        hunk: &MultiBufferDiffHunk,
 6689        cx: &mut App,
 6690    ) -> Option<()> {
 6691        let buffer = self.buffer.read(cx);
 6692        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6693        let buffer = buffer.buffer(hunk.buffer_id)?;
 6694        let buffer = buffer.read(cx);
 6695        let original_text = change_set
 6696            .read(cx)
 6697            .base_text
 6698            .as_ref()?
 6699            .as_rope()
 6700            .slice(hunk.diff_base_byte_range.clone());
 6701        let buffer_snapshot = buffer.snapshot();
 6702        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6703        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6704            probe
 6705                .0
 6706                .start
 6707                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6708                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6709        }) {
 6710            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6711            Some(())
 6712        } else {
 6713            None
 6714        }
 6715    }
 6716
 6717    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6718        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6719    }
 6720
 6721    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6722        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6723    }
 6724
 6725    fn manipulate_lines<Fn>(
 6726        &mut self,
 6727        window: &mut Window,
 6728        cx: &mut Context<Self>,
 6729        mut callback: Fn,
 6730    ) where
 6731        Fn: FnMut(&mut Vec<&str>),
 6732    {
 6733        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6734        let buffer = self.buffer.read(cx).snapshot(cx);
 6735
 6736        let mut edits = Vec::new();
 6737
 6738        let selections = self.selections.all::<Point>(cx);
 6739        let mut selections = selections.iter().peekable();
 6740        let mut contiguous_row_selections = Vec::new();
 6741        let mut new_selections = Vec::new();
 6742        let mut added_lines = 0;
 6743        let mut removed_lines = 0;
 6744
 6745        while let Some(selection) = selections.next() {
 6746            let (start_row, end_row) = consume_contiguous_rows(
 6747                &mut contiguous_row_selections,
 6748                selection,
 6749                &display_map,
 6750                &mut selections,
 6751            );
 6752
 6753            let start_point = Point::new(start_row.0, 0);
 6754            let end_point = Point::new(
 6755                end_row.previous_row().0,
 6756                buffer.line_len(end_row.previous_row()),
 6757            );
 6758            let text = buffer
 6759                .text_for_range(start_point..end_point)
 6760                .collect::<String>();
 6761
 6762            let mut lines = text.split('\n').collect_vec();
 6763
 6764            let lines_before = lines.len();
 6765            callback(&mut lines);
 6766            let lines_after = lines.len();
 6767
 6768            edits.push((start_point..end_point, lines.join("\n")));
 6769
 6770            // Selections must change based on added and removed line count
 6771            let start_row =
 6772                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6773            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6774            new_selections.push(Selection {
 6775                id: selection.id,
 6776                start: start_row,
 6777                end: end_row,
 6778                goal: SelectionGoal::None,
 6779                reversed: selection.reversed,
 6780            });
 6781
 6782            if lines_after > lines_before {
 6783                added_lines += lines_after - lines_before;
 6784            } else if lines_before > lines_after {
 6785                removed_lines += lines_before - lines_after;
 6786            }
 6787        }
 6788
 6789        self.transact(window, cx, |this, window, cx| {
 6790            let buffer = this.buffer.update(cx, |buffer, cx| {
 6791                buffer.edit(edits, None, cx);
 6792                buffer.snapshot(cx)
 6793            });
 6794
 6795            // Recalculate offsets on newly edited buffer
 6796            let new_selections = new_selections
 6797                .iter()
 6798                .map(|s| {
 6799                    let start_point = Point::new(s.start.0, 0);
 6800                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6801                    Selection {
 6802                        id: s.id,
 6803                        start: buffer.point_to_offset(start_point),
 6804                        end: buffer.point_to_offset(end_point),
 6805                        goal: s.goal,
 6806                        reversed: s.reversed,
 6807                    }
 6808                })
 6809                .collect();
 6810
 6811            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6812                s.select(new_selections);
 6813            });
 6814
 6815            this.request_autoscroll(Autoscroll::fit(), cx);
 6816        });
 6817    }
 6818
 6819    pub fn convert_to_upper_case(
 6820        &mut self,
 6821        _: &ConvertToUpperCase,
 6822        window: &mut Window,
 6823        cx: &mut Context<Self>,
 6824    ) {
 6825        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6826    }
 6827
 6828    pub fn convert_to_lower_case(
 6829        &mut self,
 6830        _: &ConvertToLowerCase,
 6831        window: &mut Window,
 6832        cx: &mut Context<Self>,
 6833    ) {
 6834        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6835    }
 6836
 6837    pub fn convert_to_title_case(
 6838        &mut self,
 6839        _: &ConvertToTitleCase,
 6840        window: &mut Window,
 6841        cx: &mut Context<Self>,
 6842    ) {
 6843        self.manipulate_text(window, cx, |text| {
 6844            text.split('\n')
 6845                .map(|line| line.to_case(Case::Title))
 6846                .join("\n")
 6847        })
 6848    }
 6849
 6850    pub fn convert_to_snake_case(
 6851        &mut self,
 6852        _: &ConvertToSnakeCase,
 6853        window: &mut Window,
 6854        cx: &mut Context<Self>,
 6855    ) {
 6856        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6857    }
 6858
 6859    pub fn convert_to_kebab_case(
 6860        &mut self,
 6861        _: &ConvertToKebabCase,
 6862        window: &mut Window,
 6863        cx: &mut Context<Self>,
 6864    ) {
 6865        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6866    }
 6867
 6868    pub fn convert_to_upper_camel_case(
 6869        &mut self,
 6870        _: &ConvertToUpperCamelCase,
 6871        window: &mut Window,
 6872        cx: &mut Context<Self>,
 6873    ) {
 6874        self.manipulate_text(window, cx, |text| {
 6875            text.split('\n')
 6876                .map(|line| line.to_case(Case::UpperCamel))
 6877                .join("\n")
 6878        })
 6879    }
 6880
 6881    pub fn convert_to_lower_camel_case(
 6882        &mut self,
 6883        _: &ConvertToLowerCamelCase,
 6884        window: &mut Window,
 6885        cx: &mut Context<Self>,
 6886    ) {
 6887        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6888    }
 6889
 6890    pub fn convert_to_opposite_case(
 6891        &mut self,
 6892        _: &ConvertToOppositeCase,
 6893        window: &mut Window,
 6894        cx: &mut Context<Self>,
 6895    ) {
 6896        self.manipulate_text(window, cx, |text| {
 6897            text.chars()
 6898                .fold(String::with_capacity(text.len()), |mut t, c| {
 6899                    if c.is_uppercase() {
 6900                        t.extend(c.to_lowercase());
 6901                    } else {
 6902                        t.extend(c.to_uppercase());
 6903                    }
 6904                    t
 6905                })
 6906        })
 6907    }
 6908
 6909    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6910    where
 6911        Fn: FnMut(&str) -> String,
 6912    {
 6913        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6914        let buffer = self.buffer.read(cx).snapshot(cx);
 6915
 6916        let mut new_selections = Vec::new();
 6917        let mut edits = Vec::new();
 6918        let mut selection_adjustment = 0i32;
 6919
 6920        for selection in self.selections.all::<usize>(cx) {
 6921            let selection_is_empty = selection.is_empty();
 6922
 6923            let (start, end) = if selection_is_empty {
 6924                let word_range = movement::surrounding_word(
 6925                    &display_map,
 6926                    selection.start.to_display_point(&display_map),
 6927                );
 6928                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6929                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6930                (start, end)
 6931            } else {
 6932                (selection.start, selection.end)
 6933            };
 6934
 6935            let text = buffer.text_for_range(start..end).collect::<String>();
 6936            let old_length = text.len() as i32;
 6937            let text = callback(&text);
 6938
 6939            new_selections.push(Selection {
 6940                start: (start as i32 - selection_adjustment) as usize,
 6941                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6942                goal: SelectionGoal::None,
 6943                ..selection
 6944            });
 6945
 6946            selection_adjustment += old_length - text.len() as i32;
 6947
 6948            edits.push((start..end, text));
 6949        }
 6950
 6951        self.transact(window, cx, |this, window, cx| {
 6952            this.buffer.update(cx, |buffer, cx| {
 6953                buffer.edit(edits, None, cx);
 6954            });
 6955
 6956            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6957                s.select(new_selections);
 6958            });
 6959
 6960            this.request_autoscroll(Autoscroll::fit(), cx);
 6961        });
 6962    }
 6963
 6964    pub fn duplicate(
 6965        &mut self,
 6966        upwards: bool,
 6967        whole_lines: bool,
 6968        window: &mut Window,
 6969        cx: &mut Context<Self>,
 6970    ) {
 6971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6972        let buffer = &display_map.buffer_snapshot;
 6973        let selections = self.selections.all::<Point>(cx);
 6974
 6975        let mut edits = Vec::new();
 6976        let mut selections_iter = selections.iter().peekable();
 6977        while let Some(selection) = selections_iter.next() {
 6978            let mut rows = selection.spanned_rows(false, &display_map);
 6979            // duplicate line-wise
 6980            if whole_lines || selection.start == selection.end {
 6981                // Avoid duplicating the same lines twice.
 6982                while let Some(next_selection) = selections_iter.peek() {
 6983                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6984                    if next_rows.start < rows.end {
 6985                        rows.end = next_rows.end;
 6986                        selections_iter.next().unwrap();
 6987                    } else {
 6988                        break;
 6989                    }
 6990                }
 6991
 6992                // Copy the text from the selected row region and splice it either at the start
 6993                // or end of the region.
 6994                let start = Point::new(rows.start.0, 0);
 6995                let end = Point::new(
 6996                    rows.end.previous_row().0,
 6997                    buffer.line_len(rows.end.previous_row()),
 6998                );
 6999                let text = buffer
 7000                    .text_for_range(start..end)
 7001                    .chain(Some("\n"))
 7002                    .collect::<String>();
 7003                let insert_location = if upwards {
 7004                    Point::new(rows.end.0, 0)
 7005                } else {
 7006                    start
 7007                };
 7008                edits.push((insert_location..insert_location, text));
 7009            } else {
 7010                // duplicate character-wise
 7011                let start = selection.start;
 7012                let end = selection.end;
 7013                let text = buffer.text_for_range(start..end).collect::<String>();
 7014                edits.push((selection.end..selection.end, text));
 7015            }
 7016        }
 7017
 7018        self.transact(window, cx, |this, _, cx| {
 7019            this.buffer.update(cx, |buffer, cx| {
 7020                buffer.edit(edits, None, cx);
 7021            });
 7022
 7023            this.request_autoscroll(Autoscroll::fit(), cx);
 7024        });
 7025    }
 7026
 7027    pub fn duplicate_line_up(
 7028        &mut self,
 7029        _: &DuplicateLineUp,
 7030        window: &mut Window,
 7031        cx: &mut Context<Self>,
 7032    ) {
 7033        self.duplicate(true, true, window, cx);
 7034    }
 7035
 7036    pub fn duplicate_line_down(
 7037        &mut self,
 7038        _: &DuplicateLineDown,
 7039        window: &mut Window,
 7040        cx: &mut Context<Self>,
 7041    ) {
 7042        self.duplicate(false, true, window, cx);
 7043    }
 7044
 7045    pub fn duplicate_selection(
 7046        &mut self,
 7047        _: &DuplicateSelection,
 7048        window: &mut Window,
 7049        cx: &mut Context<Self>,
 7050    ) {
 7051        self.duplicate(false, false, window, cx);
 7052    }
 7053
 7054    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7055        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7056        let buffer = self.buffer.read(cx).snapshot(cx);
 7057
 7058        let mut edits = Vec::new();
 7059        let mut unfold_ranges = Vec::new();
 7060        let mut refold_creases = Vec::new();
 7061
 7062        let selections = self.selections.all::<Point>(cx);
 7063        let mut selections = selections.iter().peekable();
 7064        let mut contiguous_row_selections = Vec::new();
 7065        let mut new_selections = Vec::new();
 7066
 7067        while let Some(selection) = selections.next() {
 7068            // Find all the selections that span a contiguous row range
 7069            let (start_row, end_row) = consume_contiguous_rows(
 7070                &mut contiguous_row_selections,
 7071                selection,
 7072                &display_map,
 7073                &mut selections,
 7074            );
 7075
 7076            // Move the text spanned by the row range to be before the line preceding the row range
 7077            if start_row.0 > 0 {
 7078                let range_to_move = Point::new(
 7079                    start_row.previous_row().0,
 7080                    buffer.line_len(start_row.previous_row()),
 7081                )
 7082                    ..Point::new(
 7083                        end_row.previous_row().0,
 7084                        buffer.line_len(end_row.previous_row()),
 7085                    );
 7086                let insertion_point = display_map
 7087                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7088                    .0;
 7089
 7090                // Don't move lines across excerpts
 7091                if buffer
 7092                    .excerpt_containing(insertion_point..range_to_move.end)
 7093                    .is_some()
 7094                {
 7095                    let text = buffer
 7096                        .text_for_range(range_to_move.clone())
 7097                        .flat_map(|s| s.chars())
 7098                        .skip(1)
 7099                        .chain(['\n'])
 7100                        .collect::<String>();
 7101
 7102                    edits.push((
 7103                        buffer.anchor_after(range_to_move.start)
 7104                            ..buffer.anchor_before(range_to_move.end),
 7105                        String::new(),
 7106                    ));
 7107                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7108                    edits.push((insertion_anchor..insertion_anchor, text));
 7109
 7110                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7111
 7112                    // Move selections up
 7113                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7114                        |mut selection| {
 7115                            selection.start.row -= row_delta;
 7116                            selection.end.row -= row_delta;
 7117                            selection
 7118                        },
 7119                    ));
 7120
 7121                    // Move folds up
 7122                    unfold_ranges.push(range_to_move.clone());
 7123                    for fold in display_map.folds_in_range(
 7124                        buffer.anchor_before(range_to_move.start)
 7125                            ..buffer.anchor_after(range_to_move.end),
 7126                    ) {
 7127                        let mut start = fold.range.start.to_point(&buffer);
 7128                        let mut end = fold.range.end.to_point(&buffer);
 7129                        start.row -= row_delta;
 7130                        end.row -= row_delta;
 7131                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7132                    }
 7133                }
 7134            }
 7135
 7136            // If we didn't move line(s), preserve the existing selections
 7137            new_selections.append(&mut contiguous_row_selections);
 7138        }
 7139
 7140        self.transact(window, cx, |this, window, cx| {
 7141            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7142            this.buffer.update(cx, |buffer, cx| {
 7143                for (range, text) in edits {
 7144                    buffer.edit([(range, text)], None, cx);
 7145                }
 7146            });
 7147            this.fold_creases(refold_creases, true, window, cx);
 7148            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7149                s.select(new_selections);
 7150            })
 7151        });
 7152    }
 7153
 7154    pub fn move_line_down(
 7155        &mut self,
 7156        _: &MoveLineDown,
 7157        window: &mut Window,
 7158        cx: &mut Context<Self>,
 7159    ) {
 7160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7161        let buffer = self.buffer.read(cx).snapshot(cx);
 7162
 7163        let mut edits = Vec::new();
 7164        let mut unfold_ranges = Vec::new();
 7165        let mut refold_creases = Vec::new();
 7166
 7167        let selections = self.selections.all::<Point>(cx);
 7168        let mut selections = selections.iter().peekable();
 7169        let mut contiguous_row_selections = Vec::new();
 7170        let mut new_selections = Vec::new();
 7171
 7172        while let Some(selection) = selections.next() {
 7173            // Find all the selections that span a contiguous row range
 7174            let (start_row, end_row) = consume_contiguous_rows(
 7175                &mut contiguous_row_selections,
 7176                selection,
 7177                &display_map,
 7178                &mut selections,
 7179            );
 7180
 7181            // Move the text spanned by the row range to be after the last line of the row range
 7182            if end_row.0 <= buffer.max_point().row {
 7183                let range_to_move =
 7184                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7185                let insertion_point = display_map
 7186                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7187                    .0;
 7188
 7189                // Don't move lines across excerpt boundaries
 7190                if buffer
 7191                    .excerpt_containing(range_to_move.start..insertion_point)
 7192                    .is_some()
 7193                {
 7194                    let mut text = String::from("\n");
 7195                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7196                    text.pop(); // Drop trailing newline
 7197                    edits.push((
 7198                        buffer.anchor_after(range_to_move.start)
 7199                            ..buffer.anchor_before(range_to_move.end),
 7200                        String::new(),
 7201                    ));
 7202                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7203                    edits.push((insertion_anchor..insertion_anchor, text));
 7204
 7205                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7206
 7207                    // Move selections down
 7208                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7209                        |mut selection| {
 7210                            selection.start.row += row_delta;
 7211                            selection.end.row += row_delta;
 7212                            selection
 7213                        },
 7214                    ));
 7215
 7216                    // Move folds down
 7217                    unfold_ranges.push(range_to_move.clone());
 7218                    for fold in display_map.folds_in_range(
 7219                        buffer.anchor_before(range_to_move.start)
 7220                            ..buffer.anchor_after(range_to_move.end),
 7221                    ) {
 7222                        let mut start = fold.range.start.to_point(&buffer);
 7223                        let mut end = fold.range.end.to_point(&buffer);
 7224                        start.row += row_delta;
 7225                        end.row += row_delta;
 7226                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7227                    }
 7228                }
 7229            }
 7230
 7231            // If we didn't move line(s), preserve the existing selections
 7232            new_selections.append(&mut contiguous_row_selections);
 7233        }
 7234
 7235        self.transact(window, cx, |this, window, cx| {
 7236            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7237            this.buffer.update(cx, |buffer, cx| {
 7238                for (range, text) in edits {
 7239                    buffer.edit([(range, text)], None, cx);
 7240                }
 7241            });
 7242            this.fold_creases(refold_creases, true, window, cx);
 7243            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7244                s.select(new_selections)
 7245            });
 7246        });
 7247    }
 7248
 7249    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7250        let text_layout_details = &self.text_layout_details(window);
 7251        self.transact(window, cx, |this, window, cx| {
 7252            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7253                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7254                let line_mode = s.line_mode;
 7255                s.move_with(|display_map, selection| {
 7256                    if !selection.is_empty() || line_mode {
 7257                        return;
 7258                    }
 7259
 7260                    let mut head = selection.head();
 7261                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7262                    if head.column() == display_map.line_len(head.row()) {
 7263                        transpose_offset = display_map
 7264                            .buffer_snapshot
 7265                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7266                    }
 7267
 7268                    if transpose_offset == 0 {
 7269                        return;
 7270                    }
 7271
 7272                    *head.column_mut() += 1;
 7273                    head = display_map.clip_point(head, Bias::Right);
 7274                    let goal = SelectionGoal::HorizontalPosition(
 7275                        display_map
 7276                            .x_for_display_point(head, text_layout_details)
 7277                            .into(),
 7278                    );
 7279                    selection.collapse_to(head, goal);
 7280
 7281                    let transpose_start = display_map
 7282                        .buffer_snapshot
 7283                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7284                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7285                        let transpose_end = display_map
 7286                            .buffer_snapshot
 7287                            .clip_offset(transpose_offset + 1, Bias::Right);
 7288                        if let Some(ch) =
 7289                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7290                        {
 7291                            edits.push((transpose_start..transpose_offset, String::new()));
 7292                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7293                        }
 7294                    }
 7295                });
 7296                edits
 7297            });
 7298            this.buffer
 7299                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7300            let selections = this.selections.all::<usize>(cx);
 7301            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7302                s.select(selections);
 7303            });
 7304        });
 7305    }
 7306
 7307    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7308        self.rewrap_impl(IsVimMode::No, cx)
 7309    }
 7310
 7311    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7312        let buffer = self.buffer.read(cx).snapshot(cx);
 7313        let selections = self.selections.all::<Point>(cx);
 7314        let mut selections = selections.iter().peekable();
 7315
 7316        let mut edits = Vec::new();
 7317        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7318
 7319        while let Some(selection) = selections.next() {
 7320            let mut start_row = selection.start.row;
 7321            let mut end_row = selection.end.row;
 7322
 7323            // Skip selections that overlap with a range that has already been rewrapped.
 7324            let selection_range = start_row..end_row;
 7325            if rewrapped_row_ranges
 7326                .iter()
 7327                .any(|range| range.overlaps(&selection_range))
 7328            {
 7329                continue;
 7330            }
 7331
 7332            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7333
 7334            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7335                match language_scope.language_name().as_ref() {
 7336                    "Markdown" | "Plain Text" => {
 7337                        should_rewrap = true;
 7338                    }
 7339                    _ => {}
 7340                }
 7341            }
 7342
 7343            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7344
 7345            // Since not all lines in the selection may be at the same indent
 7346            // level, choose the indent size that is the most common between all
 7347            // of the lines.
 7348            //
 7349            // If there is a tie, we use the deepest indent.
 7350            let (indent_size, indent_end) = {
 7351                let mut indent_size_occurrences = HashMap::default();
 7352                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7353
 7354                for row in start_row..=end_row {
 7355                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7356                    rows_by_indent_size.entry(indent).or_default().push(row);
 7357                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7358                }
 7359
 7360                let indent_size = indent_size_occurrences
 7361                    .into_iter()
 7362                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7363                    .map(|(indent, _)| indent)
 7364                    .unwrap_or_default();
 7365                let row = rows_by_indent_size[&indent_size][0];
 7366                let indent_end = Point::new(row, indent_size.len);
 7367
 7368                (indent_size, indent_end)
 7369            };
 7370
 7371            let mut line_prefix = indent_size.chars().collect::<String>();
 7372
 7373            if let Some(comment_prefix) =
 7374                buffer
 7375                    .language_scope_at(selection.head())
 7376                    .and_then(|language| {
 7377                        language
 7378                            .line_comment_prefixes()
 7379                            .iter()
 7380                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7381                            .cloned()
 7382                    })
 7383            {
 7384                line_prefix.push_str(&comment_prefix);
 7385                should_rewrap = true;
 7386            }
 7387
 7388            if !should_rewrap {
 7389                continue;
 7390            }
 7391
 7392            if selection.is_empty() {
 7393                'expand_upwards: while start_row > 0 {
 7394                    let prev_row = start_row - 1;
 7395                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7396                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7397                    {
 7398                        start_row = prev_row;
 7399                    } else {
 7400                        break 'expand_upwards;
 7401                    }
 7402                }
 7403
 7404                'expand_downwards: while end_row < buffer.max_point().row {
 7405                    let next_row = end_row + 1;
 7406                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7407                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7408                    {
 7409                        end_row = next_row;
 7410                    } else {
 7411                        break 'expand_downwards;
 7412                    }
 7413                }
 7414            }
 7415
 7416            let start = Point::new(start_row, 0);
 7417            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7418            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7419            let Some(lines_without_prefixes) = selection_text
 7420                .lines()
 7421                .map(|line| {
 7422                    line.strip_prefix(&line_prefix)
 7423                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7424                        .ok_or_else(|| {
 7425                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7426                        })
 7427                })
 7428                .collect::<Result<Vec<_>, _>>()
 7429                .log_err()
 7430            else {
 7431                continue;
 7432            };
 7433
 7434            let wrap_column = buffer
 7435                .settings_at(Point::new(start_row, 0), cx)
 7436                .preferred_line_length as usize;
 7437            let wrapped_text = wrap_with_prefix(
 7438                line_prefix,
 7439                lines_without_prefixes.join(" "),
 7440                wrap_column,
 7441                tab_size,
 7442            );
 7443
 7444            // TODO: should always use char-based diff while still supporting cursor behavior that
 7445            // matches vim.
 7446            let diff = match is_vim_mode {
 7447                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7448                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7449            };
 7450            let mut offset = start.to_offset(&buffer);
 7451            let mut moved_since_edit = true;
 7452
 7453            for change in diff.iter_all_changes() {
 7454                let value = change.value();
 7455                match change.tag() {
 7456                    ChangeTag::Equal => {
 7457                        offset += value.len();
 7458                        moved_since_edit = true;
 7459                    }
 7460                    ChangeTag::Delete => {
 7461                        let start = buffer.anchor_after(offset);
 7462                        let end = buffer.anchor_before(offset + value.len());
 7463
 7464                        if moved_since_edit {
 7465                            edits.push((start..end, String::new()));
 7466                        } else {
 7467                            edits.last_mut().unwrap().0.end = end;
 7468                        }
 7469
 7470                        offset += value.len();
 7471                        moved_since_edit = false;
 7472                    }
 7473                    ChangeTag::Insert => {
 7474                        if moved_since_edit {
 7475                            let anchor = buffer.anchor_after(offset);
 7476                            edits.push((anchor..anchor, value.to_string()));
 7477                        } else {
 7478                            edits.last_mut().unwrap().1.push_str(value);
 7479                        }
 7480
 7481                        moved_since_edit = false;
 7482                    }
 7483                }
 7484            }
 7485
 7486            rewrapped_row_ranges.push(start_row..=end_row);
 7487        }
 7488
 7489        self.buffer
 7490            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7491    }
 7492
 7493    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7494        let mut text = String::new();
 7495        let buffer = self.buffer.read(cx).snapshot(cx);
 7496        let mut selections = self.selections.all::<Point>(cx);
 7497        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7498        {
 7499            let max_point = buffer.max_point();
 7500            let mut is_first = true;
 7501            for selection in &mut selections {
 7502                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7503                if is_entire_line {
 7504                    selection.start = Point::new(selection.start.row, 0);
 7505                    if !selection.is_empty() && selection.end.column == 0 {
 7506                        selection.end = cmp::min(max_point, selection.end);
 7507                    } else {
 7508                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7509                    }
 7510                    selection.goal = SelectionGoal::None;
 7511                }
 7512                if is_first {
 7513                    is_first = false;
 7514                } else {
 7515                    text += "\n";
 7516                }
 7517                let mut len = 0;
 7518                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7519                    text.push_str(chunk);
 7520                    len += chunk.len();
 7521                }
 7522                clipboard_selections.push(ClipboardSelection {
 7523                    len,
 7524                    is_entire_line,
 7525                    first_line_indent: buffer
 7526                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7527                        .len,
 7528                });
 7529            }
 7530        }
 7531
 7532        self.transact(window, cx, |this, window, cx| {
 7533            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7534                s.select(selections);
 7535            });
 7536            this.insert("", window, cx);
 7537        });
 7538        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7539    }
 7540
 7541    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7542        let item = self.cut_common(window, cx);
 7543        cx.write_to_clipboard(item);
 7544    }
 7545
 7546    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7547        self.change_selections(None, window, cx, |s| {
 7548            s.move_with(|snapshot, sel| {
 7549                if sel.is_empty() {
 7550                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7551                }
 7552            });
 7553        });
 7554        let item = self.cut_common(window, cx);
 7555        cx.set_global(KillRing(item))
 7556    }
 7557
 7558    pub fn kill_ring_yank(
 7559        &mut self,
 7560        _: &KillRingYank,
 7561        window: &mut Window,
 7562        cx: &mut Context<Self>,
 7563    ) {
 7564        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7565            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7566                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7567            } else {
 7568                return;
 7569            }
 7570        } else {
 7571            return;
 7572        };
 7573        self.do_paste(&text, metadata, false, window, cx);
 7574    }
 7575
 7576    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7577        let selections = self.selections.all::<Point>(cx);
 7578        let buffer = self.buffer.read(cx).read(cx);
 7579        let mut text = String::new();
 7580
 7581        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7582        {
 7583            let max_point = buffer.max_point();
 7584            let mut is_first = true;
 7585            for selection in selections.iter() {
 7586                let mut start = selection.start;
 7587                let mut end = selection.end;
 7588                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7589                if is_entire_line {
 7590                    start = Point::new(start.row, 0);
 7591                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7592                }
 7593                if is_first {
 7594                    is_first = false;
 7595                } else {
 7596                    text += "\n";
 7597                }
 7598                let mut len = 0;
 7599                for chunk in buffer.text_for_range(start..end) {
 7600                    text.push_str(chunk);
 7601                    len += chunk.len();
 7602                }
 7603                clipboard_selections.push(ClipboardSelection {
 7604                    len,
 7605                    is_entire_line,
 7606                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7607                });
 7608            }
 7609        }
 7610
 7611        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7612            text,
 7613            clipboard_selections,
 7614        ));
 7615    }
 7616
 7617    pub fn do_paste(
 7618        &mut self,
 7619        text: &String,
 7620        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7621        handle_entire_lines: bool,
 7622        window: &mut Window,
 7623        cx: &mut Context<Self>,
 7624    ) {
 7625        if self.read_only(cx) {
 7626            return;
 7627        }
 7628
 7629        let clipboard_text = Cow::Borrowed(text);
 7630
 7631        self.transact(window, cx, |this, window, cx| {
 7632            if let Some(mut clipboard_selections) = clipboard_selections {
 7633                let old_selections = this.selections.all::<usize>(cx);
 7634                let all_selections_were_entire_line =
 7635                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7636                let first_selection_indent_column =
 7637                    clipboard_selections.first().map(|s| s.first_line_indent);
 7638                if clipboard_selections.len() != old_selections.len() {
 7639                    clipboard_selections.drain(..);
 7640                }
 7641                let cursor_offset = this.selections.last::<usize>(cx).head();
 7642                let mut auto_indent_on_paste = true;
 7643
 7644                this.buffer.update(cx, |buffer, cx| {
 7645                    let snapshot = buffer.read(cx);
 7646                    auto_indent_on_paste =
 7647                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7648
 7649                    let mut start_offset = 0;
 7650                    let mut edits = Vec::new();
 7651                    let mut original_indent_columns = Vec::new();
 7652                    for (ix, selection) in old_selections.iter().enumerate() {
 7653                        let to_insert;
 7654                        let entire_line;
 7655                        let original_indent_column;
 7656                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7657                            let end_offset = start_offset + clipboard_selection.len;
 7658                            to_insert = &clipboard_text[start_offset..end_offset];
 7659                            entire_line = clipboard_selection.is_entire_line;
 7660                            start_offset = end_offset + 1;
 7661                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7662                        } else {
 7663                            to_insert = clipboard_text.as_str();
 7664                            entire_line = all_selections_were_entire_line;
 7665                            original_indent_column = first_selection_indent_column
 7666                        }
 7667
 7668                        // If the corresponding selection was empty when this slice of the
 7669                        // clipboard text was written, then the entire line containing the
 7670                        // selection was copied. If this selection is also currently empty,
 7671                        // then paste the line before the current line of the buffer.
 7672                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7673                            let column = selection.start.to_point(&snapshot).column as usize;
 7674                            let line_start = selection.start - column;
 7675                            line_start..line_start
 7676                        } else {
 7677                            selection.range()
 7678                        };
 7679
 7680                        edits.push((range, to_insert));
 7681                        original_indent_columns.extend(original_indent_column);
 7682                    }
 7683                    drop(snapshot);
 7684
 7685                    buffer.edit(
 7686                        edits,
 7687                        if auto_indent_on_paste {
 7688                            Some(AutoindentMode::Block {
 7689                                original_indent_columns,
 7690                            })
 7691                        } else {
 7692                            None
 7693                        },
 7694                        cx,
 7695                    );
 7696                });
 7697
 7698                let selections = this.selections.all::<usize>(cx);
 7699                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7700                    s.select(selections)
 7701                });
 7702            } else {
 7703                this.insert(&clipboard_text, window, cx);
 7704            }
 7705        });
 7706    }
 7707
 7708    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7709        if let Some(item) = cx.read_from_clipboard() {
 7710            let entries = item.entries();
 7711
 7712            match entries.first() {
 7713                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7714                // of all the pasted entries.
 7715                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7716                    .do_paste(
 7717                        clipboard_string.text(),
 7718                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7719                        true,
 7720                        window,
 7721                        cx,
 7722                    ),
 7723                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7724            }
 7725        }
 7726    }
 7727
 7728    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7729        if self.read_only(cx) {
 7730            return;
 7731        }
 7732
 7733        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7734            if let Some((selections, _)) =
 7735                self.selection_history.transaction(transaction_id).cloned()
 7736            {
 7737                self.change_selections(None, window, cx, |s| {
 7738                    s.select_anchors(selections.to_vec());
 7739                });
 7740            }
 7741            self.request_autoscroll(Autoscroll::fit(), cx);
 7742            self.unmark_text(window, cx);
 7743            self.refresh_inline_completion(true, false, window, cx);
 7744            cx.emit(EditorEvent::Edited { transaction_id });
 7745            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7746        }
 7747    }
 7748
 7749    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7750        if self.read_only(cx) {
 7751            return;
 7752        }
 7753
 7754        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7755            if let Some((_, Some(selections))) =
 7756                self.selection_history.transaction(transaction_id).cloned()
 7757            {
 7758                self.change_selections(None, window, cx, |s| {
 7759                    s.select_anchors(selections.to_vec());
 7760                });
 7761            }
 7762            self.request_autoscroll(Autoscroll::fit(), cx);
 7763            self.unmark_text(window, cx);
 7764            self.refresh_inline_completion(true, false, window, cx);
 7765            cx.emit(EditorEvent::Edited { transaction_id });
 7766        }
 7767    }
 7768
 7769    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7770        self.buffer
 7771            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7772    }
 7773
 7774    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7775        self.buffer
 7776            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7777    }
 7778
 7779    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7780        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7781            let line_mode = s.line_mode;
 7782            s.move_with(|map, selection| {
 7783                let cursor = if selection.is_empty() && !line_mode {
 7784                    movement::left(map, selection.start)
 7785                } else {
 7786                    selection.start
 7787                };
 7788                selection.collapse_to(cursor, SelectionGoal::None);
 7789            });
 7790        })
 7791    }
 7792
 7793    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7795            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7796        })
 7797    }
 7798
 7799    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7800        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7801            let line_mode = s.line_mode;
 7802            s.move_with(|map, selection| {
 7803                let cursor = if selection.is_empty() && !line_mode {
 7804                    movement::right(map, selection.end)
 7805                } else {
 7806                    selection.end
 7807                };
 7808                selection.collapse_to(cursor, SelectionGoal::None)
 7809            });
 7810        })
 7811    }
 7812
 7813    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7815            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7816        })
 7817    }
 7818
 7819    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7820        if self.take_rename(true, window, cx).is_some() {
 7821            return;
 7822        }
 7823
 7824        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7825            cx.propagate();
 7826            return;
 7827        }
 7828
 7829        let text_layout_details = &self.text_layout_details(window);
 7830        let selection_count = self.selections.count();
 7831        let first_selection = self.selections.first_anchor();
 7832
 7833        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7834            let line_mode = s.line_mode;
 7835            s.move_with(|map, selection| {
 7836                if !selection.is_empty() && !line_mode {
 7837                    selection.goal = SelectionGoal::None;
 7838                }
 7839                let (cursor, goal) = movement::up(
 7840                    map,
 7841                    selection.start,
 7842                    selection.goal,
 7843                    false,
 7844                    text_layout_details,
 7845                );
 7846                selection.collapse_to(cursor, goal);
 7847            });
 7848        });
 7849
 7850        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7851        {
 7852            cx.propagate();
 7853        }
 7854    }
 7855
 7856    pub fn move_up_by_lines(
 7857        &mut self,
 7858        action: &MoveUpByLines,
 7859        window: &mut Window,
 7860        cx: &mut Context<Self>,
 7861    ) {
 7862        if self.take_rename(true, window, cx).is_some() {
 7863            return;
 7864        }
 7865
 7866        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7867            cx.propagate();
 7868            return;
 7869        }
 7870
 7871        let text_layout_details = &self.text_layout_details(window);
 7872
 7873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7874            let line_mode = s.line_mode;
 7875            s.move_with(|map, selection| {
 7876                if !selection.is_empty() && !line_mode {
 7877                    selection.goal = SelectionGoal::None;
 7878                }
 7879                let (cursor, goal) = movement::up_by_rows(
 7880                    map,
 7881                    selection.start,
 7882                    action.lines,
 7883                    selection.goal,
 7884                    false,
 7885                    text_layout_details,
 7886                );
 7887                selection.collapse_to(cursor, goal);
 7888            });
 7889        })
 7890    }
 7891
 7892    pub fn move_down_by_lines(
 7893        &mut self,
 7894        action: &MoveDownByLines,
 7895        window: &mut Window,
 7896        cx: &mut Context<Self>,
 7897    ) {
 7898        if self.take_rename(true, window, cx).is_some() {
 7899            return;
 7900        }
 7901
 7902        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7903            cx.propagate();
 7904            return;
 7905        }
 7906
 7907        let text_layout_details = &self.text_layout_details(window);
 7908
 7909        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7910            let line_mode = s.line_mode;
 7911            s.move_with(|map, selection| {
 7912                if !selection.is_empty() && !line_mode {
 7913                    selection.goal = SelectionGoal::None;
 7914                }
 7915                let (cursor, goal) = movement::down_by_rows(
 7916                    map,
 7917                    selection.start,
 7918                    action.lines,
 7919                    selection.goal,
 7920                    false,
 7921                    text_layout_details,
 7922                );
 7923                selection.collapse_to(cursor, goal);
 7924            });
 7925        })
 7926    }
 7927
 7928    pub fn select_down_by_lines(
 7929        &mut self,
 7930        action: &SelectDownByLines,
 7931        window: &mut Window,
 7932        cx: &mut Context<Self>,
 7933    ) {
 7934        let text_layout_details = &self.text_layout_details(window);
 7935        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7936            s.move_heads_with(|map, head, goal| {
 7937                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7938            })
 7939        })
 7940    }
 7941
 7942    pub fn select_up_by_lines(
 7943        &mut self,
 7944        action: &SelectUpByLines,
 7945        window: &mut Window,
 7946        cx: &mut Context<Self>,
 7947    ) {
 7948        let text_layout_details = &self.text_layout_details(window);
 7949        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7950            s.move_heads_with(|map, head, goal| {
 7951                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7952            })
 7953        })
 7954    }
 7955
 7956    pub fn select_page_up(
 7957        &mut self,
 7958        _: &SelectPageUp,
 7959        window: &mut Window,
 7960        cx: &mut Context<Self>,
 7961    ) {
 7962        let Some(row_count) = self.visible_row_count() else {
 7963            return;
 7964        };
 7965
 7966        let text_layout_details = &self.text_layout_details(window);
 7967
 7968        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7969            s.move_heads_with(|map, head, goal| {
 7970                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7971            })
 7972        })
 7973    }
 7974
 7975    pub fn move_page_up(
 7976        &mut self,
 7977        action: &MovePageUp,
 7978        window: &mut Window,
 7979        cx: &mut Context<Self>,
 7980    ) {
 7981        if self.take_rename(true, window, cx).is_some() {
 7982            return;
 7983        }
 7984
 7985        if self
 7986            .context_menu
 7987            .borrow_mut()
 7988            .as_mut()
 7989            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7990            .unwrap_or(false)
 7991        {
 7992            return;
 7993        }
 7994
 7995        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7996            cx.propagate();
 7997            return;
 7998        }
 7999
 8000        let Some(row_count) = self.visible_row_count() else {
 8001            return;
 8002        };
 8003
 8004        let autoscroll = if action.center_cursor {
 8005            Autoscroll::center()
 8006        } else {
 8007            Autoscroll::fit()
 8008        };
 8009
 8010        let text_layout_details = &self.text_layout_details(window);
 8011
 8012        self.change_selections(Some(autoscroll), window, cx, |s| {
 8013            let line_mode = s.line_mode;
 8014            s.move_with(|map, selection| {
 8015                if !selection.is_empty() && !line_mode {
 8016                    selection.goal = SelectionGoal::None;
 8017                }
 8018                let (cursor, goal) = movement::up_by_rows(
 8019                    map,
 8020                    selection.end,
 8021                    row_count,
 8022                    selection.goal,
 8023                    false,
 8024                    text_layout_details,
 8025                );
 8026                selection.collapse_to(cursor, goal);
 8027            });
 8028        });
 8029    }
 8030
 8031    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8032        let text_layout_details = &self.text_layout_details(window);
 8033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8034            s.move_heads_with(|map, head, goal| {
 8035                movement::up(map, head, goal, false, text_layout_details)
 8036            })
 8037        })
 8038    }
 8039
 8040    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8041        self.take_rename(true, window, cx);
 8042
 8043        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8044            cx.propagate();
 8045            return;
 8046        }
 8047
 8048        let text_layout_details = &self.text_layout_details(window);
 8049        let selection_count = self.selections.count();
 8050        let first_selection = self.selections.first_anchor();
 8051
 8052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8053            let line_mode = s.line_mode;
 8054            s.move_with(|map, selection| {
 8055                if !selection.is_empty() && !line_mode {
 8056                    selection.goal = SelectionGoal::None;
 8057                }
 8058                let (cursor, goal) = movement::down(
 8059                    map,
 8060                    selection.end,
 8061                    selection.goal,
 8062                    false,
 8063                    text_layout_details,
 8064                );
 8065                selection.collapse_to(cursor, goal);
 8066            });
 8067        });
 8068
 8069        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8070        {
 8071            cx.propagate();
 8072        }
 8073    }
 8074
 8075    pub fn select_page_down(
 8076        &mut self,
 8077        _: &SelectPageDown,
 8078        window: &mut Window,
 8079        cx: &mut Context<Self>,
 8080    ) {
 8081        let Some(row_count) = self.visible_row_count() else {
 8082            return;
 8083        };
 8084
 8085        let text_layout_details = &self.text_layout_details(window);
 8086
 8087        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8088            s.move_heads_with(|map, head, goal| {
 8089                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8090            })
 8091        })
 8092    }
 8093
 8094    pub fn move_page_down(
 8095        &mut self,
 8096        action: &MovePageDown,
 8097        window: &mut Window,
 8098        cx: &mut Context<Self>,
 8099    ) {
 8100        if self.take_rename(true, window, cx).is_some() {
 8101            return;
 8102        }
 8103
 8104        if self
 8105            .context_menu
 8106            .borrow_mut()
 8107            .as_mut()
 8108            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8109            .unwrap_or(false)
 8110        {
 8111            return;
 8112        }
 8113
 8114        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8115            cx.propagate();
 8116            return;
 8117        }
 8118
 8119        let Some(row_count) = self.visible_row_count() else {
 8120            return;
 8121        };
 8122
 8123        let autoscroll = if action.center_cursor {
 8124            Autoscroll::center()
 8125        } else {
 8126            Autoscroll::fit()
 8127        };
 8128
 8129        let text_layout_details = &self.text_layout_details(window);
 8130        self.change_selections(Some(autoscroll), window, cx, |s| {
 8131            let line_mode = s.line_mode;
 8132            s.move_with(|map, selection| {
 8133                if !selection.is_empty() && !line_mode {
 8134                    selection.goal = SelectionGoal::None;
 8135                }
 8136                let (cursor, goal) = movement::down_by_rows(
 8137                    map,
 8138                    selection.end,
 8139                    row_count,
 8140                    selection.goal,
 8141                    false,
 8142                    text_layout_details,
 8143                );
 8144                selection.collapse_to(cursor, goal);
 8145            });
 8146        });
 8147    }
 8148
 8149    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8150        let text_layout_details = &self.text_layout_details(window);
 8151        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8152            s.move_heads_with(|map, head, goal| {
 8153                movement::down(map, head, goal, false, text_layout_details)
 8154            })
 8155        });
 8156    }
 8157
 8158    pub fn context_menu_first(
 8159        &mut self,
 8160        _: &ContextMenuFirst,
 8161        _window: &mut Window,
 8162        cx: &mut Context<Self>,
 8163    ) {
 8164        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8165            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8166        }
 8167    }
 8168
 8169    pub fn context_menu_prev(
 8170        &mut self,
 8171        _: &ContextMenuPrev,
 8172        _window: &mut Window,
 8173        cx: &mut Context<Self>,
 8174    ) {
 8175        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8176            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8177        }
 8178    }
 8179
 8180    pub fn context_menu_next(
 8181        &mut self,
 8182        _: &ContextMenuNext,
 8183        _window: &mut Window,
 8184        cx: &mut Context<Self>,
 8185    ) {
 8186        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8187            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8188        }
 8189    }
 8190
 8191    pub fn context_menu_last(
 8192        &mut self,
 8193        _: &ContextMenuLast,
 8194        _window: &mut Window,
 8195        cx: &mut Context<Self>,
 8196    ) {
 8197        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8198            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8199        }
 8200    }
 8201
 8202    pub fn move_to_previous_word_start(
 8203        &mut self,
 8204        _: &MoveToPreviousWordStart,
 8205        window: &mut Window,
 8206        cx: &mut Context<Self>,
 8207    ) {
 8208        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8209            s.move_cursors_with(|map, head, _| {
 8210                (
 8211                    movement::previous_word_start(map, head),
 8212                    SelectionGoal::None,
 8213                )
 8214            });
 8215        })
 8216    }
 8217
 8218    pub fn move_to_previous_subword_start(
 8219        &mut self,
 8220        _: &MoveToPreviousSubwordStart,
 8221        window: &mut Window,
 8222        cx: &mut Context<Self>,
 8223    ) {
 8224        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8225            s.move_cursors_with(|map, head, _| {
 8226                (
 8227                    movement::previous_subword_start(map, head),
 8228                    SelectionGoal::None,
 8229                )
 8230            });
 8231        })
 8232    }
 8233
 8234    pub fn select_to_previous_word_start(
 8235        &mut self,
 8236        _: &SelectToPreviousWordStart,
 8237        window: &mut Window,
 8238        cx: &mut Context<Self>,
 8239    ) {
 8240        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8241            s.move_heads_with(|map, head, _| {
 8242                (
 8243                    movement::previous_word_start(map, head),
 8244                    SelectionGoal::None,
 8245                )
 8246            });
 8247        })
 8248    }
 8249
 8250    pub fn select_to_previous_subword_start(
 8251        &mut self,
 8252        _: &SelectToPreviousSubwordStart,
 8253        window: &mut Window,
 8254        cx: &mut Context<Self>,
 8255    ) {
 8256        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8257            s.move_heads_with(|map, head, _| {
 8258                (
 8259                    movement::previous_subword_start(map, head),
 8260                    SelectionGoal::None,
 8261                )
 8262            });
 8263        })
 8264    }
 8265
 8266    pub fn delete_to_previous_word_start(
 8267        &mut self,
 8268        action: &DeleteToPreviousWordStart,
 8269        window: &mut Window,
 8270        cx: &mut Context<Self>,
 8271    ) {
 8272        self.transact(window, cx, |this, window, cx| {
 8273            this.select_autoclose_pair(window, cx);
 8274            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8275                let line_mode = s.line_mode;
 8276                s.move_with(|map, selection| {
 8277                    if selection.is_empty() && !line_mode {
 8278                        let cursor = if action.ignore_newlines {
 8279                            movement::previous_word_start(map, selection.head())
 8280                        } else {
 8281                            movement::previous_word_start_or_newline(map, selection.head())
 8282                        };
 8283                        selection.set_head(cursor, SelectionGoal::None);
 8284                    }
 8285                });
 8286            });
 8287            this.insert("", window, cx);
 8288        });
 8289    }
 8290
 8291    pub fn delete_to_previous_subword_start(
 8292        &mut self,
 8293        _: &DeleteToPreviousSubwordStart,
 8294        window: &mut Window,
 8295        cx: &mut Context<Self>,
 8296    ) {
 8297        self.transact(window, cx, |this, window, cx| {
 8298            this.select_autoclose_pair(window, cx);
 8299            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8300                let line_mode = s.line_mode;
 8301                s.move_with(|map, selection| {
 8302                    if selection.is_empty() && !line_mode {
 8303                        let cursor = movement::previous_subword_start(map, selection.head());
 8304                        selection.set_head(cursor, SelectionGoal::None);
 8305                    }
 8306                });
 8307            });
 8308            this.insert("", window, cx);
 8309        });
 8310    }
 8311
 8312    pub fn move_to_next_word_end(
 8313        &mut self,
 8314        _: &MoveToNextWordEnd,
 8315        window: &mut Window,
 8316        cx: &mut Context<Self>,
 8317    ) {
 8318        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8319            s.move_cursors_with(|map, head, _| {
 8320                (movement::next_word_end(map, head), SelectionGoal::None)
 8321            });
 8322        })
 8323    }
 8324
 8325    pub fn move_to_next_subword_end(
 8326        &mut self,
 8327        _: &MoveToNextSubwordEnd,
 8328        window: &mut Window,
 8329        cx: &mut Context<Self>,
 8330    ) {
 8331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8332            s.move_cursors_with(|map, head, _| {
 8333                (movement::next_subword_end(map, head), SelectionGoal::None)
 8334            });
 8335        })
 8336    }
 8337
 8338    pub fn select_to_next_word_end(
 8339        &mut self,
 8340        _: &SelectToNextWordEnd,
 8341        window: &mut Window,
 8342        cx: &mut Context<Self>,
 8343    ) {
 8344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8345            s.move_heads_with(|map, head, _| {
 8346                (movement::next_word_end(map, head), SelectionGoal::None)
 8347            });
 8348        })
 8349    }
 8350
 8351    pub fn select_to_next_subword_end(
 8352        &mut self,
 8353        _: &SelectToNextSubwordEnd,
 8354        window: &mut Window,
 8355        cx: &mut Context<Self>,
 8356    ) {
 8357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8358            s.move_heads_with(|map, head, _| {
 8359                (movement::next_subword_end(map, head), SelectionGoal::None)
 8360            });
 8361        })
 8362    }
 8363
 8364    pub fn delete_to_next_word_end(
 8365        &mut self,
 8366        action: &DeleteToNextWordEnd,
 8367        window: &mut Window,
 8368        cx: &mut Context<Self>,
 8369    ) {
 8370        self.transact(window, cx, |this, window, cx| {
 8371            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8372                let line_mode = s.line_mode;
 8373                s.move_with(|map, selection| {
 8374                    if selection.is_empty() && !line_mode {
 8375                        let cursor = if action.ignore_newlines {
 8376                            movement::next_word_end(map, selection.head())
 8377                        } else {
 8378                            movement::next_word_end_or_newline(map, selection.head())
 8379                        };
 8380                        selection.set_head(cursor, SelectionGoal::None);
 8381                    }
 8382                });
 8383            });
 8384            this.insert("", window, cx);
 8385        });
 8386    }
 8387
 8388    pub fn delete_to_next_subword_end(
 8389        &mut self,
 8390        _: &DeleteToNextSubwordEnd,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        self.transact(window, cx, |this, window, cx| {
 8395            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8396                s.move_with(|map, selection| {
 8397                    if selection.is_empty() {
 8398                        let cursor = movement::next_subword_end(map, selection.head());
 8399                        selection.set_head(cursor, SelectionGoal::None);
 8400                    }
 8401                });
 8402            });
 8403            this.insert("", window, cx);
 8404        });
 8405    }
 8406
 8407    pub fn move_to_beginning_of_line(
 8408        &mut self,
 8409        action: &MoveToBeginningOfLine,
 8410        window: &mut Window,
 8411        cx: &mut Context<Self>,
 8412    ) {
 8413        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8414            s.move_cursors_with(|map, head, _| {
 8415                (
 8416                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8417                    SelectionGoal::None,
 8418                )
 8419            });
 8420        })
 8421    }
 8422
 8423    pub fn select_to_beginning_of_line(
 8424        &mut self,
 8425        action: &SelectToBeginningOfLine,
 8426        window: &mut Window,
 8427        cx: &mut Context<Self>,
 8428    ) {
 8429        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8430            s.move_heads_with(|map, head, _| {
 8431                (
 8432                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8433                    SelectionGoal::None,
 8434                )
 8435            });
 8436        });
 8437    }
 8438
 8439    pub fn delete_to_beginning_of_line(
 8440        &mut self,
 8441        _: &DeleteToBeginningOfLine,
 8442        window: &mut Window,
 8443        cx: &mut Context<Self>,
 8444    ) {
 8445        self.transact(window, cx, |this, window, cx| {
 8446            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8447                s.move_with(|_, selection| {
 8448                    selection.reversed = true;
 8449                });
 8450            });
 8451
 8452            this.select_to_beginning_of_line(
 8453                &SelectToBeginningOfLine {
 8454                    stop_at_soft_wraps: false,
 8455                },
 8456                window,
 8457                cx,
 8458            );
 8459            this.backspace(&Backspace, window, cx);
 8460        });
 8461    }
 8462
 8463    pub fn move_to_end_of_line(
 8464        &mut self,
 8465        action: &MoveToEndOfLine,
 8466        window: &mut Window,
 8467        cx: &mut Context<Self>,
 8468    ) {
 8469        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8470            s.move_cursors_with(|map, head, _| {
 8471                (
 8472                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8473                    SelectionGoal::None,
 8474                )
 8475            });
 8476        })
 8477    }
 8478
 8479    pub fn select_to_end_of_line(
 8480        &mut self,
 8481        action: &SelectToEndOfLine,
 8482        window: &mut Window,
 8483        cx: &mut Context<Self>,
 8484    ) {
 8485        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8486            s.move_heads_with(|map, head, _| {
 8487                (
 8488                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8489                    SelectionGoal::None,
 8490                )
 8491            });
 8492        })
 8493    }
 8494
 8495    pub fn delete_to_end_of_line(
 8496        &mut self,
 8497        _: &DeleteToEndOfLine,
 8498        window: &mut Window,
 8499        cx: &mut Context<Self>,
 8500    ) {
 8501        self.transact(window, cx, |this, window, cx| {
 8502            this.select_to_end_of_line(
 8503                &SelectToEndOfLine {
 8504                    stop_at_soft_wraps: false,
 8505                },
 8506                window,
 8507                cx,
 8508            );
 8509            this.delete(&Delete, window, cx);
 8510        });
 8511    }
 8512
 8513    pub fn cut_to_end_of_line(
 8514        &mut self,
 8515        _: &CutToEndOfLine,
 8516        window: &mut Window,
 8517        cx: &mut Context<Self>,
 8518    ) {
 8519        self.transact(window, cx, |this, window, cx| {
 8520            this.select_to_end_of_line(
 8521                &SelectToEndOfLine {
 8522                    stop_at_soft_wraps: false,
 8523                },
 8524                window,
 8525                cx,
 8526            );
 8527            this.cut(&Cut, window, cx);
 8528        });
 8529    }
 8530
 8531    pub fn move_to_start_of_paragraph(
 8532        &mut self,
 8533        _: &MoveToStartOfParagraph,
 8534        window: &mut Window,
 8535        cx: &mut Context<Self>,
 8536    ) {
 8537        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8538            cx.propagate();
 8539            return;
 8540        }
 8541
 8542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8543            s.move_with(|map, selection| {
 8544                selection.collapse_to(
 8545                    movement::start_of_paragraph(map, selection.head(), 1),
 8546                    SelectionGoal::None,
 8547                )
 8548            });
 8549        })
 8550    }
 8551
 8552    pub fn move_to_end_of_paragraph(
 8553        &mut self,
 8554        _: &MoveToEndOfParagraph,
 8555        window: &mut Window,
 8556        cx: &mut Context<Self>,
 8557    ) {
 8558        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8559            cx.propagate();
 8560            return;
 8561        }
 8562
 8563        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8564            s.move_with(|map, selection| {
 8565                selection.collapse_to(
 8566                    movement::end_of_paragraph(map, selection.head(), 1),
 8567                    SelectionGoal::None,
 8568                )
 8569            });
 8570        })
 8571    }
 8572
 8573    pub fn select_to_start_of_paragraph(
 8574        &mut self,
 8575        _: &SelectToStartOfParagraph,
 8576        window: &mut Window,
 8577        cx: &mut Context<Self>,
 8578    ) {
 8579        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8580            cx.propagate();
 8581            return;
 8582        }
 8583
 8584        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8585            s.move_heads_with(|map, head, _| {
 8586                (
 8587                    movement::start_of_paragraph(map, head, 1),
 8588                    SelectionGoal::None,
 8589                )
 8590            });
 8591        })
 8592    }
 8593
 8594    pub fn select_to_end_of_paragraph(
 8595        &mut self,
 8596        _: &SelectToEndOfParagraph,
 8597        window: &mut Window,
 8598        cx: &mut Context<Self>,
 8599    ) {
 8600        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8601            cx.propagate();
 8602            return;
 8603        }
 8604
 8605        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8606            s.move_heads_with(|map, head, _| {
 8607                (
 8608                    movement::end_of_paragraph(map, head, 1),
 8609                    SelectionGoal::None,
 8610                )
 8611            });
 8612        })
 8613    }
 8614
 8615    pub fn move_to_beginning(
 8616        &mut self,
 8617        _: &MoveToBeginning,
 8618        window: &mut Window,
 8619        cx: &mut Context<Self>,
 8620    ) {
 8621        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8622            cx.propagate();
 8623            return;
 8624        }
 8625
 8626        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8627            s.select_ranges(vec![0..0]);
 8628        });
 8629    }
 8630
 8631    pub fn select_to_beginning(
 8632        &mut self,
 8633        _: &SelectToBeginning,
 8634        window: &mut Window,
 8635        cx: &mut Context<Self>,
 8636    ) {
 8637        let mut selection = self.selections.last::<Point>(cx);
 8638        selection.set_head(Point::zero(), SelectionGoal::None);
 8639
 8640        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8641            s.select(vec![selection]);
 8642        });
 8643    }
 8644
 8645    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8646        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8647            cx.propagate();
 8648            return;
 8649        }
 8650
 8651        let cursor = self.buffer.read(cx).read(cx).len();
 8652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8653            s.select_ranges(vec![cursor..cursor])
 8654        });
 8655    }
 8656
 8657    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8658        self.nav_history = nav_history;
 8659    }
 8660
 8661    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8662        self.nav_history.as_ref()
 8663    }
 8664
 8665    fn push_to_nav_history(
 8666        &mut self,
 8667        cursor_anchor: Anchor,
 8668        new_position: Option<Point>,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        if let Some(nav_history) = self.nav_history.as_mut() {
 8672            let buffer = self.buffer.read(cx).read(cx);
 8673            let cursor_position = cursor_anchor.to_point(&buffer);
 8674            let scroll_state = self.scroll_manager.anchor();
 8675            let scroll_top_row = scroll_state.top_row(&buffer);
 8676            drop(buffer);
 8677
 8678            if let Some(new_position) = new_position {
 8679                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8680                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8681                    return;
 8682                }
 8683            }
 8684
 8685            nav_history.push(
 8686                Some(NavigationData {
 8687                    cursor_anchor,
 8688                    cursor_position,
 8689                    scroll_anchor: scroll_state,
 8690                    scroll_top_row,
 8691                }),
 8692                cx,
 8693            );
 8694        }
 8695    }
 8696
 8697    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8698        let buffer = self.buffer.read(cx).snapshot(cx);
 8699        let mut selection = self.selections.first::<usize>(cx);
 8700        selection.set_head(buffer.len(), SelectionGoal::None);
 8701        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8702            s.select(vec![selection]);
 8703        });
 8704    }
 8705
 8706    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8707        let end = self.buffer.read(cx).read(cx).len();
 8708        self.change_selections(None, window, cx, |s| {
 8709            s.select_ranges(vec![0..end]);
 8710        });
 8711    }
 8712
 8713    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8714        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8715        let mut selections = self.selections.all::<Point>(cx);
 8716        let max_point = display_map.buffer_snapshot.max_point();
 8717        for selection in &mut selections {
 8718            let rows = selection.spanned_rows(true, &display_map);
 8719            selection.start = Point::new(rows.start.0, 0);
 8720            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8721            selection.reversed = false;
 8722        }
 8723        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8724            s.select(selections);
 8725        });
 8726    }
 8727
 8728    pub fn split_selection_into_lines(
 8729        &mut self,
 8730        _: &SplitSelectionIntoLines,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        let mut to_unfold = Vec::new();
 8735        let mut new_selection_ranges = Vec::new();
 8736        {
 8737            let selections = self.selections.all::<Point>(cx);
 8738            let buffer = self.buffer.read(cx).read(cx);
 8739            for selection in selections {
 8740                for row in selection.start.row..selection.end.row {
 8741                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8742                    new_selection_ranges.push(cursor..cursor);
 8743                }
 8744                new_selection_ranges.push(selection.end..selection.end);
 8745                to_unfold.push(selection.start..selection.end);
 8746            }
 8747        }
 8748        self.unfold_ranges(&to_unfold, true, true, cx);
 8749        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8750            s.select_ranges(new_selection_ranges);
 8751        });
 8752    }
 8753
 8754    pub fn add_selection_above(
 8755        &mut self,
 8756        _: &AddSelectionAbove,
 8757        window: &mut Window,
 8758        cx: &mut Context<Self>,
 8759    ) {
 8760        self.add_selection(true, window, cx);
 8761    }
 8762
 8763    pub fn add_selection_below(
 8764        &mut self,
 8765        _: &AddSelectionBelow,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) {
 8769        self.add_selection(false, window, cx);
 8770    }
 8771
 8772    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8774        let mut selections = self.selections.all::<Point>(cx);
 8775        let text_layout_details = self.text_layout_details(window);
 8776        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8777            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8778            let range = oldest_selection.display_range(&display_map).sorted();
 8779
 8780            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8781            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8782            let positions = start_x.min(end_x)..start_x.max(end_x);
 8783
 8784            selections.clear();
 8785            let mut stack = Vec::new();
 8786            for row in range.start.row().0..=range.end.row().0 {
 8787                if let Some(selection) = self.selections.build_columnar_selection(
 8788                    &display_map,
 8789                    DisplayRow(row),
 8790                    &positions,
 8791                    oldest_selection.reversed,
 8792                    &text_layout_details,
 8793                ) {
 8794                    stack.push(selection.id);
 8795                    selections.push(selection);
 8796                }
 8797            }
 8798
 8799            if above {
 8800                stack.reverse();
 8801            }
 8802
 8803            AddSelectionsState { above, stack }
 8804        });
 8805
 8806        let last_added_selection = *state.stack.last().unwrap();
 8807        let mut new_selections = Vec::new();
 8808        if above == state.above {
 8809            let end_row = if above {
 8810                DisplayRow(0)
 8811            } else {
 8812                display_map.max_point().row()
 8813            };
 8814
 8815            'outer: for selection in selections {
 8816                if selection.id == last_added_selection {
 8817                    let range = selection.display_range(&display_map).sorted();
 8818                    debug_assert_eq!(range.start.row(), range.end.row());
 8819                    let mut row = range.start.row();
 8820                    let positions =
 8821                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8822                            px(start)..px(end)
 8823                        } else {
 8824                            let start_x =
 8825                                display_map.x_for_display_point(range.start, &text_layout_details);
 8826                            let end_x =
 8827                                display_map.x_for_display_point(range.end, &text_layout_details);
 8828                            start_x.min(end_x)..start_x.max(end_x)
 8829                        };
 8830
 8831                    while row != end_row {
 8832                        if above {
 8833                            row.0 -= 1;
 8834                        } else {
 8835                            row.0 += 1;
 8836                        }
 8837
 8838                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8839                            &display_map,
 8840                            row,
 8841                            &positions,
 8842                            selection.reversed,
 8843                            &text_layout_details,
 8844                        ) {
 8845                            state.stack.push(new_selection.id);
 8846                            if above {
 8847                                new_selections.push(new_selection);
 8848                                new_selections.push(selection);
 8849                            } else {
 8850                                new_selections.push(selection);
 8851                                new_selections.push(new_selection);
 8852                            }
 8853
 8854                            continue 'outer;
 8855                        }
 8856                    }
 8857                }
 8858
 8859                new_selections.push(selection);
 8860            }
 8861        } else {
 8862            new_selections = selections;
 8863            new_selections.retain(|s| s.id != last_added_selection);
 8864            state.stack.pop();
 8865        }
 8866
 8867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8868            s.select(new_selections);
 8869        });
 8870        if state.stack.len() > 1 {
 8871            self.add_selections_state = Some(state);
 8872        }
 8873    }
 8874
 8875    pub fn select_next_match_internal(
 8876        &mut self,
 8877        display_map: &DisplaySnapshot,
 8878        replace_newest: bool,
 8879        autoscroll: Option<Autoscroll>,
 8880        window: &mut Window,
 8881        cx: &mut Context<Self>,
 8882    ) -> Result<()> {
 8883        fn select_next_match_ranges(
 8884            this: &mut Editor,
 8885            range: Range<usize>,
 8886            replace_newest: bool,
 8887            auto_scroll: Option<Autoscroll>,
 8888            window: &mut Window,
 8889            cx: &mut Context<Editor>,
 8890        ) {
 8891            this.unfold_ranges(&[range.clone()], false, true, cx);
 8892            this.change_selections(auto_scroll, window, cx, |s| {
 8893                if replace_newest {
 8894                    s.delete(s.newest_anchor().id);
 8895                }
 8896                s.insert_range(range.clone());
 8897            });
 8898        }
 8899
 8900        let buffer = &display_map.buffer_snapshot;
 8901        let mut selections = self.selections.all::<usize>(cx);
 8902        if let Some(mut select_next_state) = self.select_next_state.take() {
 8903            let query = &select_next_state.query;
 8904            if !select_next_state.done {
 8905                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8906                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8907                let mut next_selected_range = None;
 8908
 8909                let bytes_after_last_selection =
 8910                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8911                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8912                let query_matches = query
 8913                    .stream_find_iter(bytes_after_last_selection)
 8914                    .map(|result| (last_selection.end, result))
 8915                    .chain(
 8916                        query
 8917                            .stream_find_iter(bytes_before_first_selection)
 8918                            .map(|result| (0, result)),
 8919                    );
 8920
 8921                for (start_offset, query_match) in query_matches {
 8922                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8923                    let offset_range =
 8924                        start_offset + query_match.start()..start_offset + query_match.end();
 8925                    let display_range = offset_range.start.to_display_point(display_map)
 8926                        ..offset_range.end.to_display_point(display_map);
 8927
 8928                    if !select_next_state.wordwise
 8929                        || (!movement::is_inside_word(display_map, display_range.start)
 8930                            && !movement::is_inside_word(display_map, display_range.end))
 8931                    {
 8932                        // TODO: This is n^2, because we might check all the selections
 8933                        if !selections
 8934                            .iter()
 8935                            .any(|selection| selection.range().overlaps(&offset_range))
 8936                        {
 8937                            next_selected_range = Some(offset_range);
 8938                            break;
 8939                        }
 8940                    }
 8941                }
 8942
 8943                if let Some(next_selected_range) = next_selected_range {
 8944                    select_next_match_ranges(
 8945                        self,
 8946                        next_selected_range,
 8947                        replace_newest,
 8948                        autoscroll,
 8949                        window,
 8950                        cx,
 8951                    );
 8952                } else {
 8953                    select_next_state.done = true;
 8954                }
 8955            }
 8956
 8957            self.select_next_state = Some(select_next_state);
 8958        } else {
 8959            let mut only_carets = true;
 8960            let mut same_text_selected = true;
 8961            let mut selected_text = None;
 8962
 8963            let mut selections_iter = selections.iter().peekable();
 8964            while let Some(selection) = selections_iter.next() {
 8965                if selection.start != selection.end {
 8966                    only_carets = false;
 8967                }
 8968
 8969                if same_text_selected {
 8970                    if selected_text.is_none() {
 8971                        selected_text =
 8972                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8973                    }
 8974
 8975                    if let Some(next_selection) = selections_iter.peek() {
 8976                        if next_selection.range().len() == selection.range().len() {
 8977                            let next_selected_text = buffer
 8978                                .text_for_range(next_selection.range())
 8979                                .collect::<String>();
 8980                            if Some(next_selected_text) != selected_text {
 8981                                same_text_selected = false;
 8982                                selected_text = None;
 8983                            }
 8984                        } else {
 8985                            same_text_selected = false;
 8986                            selected_text = None;
 8987                        }
 8988                    }
 8989                }
 8990            }
 8991
 8992            if only_carets {
 8993                for selection in &mut selections {
 8994                    let word_range = movement::surrounding_word(
 8995                        display_map,
 8996                        selection.start.to_display_point(display_map),
 8997                    );
 8998                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8999                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9000                    selection.goal = SelectionGoal::None;
 9001                    selection.reversed = false;
 9002                    select_next_match_ranges(
 9003                        self,
 9004                        selection.start..selection.end,
 9005                        replace_newest,
 9006                        autoscroll,
 9007                        window,
 9008                        cx,
 9009                    );
 9010                }
 9011
 9012                if selections.len() == 1 {
 9013                    let selection = selections
 9014                        .last()
 9015                        .expect("ensured that there's only one selection");
 9016                    let query = buffer
 9017                        .text_for_range(selection.start..selection.end)
 9018                        .collect::<String>();
 9019                    let is_empty = query.is_empty();
 9020                    let select_state = SelectNextState {
 9021                        query: AhoCorasick::new(&[query])?,
 9022                        wordwise: true,
 9023                        done: is_empty,
 9024                    };
 9025                    self.select_next_state = Some(select_state);
 9026                } else {
 9027                    self.select_next_state = None;
 9028                }
 9029            } else if let Some(selected_text) = selected_text {
 9030                self.select_next_state = Some(SelectNextState {
 9031                    query: AhoCorasick::new(&[selected_text])?,
 9032                    wordwise: false,
 9033                    done: false,
 9034                });
 9035                self.select_next_match_internal(
 9036                    display_map,
 9037                    replace_newest,
 9038                    autoscroll,
 9039                    window,
 9040                    cx,
 9041                )?;
 9042            }
 9043        }
 9044        Ok(())
 9045    }
 9046
 9047    pub fn select_all_matches(
 9048        &mut self,
 9049        _action: &SelectAllMatches,
 9050        window: &mut Window,
 9051        cx: &mut Context<Self>,
 9052    ) -> Result<()> {
 9053        self.push_to_selection_history();
 9054        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9055
 9056        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9057        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9058            return Ok(());
 9059        };
 9060        if select_next_state.done {
 9061            return Ok(());
 9062        }
 9063
 9064        let mut new_selections = self.selections.all::<usize>(cx);
 9065
 9066        let buffer = &display_map.buffer_snapshot;
 9067        let query_matches = select_next_state
 9068            .query
 9069            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9070
 9071        for query_match in query_matches {
 9072            let query_match = query_match.unwrap(); // can only fail due to I/O
 9073            let offset_range = query_match.start()..query_match.end();
 9074            let display_range = offset_range.start.to_display_point(&display_map)
 9075                ..offset_range.end.to_display_point(&display_map);
 9076
 9077            if !select_next_state.wordwise
 9078                || (!movement::is_inside_word(&display_map, display_range.start)
 9079                    && !movement::is_inside_word(&display_map, display_range.end))
 9080            {
 9081                self.selections.change_with(cx, |selections| {
 9082                    new_selections.push(Selection {
 9083                        id: selections.new_selection_id(),
 9084                        start: offset_range.start,
 9085                        end: offset_range.end,
 9086                        reversed: false,
 9087                        goal: SelectionGoal::None,
 9088                    });
 9089                });
 9090            }
 9091        }
 9092
 9093        new_selections.sort_by_key(|selection| selection.start);
 9094        let mut ix = 0;
 9095        while ix + 1 < new_selections.len() {
 9096            let current_selection = &new_selections[ix];
 9097            let next_selection = &new_selections[ix + 1];
 9098            if current_selection.range().overlaps(&next_selection.range()) {
 9099                if current_selection.id < next_selection.id {
 9100                    new_selections.remove(ix + 1);
 9101                } else {
 9102                    new_selections.remove(ix);
 9103                }
 9104            } else {
 9105                ix += 1;
 9106            }
 9107        }
 9108
 9109        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9110
 9111        for selection in new_selections.iter_mut() {
 9112            selection.reversed = reversed;
 9113        }
 9114
 9115        select_next_state.done = true;
 9116        self.unfold_ranges(
 9117            &new_selections
 9118                .iter()
 9119                .map(|selection| selection.range())
 9120                .collect::<Vec<_>>(),
 9121            false,
 9122            false,
 9123            cx,
 9124        );
 9125        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9126            selections.select(new_selections)
 9127        });
 9128
 9129        Ok(())
 9130    }
 9131
 9132    pub fn select_next(
 9133        &mut self,
 9134        action: &SelectNext,
 9135        window: &mut Window,
 9136        cx: &mut Context<Self>,
 9137    ) -> Result<()> {
 9138        self.push_to_selection_history();
 9139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9140        self.select_next_match_internal(
 9141            &display_map,
 9142            action.replace_newest,
 9143            Some(Autoscroll::newest()),
 9144            window,
 9145            cx,
 9146        )?;
 9147        Ok(())
 9148    }
 9149
 9150    pub fn select_previous(
 9151        &mut self,
 9152        action: &SelectPrevious,
 9153        window: &mut Window,
 9154        cx: &mut Context<Self>,
 9155    ) -> Result<()> {
 9156        self.push_to_selection_history();
 9157        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9158        let buffer = &display_map.buffer_snapshot;
 9159        let mut selections = self.selections.all::<usize>(cx);
 9160        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9161            let query = &select_prev_state.query;
 9162            if !select_prev_state.done {
 9163                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9164                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9165                let mut next_selected_range = None;
 9166                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9167                let bytes_before_last_selection =
 9168                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9169                let bytes_after_first_selection =
 9170                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9171                let query_matches = query
 9172                    .stream_find_iter(bytes_before_last_selection)
 9173                    .map(|result| (last_selection.start, result))
 9174                    .chain(
 9175                        query
 9176                            .stream_find_iter(bytes_after_first_selection)
 9177                            .map(|result| (buffer.len(), result)),
 9178                    );
 9179                for (end_offset, query_match) in query_matches {
 9180                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9181                    let offset_range =
 9182                        end_offset - query_match.end()..end_offset - query_match.start();
 9183                    let display_range = offset_range.start.to_display_point(&display_map)
 9184                        ..offset_range.end.to_display_point(&display_map);
 9185
 9186                    if !select_prev_state.wordwise
 9187                        || (!movement::is_inside_word(&display_map, display_range.start)
 9188                            && !movement::is_inside_word(&display_map, display_range.end))
 9189                    {
 9190                        next_selected_range = Some(offset_range);
 9191                        break;
 9192                    }
 9193                }
 9194
 9195                if let Some(next_selected_range) = next_selected_range {
 9196                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9197                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9198                        if action.replace_newest {
 9199                            s.delete(s.newest_anchor().id);
 9200                        }
 9201                        s.insert_range(next_selected_range);
 9202                    });
 9203                } else {
 9204                    select_prev_state.done = true;
 9205                }
 9206            }
 9207
 9208            self.select_prev_state = Some(select_prev_state);
 9209        } else {
 9210            let mut only_carets = true;
 9211            let mut same_text_selected = true;
 9212            let mut selected_text = None;
 9213
 9214            let mut selections_iter = selections.iter().peekable();
 9215            while let Some(selection) = selections_iter.next() {
 9216                if selection.start != selection.end {
 9217                    only_carets = false;
 9218                }
 9219
 9220                if same_text_selected {
 9221                    if selected_text.is_none() {
 9222                        selected_text =
 9223                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9224                    }
 9225
 9226                    if let Some(next_selection) = selections_iter.peek() {
 9227                        if next_selection.range().len() == selection.range().len() {
 9228                            let next_selected_text = buffer
 9229                                .text_for_range(next_selection.range())
 9230                                .collect::<String>();
 9231                            if Some(next_selected_text) != selected_text {
 9232                                same_text_selected = false;
 9233                                selected_text = None;
 9234                            }
 9235                        } else {
 9236                            same_text_selected = false;
 9237                            selected_text = None;
 9238                        }
 9239                    }
 9240                }
 9241            }
 9242
 9243            if only_carets {
 9244                for selection in &mut selections {
 9245                    let word_range = movement::surrounding_word(
 9246                        &display_map,
 9247                        selection.start.to_display_point(&display_map),
 9248                    );
 9249                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9250                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9251                    selection.goal = SelectionGoal::None;
 9252                    selection.reversed = false;
 9253                }
 9254                if selections.len() == 1 {
 9255                    let selection = selections
 9256                        .last()
 9257                        .expect("ensured that there's only one selection");
 9258                    let query = buffer
 9259                        .text_for_range(selection.start..selection.end)
 9260                        .collect::<String>();
 9261                    let is_empty = query.is_empty();
 9262                    let select_state = SelectNextState {
 9263                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9264                        wordwise: true,
 9265                        done: is_empty,
 9266                    };
 9267                    self.select_prev_state = Some(select_state);
 9268                } else {
 9269                    self.select_prev_state = None;
 9270                }
 9271
 9272                self.unfold_ranges(
 9273                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9274                    false,
 9275                    true,
 9276                    cx,
 9277                );
 9278                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9279                    s.select(selections);
 9280                });
 9281            } else if let Some(selected_text) = selected_text {
 9282                self.select_prev_state = Some(SelectNextState {
 9283                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9284                    wordwise: false,
 9285                    done: false,
 9286                });
 9287                self.select_previous(action, window, cx)?;
 9288            }
 9289        }
 9290        Ok(())
 9291    }
 9292
 9293    pub fn toggle_comments(
 9294        &mut self,
 9295        action: &ToggleComments,
 9296        window: &mut Window,
 9297        cx: &mut Context<Self>,
 9298    ) {
 9299        if self.read_only(cx) {
 9300            return;
 9301        }
 9302        let text_layout_details = &self.text_layout_details(window);
 9303        self.transact(window, cx, |this, window, cx| {
 9304            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9305            let mut edits = Vec::new();
 9306            let mut selection_edit_ranges = Vec::new();
 9307            let mut last_toggled_row = None;
 9308            let snapshot = this.buffer.read(cx).read(cx);
 9309            let empty_str: Arc<str> = Arc::default();
 9310            let mut suffixes_inserted = Vec::new();
 9311            let ignore_indent = action.ignore_indent;
 9312
 9313            fn comment_prefix_range(
 9314                snapshot: &MultiBufferSnapshot,
 9315                row: MultiBufferRow,
 9316                comment_prefix: &str,
 9317                comment_prefix_whitespace: &str,
 9318                ignore_indent: bool,
 9319            ) -> Range<Point> {
 9320                let indent_size = if ignore_indent {
 9321                    0
 9322                } else {
 9323                    snapshot.indent_size_for_line(row).len
 9324                };
 9325
 9326                let start = Point::new(row.0, indent_size);
 9327
 9328                let mut line_bytes = snapshot
 9329                    .bytes_in_range(start..snapshot.max_point())
 9330                    .flatten()
 9331                    .copied();
 9332
 9333                // If this line currently begins with the line comment prefix, then record
 9334                // the range containing the prefix.
 9335                if line_bytes
 9336                    .by_ref()
 9337                    .take(comment_prefix.len())
 9338                    .eq(comment_prefix.bytes())
 9339                {
 9340                    // Include any whitespace that matches the comment prefix.
 9341                    let matching_whitespace_len = line_bytes
 9342                        .zip(comment_prefix_whitespace.bytes())
 9343                        .take_while(|(a, b)| a == b)
 9344                        .count() as u32;
 9345                    let end = Point::new(
 9346                        start.row,
 9347                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9348                    );
 9349                    start..end
 9350                } else {
 9351                    start..start
 9352                }
 9353            }
 9354
 9355            fn comment_suffix_range(
 9356                snapshot: &MultiBufferSnapshot,
 9357                row: MultiBufferRow,
 9358                comment_suffix: &str,
 9359                comment_suffix_has_leading_space: bool,
 9360            ) -> Range<Point> {
 9361                let end = Point::new(row.0, snapshot.line_len(row));
 9362                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9363
 9364                let mut line_end_bytes = snapshot
 9365                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9366                    .flatten()
 9367                    .copied();
 9368
 9369                let leading_space_len = if suffix_start_column > 0
 9370                    && line_end_bytes.next() == Some(b' ')
 9371                    && comment_suffix_has_leading_space
 9372                {
 9373                    1
 9374                } else {
 9375                    0
 9376                };
 9377
 9378                // If this line currently begins with the line comment prefix, then record
 9379                // the range containing the prefix.
 9380                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9381                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9382                    start..end
 9383                } else {
 9384                    end..end
 9385                }
 9386            }
 9387
 9388            // TODO: Handle selections that cross excerpts
 9389            for selection in &mut selections {
 9390                let start_column = snapshot
 9391                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9392                    .len;
 9393                let language = if let Some(language) =
 9394                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9395                {
 9396                    language
 9397                } else {
 9398                    continue;
 9399                };
 9400
 9401                selection_edit_ranges.clear();
 9402
 9403                // If multiple selections contain a given row, avoid processing that
 9404                // row more than once.
 9405                let mut start_row = MultiBufferRow(selection.start.row);
 9406                if last_toggled_row == Some(start_row) {
 9407                    start_row = start_row.next_row();
 9408                }
 9409                let end_row =
 9410                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9411                        MultiBufferRow(selection.end.row - 1)
 9412                    } else {
 9413                        MultiBufferRow(selection.end.row)
 9414                    };
 9415                last_toggled_row = Some(end_row);
 9416
 9417                if start_row > end_row {
 9418                    continue;
 9419                }
 9420
 9421                // If the language has line comments, toggle those.
 9422                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9423
 9424                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9425                if ignore_indent {
 9426                    full_comment_prefixes = full_comment_prefixes
 9427                        .into_iter()
 9428                        .map(|s| Arc::from(s.trim_end()))
 9429                        .collect();
 9430                }
 9431
 9432                if !full_comment_prefixes.is_empty() {
 9433                    let first_prefix = full_comment_prefixes
 9434                        .first()
 9435                        .expect("prefixes is non-empty");
 9436                    let prefix_trimmed_lengths = full_comment_prefixes
 9437                        .iter()
 9438                        .map(|p| p.trim_end_matches(' ').len())
 9439                        .collect::<SmallVec<[usize; 4]>>();
 9440
 9441                    let mut all_selection_lines_are_comments = true;
 9442
 9443                    for row in start_row.0..=end_row.0 {
 9444                        let row = MultiBufferRow(row);
 9445                        if start_row < end_row && snapshot.is_line_blank(row) {
 9446                            continue;
 9447                        }
 9448
 9449                        let prefix_range = full_comment_prefixes
 9450                            .iter()
 9451                            .zip(prefix_trimmed_lengths.iter().copied())
 9452                            .map(|(prefix, trimmed_prefix_len)| {
 9453                                comment_prefix_range(
 9454                                    snapshot.deref(),
 9455                                    row,
 9456                                    &prefix[..trimmed_prefix_len],
 9457                                    &prefix[trimmed_prefix_len..],
 9458                                    ignore_indent,
 9459                                )
 9460                            })
 9461                            .max_by_key(|range| range.end.column - range.start.column)
 9462                            .expect("prefixes is non-empty");
 9463
 9464                        if prefix_range.is_empty() {
 9465                            all_selection_lines_are_comments = false;
 9466                        }
 9467
 9468                        selection_edit_ranges.push(prefix_range);
 9469                    }
 9470
 9471                    if all_selection_lines_are_comments {
 9472                        edits.extend(
 9473                            selection_edit_ranges
 9474                                .iter()
 9475                                .cloned()
 9476                                .map(|range| (range, empty_str.clone())),
 9477                        );
 9478                    } else {
 9479                        let min_column = selection_edit_ranges
 9480                            .iter()
 9481                            .map(|range| range.start.column)
 9482                            .min()
 9483                            .unwrap_or(0);
 9484                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9485                            let position = Point::new(range.start.row, min_column);
 9486                            (position..position, first_prefix.clone())
 9487                        }));
 9488                    }
 9489                } else if let Some((full_comment_prefix, comment_suffix)) =
 9490                    language.block_comment_delimiters()
 9491                {
 9492                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9493                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9494                    let prefix_range = comment_prefix_range(
 9495                        snapshot.deref(),
 9496                        start_row,
 9497                        comment_prefix,
 9498                        comment_prefix_whitespace,
 9499                        ignore_indent,
 9500                    );
 9501                    let suffix_range = comment_suffix_range(
 9502                        snapshot.deref(),
 9503                        end_row,
 9504                        comment_suffix.trim_start_matches(' '),
 9505                        comment_suffix.starts_with(' '),
 9506                    );
 9507
 9508                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9509                        edits.push((
 9510                            prefix_range.start..prefix_range.start,
 9511                            full_comment_prefix.clone(),
 9512                        ));
 9513                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9514                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9515                    } else {
 9516                        edits.push((prefix_range, empty_str.clone()));
 9517                        edits.push((suffix_range, empty_str.clone()));
 9518                    }
 9519                } else {
 9520                    continue;
 9521                }
 9522            }
 9523
 9524            drop(snapshot);
 9525            this.buffer.update(cx, |buffer, cx| {
 9526                buffer.edit(edits, None, cx);
 9527            });
 9528
 9529            // Adjust selections so that they end before any comment suffixes that
 9530            // were inserted.
 9531            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9532            let mut selections = this.selections.all::<Point>(cx);
 9533            let snapshot = this.buffer.read(cx).read(cx);
 9534            for selection in &mut selections {
 9535                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9536                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9537                        Ordering::Less => {
 9538                            suffixes_inserted.next();
 9539                            continue;
 9540                        }
 9541                        Ordering::Greater => break,
 9542                        Ordering::Equal => {
 9543                            if selection.end.column == snapshot.line_len(row) {
 9544                                if selection.is_empty() {
 9545                                    selection.start.column -= suffix_len as u32;
 9546                                }
 9547                                selection.end.column -= suffix_len as u32;
 9548                            }
 9549                            break;
 9550                        }
 9551                    }
 9552                }
 9553            }
 9554
 9555            drop(snapshot);
 9556            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9557                s.select(selections)
 9558            });
 9559
 9560            let selections = this.selections.all::<Point>(cx);
 9561            let selections_on_single_row = selections.windows(2).all(|selections| {
 9562                selections[0].start.row == selections[1].start.row
 9563                    && selections[0].end.row == selections[1].end.row
 9564                    && selections[0].start.row == selections[0].end.row
 9565            });
 9566            let selections_selecting = selections
 9567                .iter()
 9568                .any(|selection| selection.start != selection.end);
 9569            let advance_downwards = action.advance_downwards
 9570                && selections_on_single_row
 9571                && !selections_selecting
 9572                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9573
 9574            if advance_downwards {
 9575                let snapshot = this.buffer.read(cx).snapshot(cx);
 9576
 9577                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9578                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9579                        let mut point = display_point.to_point(display_snapshot);
 9580                        point.row += 1;
 9581                        point = snapshot.clip_point(point, Bias::Left);
 9582                        let display_point = point.to_display_point(display_snapshot);
 9583                        let goal = SelectionGoal::HorizontalPosition(
 9584                            display_snapshot
 9585                                .x_for_display_point(display_point, text_layout_details)
 9586                                .into(),
 9587                        );
 9588                        (display_point, goal)
 9589                    })
 9590                });
 9591            }
 9592        });
 9593    }
 9594
 9595    pub fn select_enclosing_symbol(
 9596        &mut self,
 9597        _: &SelectEnclosingSymbol,
 9598        window: &mut Window,
 9599        cx: &mut Context<Self>,
 9600    ) {
 9601        let buffer = self.buffer.read(cx).snapshot(cx);
 9602        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9603
 9604        fn update_selection(
 9605            selection: &Selection<usize>,
 9606            buffer_snap: &MultiBufferSnapshot,
 9607        ) -> Option<Selection<usize>> {
 9608            let cursor = selection.head();
 9609            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9610            for symbol in symbols.iter().rev() {
 9611                let start = symbol.range.start.to_offset(buffer_snap);
 9612                let end = symbol.range.end.to_offset(buffer_snap);
 9613                let new_range = start..end;
 9614                if start < selection.start || end > selection.end {
 9615                    return Some(Selection {
 9616                        id: selection.id,
 9617                        start: new_range.start,
 9618                        end: new_range.end,
 9619                        goal: SelectionGoal::None,
 9620                        reversed: selection.reversed,
 9621                    });
 9622                }
 9623            }
 9624            None
 9625        }
 9626
 9627        let mut selected_larger_symbol = false;
 9628        let new_selections = old_selections
 9629            .iter()
 9630            .map(|selection| match update_selection(selection, &buffer) {
 9631                Some(new_selection) => {
 9632                    if new_selection.range() != selection.range() {
 9633                        selected_larger_symbol = true;
 9634                    }
 9635                    new_selection
 9636                }
 9637                None => selection.clone(),
 9638            })
 9639            .collect::<Vec<_>>();
 9640
 9641        if selected_larger_symbol {
 9642            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9643                s.select(new_selections);
 9644            });
 9645        }
 9646    }
 9647
 9648    pub fn select_larger_syntax_node(
 9649        &mut self,
 9650        _: &SelectLargerSyntaxNode,
 9651        window: &mut Window,
 9652        cx: &mut Context<Self>,
 9653    ) {
 9654        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9655        let buffer = self.buffer.read(cx).snapshot(cx);
 9656        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9657
 9658        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9659        let mut selected_larger_node = false;
 9660        let new_selections = old_selections
 9661            .iter()
 9662            .map(|selection| {
 9663                let old_range = selection.start..selection.end;
 9664                let mut new_range = old_range.clone();
 9665                let mut new_node = None;
 9666                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9667                {
 9668                    new_node = Some(node);
 9669                    new_range = containing_range;
 9670                    if !display_map.intersects_fold(new_range.start)
 9671                        && !display_map.intersects_fold(new_range.end)
 9672                    {
 9673                        break;
 9674                    }
 9675                }
 9676
 9677                if let Some(node) = new_node {
 9678                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9679                    // nodes. Parent and grandparent are also logged because this operation will not
 9680                    // visit nodes that have the same range as their parent.
 9681                    log::info!("Node: {node:?}");
 9682                    let parent = node.parent();
 9683                    log::info!("Parent: {parent:?}");
 9684                    let grandparent = parent.and_then(|x| x.parent());
 9685                    log::info!("Grandparent: {grandparent:?}");
 9686                }
 9687
 9688                selected_larger_node |= new_range != old_range;
 9689                Selection {
 9690                    id: selection.id,
 9691                    start: new_range.start,
 9692                    end: new_range.end,
 9693                    goal: SelectionGoal::None,
 9694                    reversed: selection.reversed,
 9695                }
 9696            })
 9697            .collect::<Vec<_>>();
 9698
 9699        if selected_larger_node {
 9700            stack.push(old_selections);
 9701            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9702                s.select(new_selections);
 9703            });
 9704        }
 9705        self.select_larger_syntax_node_stack = stack;
 9706    }
 9707
 9708    pub fn select_smaller_syntax_node(
 9709        &mut self,
 9710        _: &SelectSmallerSyntaxNode,
 9711        window: &mut Window,
 9712        cx: &mut Context<Self>,
 9713    ) {
 9714        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9715        if let Some(selections) = stack.pop() {
 9716            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9717                s.select(selections.to_vec());
 9718            });
 9719        }
 9720        self.select_larger_syntax_node_stack = stack;
 9721    }
 9722
 9723    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9724        if !EditorSettings::get_global(cx).gutter.runnables {
 9725            self.clear_tasks();
 9726            return Task::ready(());
 9727        }
 9728        let project = self.project.as_ref().map(Entity::downgrade);
 9729        cx.spawn_in(window, |this, mut cx| async move {
 9730            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9731            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9732                return;
 9733            };
 9734            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9735                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9736            }) else {
 9737                return;
 9738            };
 9739
 9740            let hide_runnables = project
 9741                .update(&mut cx, |project, cx| {
 9742                    // Do not display any test indicators in non-dev server remote projects.
 9743                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9744                })
 9745                .unwrap_or(true);
 9746            if hide_runnables {
 9747                return;
 9748            }
 9749            let new_rows =
 9750                cx.background_executor()
 9751                    .spawn({
 9752                        let snapshot = display_snapshot.clone();
 9753                        async move {
 9754                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9755                        }
 9756                    })
 9757                    .await;
 9758
 9759            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9760            this.update(&mut cx, |this, _| {
 9761                this.clear_tasks();
 9762                for (key, value) in rows {
 9763                    this.insert_tasks(key, value);
 9764                }
 9765            })
 9766            .ok();
 9767        })
 9768    }
 9769    fn fetch_runnable_ranges(
 9770        snapshot: &DisplaySnapshot,
 9771        range: Range<Anchor>,
 9772    ) -> Vec<language::RunnableRange> {
 9773        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9774    }
 9775
 9776    fn runnable_rows(
 9777        project: Entity<Project>,
 9778        snapshot: DisplaySnapshot,
 9779        runnable_ranges: Vec<RunnableRange>,
 9780        mut cx: AsyncWindowContext,
 9781    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9782        runnable_ranges
 9783            .into_iter()
 9784            .filter_map(|mut runnable| {
 9785                let tasks = cx
 9786                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9787                    .ok()?;
 9788                if tasks.is_empty() {
 9789                    return None;
 9790                }
 9791
 9792                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9793
 9794                let row = snapshot
 9795                    .buffer_snapshot
 9796                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9797                    .1
 9798                    .start
 9799                    .row;
 9800
 9801                let context_range =
 9802                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9803                Some((
 9804                    (runnable.buffer_id, row),
 9805                    RunnableTasks {
 9806                        templates: tasks,
 9807                        offset: MultiBufferOffset(runnable.run_range.start),
 9808                        context_range,
 9809                        column: point.column,
 9810                        extra_variables: runnable.extra_captures,
 9811                    },
 9812                ))
 9813            })
 9814            .collect()
 9815    }
 9816
 9817    fn templates_with_tags(
 9818        project: &Entity<Project>,
 9819        runnable: &mut Runnable,
 9820        cx: &mut App,
 9821    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9822        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9823            let (worktree_id, file) = project
 9824                .buffer_for_id(runnable.buffer, cx)
 9825                .and_then(|buffer| buffer.read(cx).file())
 9826                .map(|file| (file.worktree_id(cx), file.clone()))
 9827                .unzip();
 9828
 9829            (
 9830                project.task_store().read(cx).task_inventory().cloned(),
 9831                worktree_id,
 9832                file,
 9833            )
 9834        });
 9835
 9836        let tags = mem::take(&mut runnable.tags);
 9837        let mut tags: Vec<_> = tags
 9838            .into_iter()
 9839            .flat_map(|tag| {
 9840                let tag = tag.0.clone();
 9841                inventory
 9842                    .as_ref()
 9843                    .into_iter()
 9844                    .flat_map(|inventory| {
 9845                        inventory.read(cx).list_tasks(
 9846                            file.clone(),
 9847                            Some(runnable.language.clone()),
 9848                            worktree_id,
 9849                            cx,
 9850                        )
 9851                    })
 9852                    .filter(move |(_, template)| {
 9853                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9854                    })
 9855            })
 9856            .sorted_by_key(|(kind, _)| kind.to_owned())
 9857            .collect();
 9858        if let Some((leading_tag_source, _)) = tags.first() {
 9859            // Strongest source wins; if we have worktree tag binding, prefer that to
 9860            // global and language bindings;
 9861            // if we have a global binding, prefer that to language binding.
 9862            let first_mismatch = tags
 9863                .iter()
 9864                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9865            if let Some(index) = first_mismatch {
 9866                tags.truncate(index);
 9867            }
 9868        }
 9869
 9870        tags
 9871    }
 9872
 9873    pub fn move_to_enclosing_bracket(
 9874        &mut self,
 9875        _: &MoveToEnclosingBracket,
 9876        window: &mut Window,
 9877        cx: &mut Context<Self>,
 9878    ) {
 9879        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9880            s.move_offsets_with(|snapshot, selection| {
 9881                let Some(enclosing_bracket_ranges) =
 9882                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9883                else {
 9884                    return;
 9885                };
 9886
 9887                let mut best_length = usize::MAX;
 9888                let mut best_inside = false;
 9889                let mut best_in_bracket_range = false;
 9890                let mut best_destination = None;
 9891                for (open, close) in enclosing_bracket_ranges {
 9892                    let close = close.to_inclusive();
 9893                    let length = close.end() - open.start;
 9894                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9895                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9896                        || close.contains(&selection.head());
 9897
 9898                    // If best is next to a bracket and current isn't, skip
 9899                    if !in_bracket_range && best_in_bracket_range {
 9900                        continue;
 9901                    }
 9902
 9903                    // Prefer smaller lengths unless best is inside and current isn't
 9904                    if length > best_length && (best_inside || !inside) {
 9905                        continue;
 9906                    }
 9907
 9908                    best_length = length;
 9909                    best_inside = inside;
 9910                    best_in_bracket_range = in_bracket_range;
 9911                    best_destination = Some(
 9912                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9913                            if inside {
 9914                                open.end
 9915                            } else {
 9916                                open.start
 9917                            }
 9918                        } else if inside {
 9919                            *close.start()
 9920                        } else {
 9921                            *close.end()
 9922                        },
 9923                    );
 9924                }
 9925
 9926                if let Some(destination) = best_destination {
 9927                    selection.collapse_to(destination, SelectionGoal::None);
 9928                }
 9929            })
 9930        });
 9931    }
 9932
 9933    pub fn undo_selection(
 9934        &mut self,
 9935        _: &UndoSelection,
 9936        window: &mut Window,
 9937        cx: &mut Context<Self>,
 9938    ) {
 9939        self.end_selection(window, cx);
 9940        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9941        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9942            self.change_selections(None, window, cx, |s| {
 9943                s.select_anchors(entry.selections.to_vec())
 9944            });
 9945            self.select_next_state = entry.select_next_state;
 9946            self.select_prev_state = entry.select_prev_state;
 9947            self.add_selections_state = entry.add_selections_state;
 9948            self.request_autoscroll(Autoscroll::newest(), cx);
 9949        }
 9950        self.selection_history.mode = SelectionHistoryMode::Normal;
 9951    }
 9952
 9953    pub fn redo_selection(
 9954        &mut self,
 9955        _: &RedoSelection,
 9956        window: &mut Window,
 9957        cx: &mut Context<Self>,
 9958    ) {
 9959        self.end_selection(window, cx);
 9960        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9961        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9962            self.change_selections(None, window, cx, |s| {
 9963                s.select_anchors(entry.selections.to_vec())
 9964            });
 9965            self.select_next_state = entry.select_next_state;
 9966            self.select_prev_state = entry.select_prev_state;
 9967            self.add_selections_state = entry.add_selections_state;
 9968            self.request_autoscroll(Autoscroll::newest(), cx);
 9969        }
 9970        self.selection_history.mode = SelectionHistoryMode::Normal;
 9971    }
 9972
 9973    pub fn expand_excerpts(
 9974        &mut self,
 9975        action: &ExpandExcerpts,
 9976        _: &mut Window,
 9977        cx: &mut Context<Self>,
 9978    ) {
 9979        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9980    }
 9981
 9982    pub fn expand_excerpts_down(
 9983        &mut self,
 9984        action: &ExpandExcerptsDown,
 9985        _: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9989    }
 9990
 9991    pub fn expand_excerpts_up(
 9992        &mut self,
 9993        action: &ExpandExcerptsUp,
 9994        _: &mut Window,
 9995        cx: &mut Context<Self>,
 9996    ) {
 9997        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9998    }
 9999
10000    pub fn expand_excerpts_for_direction(
10001        &mut self,
10002        lines: u32,
10003        direction: ExpandExcerptDirection,
10004
10005        cx: &mut Context<Self>,
10006    ) {
10007        let selections = self.selections.disjoint_anchors();
10008
10009        let lines = if lines == 0 {
10010            EditorSettings::get_global(cx).expand_excerpt_lines
10011        } else {
10012            lines
10013        };
10014
10015        self.buffer.update(cx, |buffer, cx| {
10016            let snapshot = buffer.snapshot(cx);
10017            let mut excerpt_ids = selections
10018                .iter()
10019                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10020                .collect::<Vec<_>>();
10021            excerpt_ids.sort();
10022            excerpt_ids.dedup();
10023            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10024        })
10025    }
10026
10027    pub fn expand_excerpt(
10028        &mut self,
10029        excerpt: ExcerptId,
10030        direction: ExpandExcerptDirection,
10031        cx: &mut Context<Self>,
10032    ) {
10033        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10034        self.buffer.update(cx, |buffer, cx| {
10035            buffer.expand_excerpts([excerpt], lines, direction, cx)
10036        })
10037    }
10038
10039    pub fn go_to_singleton_buffer_point(
10040        &mut self,
10041        point: Point,
10042        window: &mut Window,
10043        cx: &mut Context<Self>,
10044    ) {
10045        self.go_to_singleton_buffer_range(point..point, window, cx);
10046    }
10047
10048    pub fn go_to_singleton_buffer_range(
10049        &mut self,
10050        range: Range<Point>,
10051        window: &mut Window,
10052        cx: &mut Context<Self>,
10053    ) {
10054        let multibuffer = self.buffer().read(cx);
10055        let Some(buffer) = multibuffer.as_singleton() else {
10056            return;
10057        };
10058        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10059            return;
10060        };
10061        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10062            return;
10063        };
10064        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10065            s.select_anchor_ranges([start..end])
10066        });
10067    }
10068
10069    fn go_to_diagnostic(
10070        &mut self,
10071        _: &GoToDiagnostic,
10072        window: &mut Window,
10073        cx: &mut Context<Self>,
10074    ) {
10075        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10076    }
10077
10078    fn go_to_prev_diagnostic(
10079        &mut self,
10080        _: &GoToPrevDiagnostic,
10081        window: &mut Window,
10082        cx: &mut Context<Self>,
10083    ) {
10084        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10085    }
10086
10087    pub fn go_to_diagnostic_impl(
10088        &mut self,
10089        direction: Direction,
10090        window: &mut Window,
10091        cx: &mut Context<Self>,
10092    ) {
10093        let buffer = self.buffer.read(cx).snapshot(cx);
10094        let selection = self.selections.newest::<usize>(cx);
10095
10096        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10097        if direction == Direction::Next {
10098            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10099                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10100                    return;
10101                };
10102                self.activate_diagnostics(
10103                    buffer_id,
10104                    popover.local_diagnostic.diagnostic.group_id,
10105                    window,
10106                    cx,
10107                );
10108                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10109                    let primary_range_start = active_diagnostics.primary_range.start;
10110                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10111                        let mut new_selection = s.newest_anchor().clone();
10112                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10113                        s.select_anchors(vec![new_selection.clone()]);
10114                    });
10115                    self.refresh_inline_completion(false, true, window, cx);
10116                }
10117                return;
10118            }
10119        }
10120
10121        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10122            active_diagnostics
10123                .primary_range
10124                .to_offset(&buffer)
10125                .to_inclusive()
10126        });
10127        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10128            if active_primary_range.contains(&selection.head()) {
10129                *active_primary_range.start()
10130            } else {
10131                selection.head()
10132            }
10133        } else {
10134            selection.head()
10135        };
10136        let snapshot = self.snapshot(window, cx);
10137        loop {
10138            let mut diagnostics;
10139            if direction == Direction::Prev {
10140                diagnostics = buffer
10141                    .diagnostics_in_range::<usize>(0..search_start)
10142                    .collect::<Vec<_>>();
10143                diagnostics.reverse();
10144            } else {
10145                diagnostics = buffer
10146                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10147                    .collect::<Vec<_>>();
10148            };
10149            let group = diagnostics
10150                .into_iter()
10151                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10152                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10153                // be sorted in a stable way
10154                // skip until we are at current active diagnostic, if it exists
10155                .skip_while(|entry| {
10156                    let is_in_range = match direction {
10157                        Direction::Prev => entry.range.end > search_start,
10158                        Direction::Next => entry.range.start < search_start,
10159                    };
10160                    is_in_range
10161                        && self
10162                            .active_diagnostics
10163                            .as_ref()
10164                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10165                })
10166                .find_map(|entry| {
10167                    if entry.diagnostic.is_primary
10168                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10169                        && entry.range.start != entry.range.end
10170                        // if we match with the active diagnostic, skip it
10171                        && Some(entry.diagnostic.group_id)
10172                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10173                    {
10174                        Some((entry.range, entry.diagnostic.group_id))
10175                    } else {
10176                        None
10177                    }
10178                });
10179
10180            if let Some((primary_range, group_id)) = group {
10181                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10182                    return;
10183                };
10184                self.activate_diagnostics(buffer_id, group_id, window, cx);
10185                if self.active_diagnostics.is_some() {
10186                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10187                        s.select(vec![Selection {
10188                            id: selection.id,
10189                            start: primary_range.start,
10190                            end: primary_range.start,
10191                            reversed: false,
10192                            goal: SelectionGoal::None,
10193                        }]);
10194                    });
10195                    self.refresh_inline_completion(false, true, window, cx);
10196                }
10197                break;
10198            } else {
10199                // Cycle around to the start of the buffer, potentially moving back to the start of
10200                // the currently active diagnostic.
10201                active_primary_range.take();
10202                if direction == Direction::Prev {
10203                    if search_start == buffer.len() {
10204                        break;
10205                    } else {
10206                        search_start = buffer.len();
10207                    }
10208                } else if search_start == 0 {
10209                    break;
10210                } else {
10211                    search_start = 0;
10212                }
10213            }
10214        }
10215    }
10216
10217    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10218        let snapshot = self.snapshot(window, cx);
10219        let selection = self.selections.newest::<Point>(cx);
10220        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10221    }
10222
10223    fn go_to_hunk_after_position(
10224        &mut self,
10225        snapshot: &EditorSnapshot,
10226        position: Point,
10227        window: &mut Window,
10228        cx: &mut Context<Editor>,
10229    ) -> Option<MultiBufferDiffHunk> {
10230        let mut hunk = snapshot
10231            .buffer_snapshot
10232            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10233            .find(|hunk| hunk.row_range.start.0 > position.row);
10234        if hunk.is_none() {
10235            hunk = snapshot
10236                .buffer_snapshot
10237                .diff_hunks_in_range(Point::zero()..position)
10238                .find(|hunk| hunk.row_range.end.0 < position.row)
10239        }
10240        if let Some(hunk) = &hunk {
10241            let destination = Point::new(hunk.row_range.start.0, 0);
10242            self.unfold_ranges(&[destination..destination], false, false, cx);
10243            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10244                s.select_ranges(vec![destination..destination]);
10245            });
10246        }
10247
10248        hunk
10249    }
10250
10251    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10252        let snapshot = self.snapshot(window, cx);
10253        let selection = self.selections.newest::<Point>(cx);
10254        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10255    }
10256
10257    fn go_to_hunk_before_position(
10258        &mut self,
10259        snapshot: &EditorSnapshot,
10260        position: Point,
10261        window: &mut Window,
10262        cx: &mut Context<Editor>,
10263    ) -> Option<MultiBufferDiffHunk> {
10264        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10265        if hunk.is_none() {
10266            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10267        }
10268        if let Some(hunk) = &hunk {
10269            let destination = Point::new(hunk.row_range.start.0, 0);
10270            self.unfold_ranges(&[destination..destination], false, false, cx);
10271            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10272                s.select_ranges(vec![destination..destination]);
10273            });
10274        }
10275
10276        hunk
10277    }
10278
10279    pub fn go_to_definition(
10280        &mut self,
10281        _: &GoToDefinition,
10282        window: &mut Window,
10283        cx: &mut Context<Self>,
10284    ) -> Task<Result<Navigated>> {
10285        let definition =
10286            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10287        cx.spawn_in(window, |editor, mut cx| async move {
10288            if definition.await? == Navigated::Yes {
10289                return Ok(Navigated::Yes);
10290            }
10291            match editor.update_in(&mut cx, |editor, window, cx| {
10292                editor.find_all_references(&FindAllReferences, window, cx)
10293            })? {
10294                Some(references) => references.await,
10295                None => Ok(Navigated::No),
10296            }
10297        })
10298    }
10299
10300    pub fn go_to_declaration(
10301        &mut self,
10302        _: &GoToDeclaration,
10303        window: &mut Window,
10304        cx: &mut Context<Self>,
10305    ) -> Task<Result<Navigated>> {
10306        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10307    }
10308
10309    pub fn go_to_declaration_split(
10310        &mut self,
10311        _: &GoToDeclaration,
10312        window: &mut Window,
10313        cx: &mut Context<Self>,
10314    ) -> Task<Result<Navigated>> {
10315        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10316    }
10317
10318    pub fn go_to_implementation(
10319        &mut self,
10320        _: &GoToImplementation,
10321        window: &mut Window,
10322        cx: &mut Context<Self>,
10323    ) -> Task<Result<Navigated>> {
10324        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10325    }
10326
10327    pub fn go_to_implementation_split(
10328        &mut self,
10329        _: &GoToImplementationSplit,
10330        window: &mut Window,
10331        cx: &mut Context<Self>,
10332    ) -> Task<Result<Navigated>> {
10333        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10334    }
10335
10336    pub fn go_to_type_definition(
10337        &mut self,
10338        _: &GoToTypeDefinition,
10339        window: &mut Window,
10340        cx: &mut Context<Self>,
10341    ) -> Task<Result<Navigated>> {
10342        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10343    }
10344
10345    pub fn go_to_definition_split(
10346        &mut self,
10347        _: &GoToDefinitionSplit,
10348        window: &mut Window,
10349        cx: &mut Context<Self>,
10350    ) -> Task<Result<Navigated>> {
10351        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10352    }
10353
10354    pub fn go_to_type_definition_split(
10355        &mut self,
10356        _: &GoToTypeDefinitionSplit,
10357        window: &mut Window,
10358        cx: &mut Context<Self>,
10359    ) -> Task<Result<Navigated>> {
10360        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10361    }
10362
10363    fn go_to_definition_of_kind(
10364        &mut self,
10365        kind: GotoDefinitionKind,
10366        split: bool,
10367        window: &mut Window,
10368        cx: &mut Context<Self>,
10369    ) -> Task<Result<Navigated>> {
10370        let Some(provider) = self.semantics_provider.clone() else {
10371            return Task::ready(Ok(Navigated::No));
10372        };
10373        let head = self.selections.newest::<usize>(cx).head();
10374        let buffer = self.buffer.read(cx);
10375        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10376            text_anchor
10377        } else {
10378            return Task::ready(Ok(Navigated::No));
10379        };
10380
10381        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10382            return Task::ready(Ok(Navigated::No));
10383        };
10384
10385        cx.spawn_in(window, |editor, mut cx| async move {
10386            let definitions = definitions.await?;
10387            let navigated = editor
10388                .update_in(&mut cx, |editor, window, cx| {
10389                    editor.navigate_to_hover_links(
10390                        Some(kind),
10391                        definitions
10392                            .into_iter()
10393                            .filter(|location| {
10394                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10395                            })
10396                            .map(HoverLink::Text)
10397                            .collect::<Vec<_>>(),
10398                        split,
10399                        window,
10400                        cx,
10401                    )
10402                })?
10403                .await?;
10404            anyhow::Ok(navigated)
10405        })
10406    }
10407
10408    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10409        let selection = self.selections.newest_anchor();
10410        let head = selection.head();
10411        let tail = selection.tail();
10412
10413        let Some((buffer, start_position)) =
10414            self.buffer.read(cx).text_anchor_for_position(head, cx)
10415        else {
10416            return;
10417        };
10418
10419        let end_position = if head != tail {
10420            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10421                return;
10422            };
10423            Some(pos)
10424        } else {
10425            None
10426        };
10427
10428        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10429            let url = if let Some(end_pos) = end_position {
10430                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10431            } else {
10432                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10433            };
10434
10435            if let Some(url) = url {
10436                editor.update(&mut cx, |_, cx| {
10437                    cx.open_url(&url);
10438                })
10439            } else {
10440                Ok(())
10441            }
10442        });
10443
10444        url_finder.detach();
10445    }
10446
10447    pub fn open_selected_filename(
10448        &mut self,
10449        _: &OpenSelectedFilename,
10450        window: &mut Window,
10451        cx: &mut Context<Self>,
10452    ) {
10453        let Some(workspace) = self.workspace() else {
10454            return;
10455        };
10456
10457        let position = self.selections.newest_anchor().head();
10458
10459        let Some((buffer, buffer_position)) =
10460            self.buffer.read(cx).text_anchor_for_position(position, cx)
10461        else {
10462            return;
10463        };
10464
10465        let project = self.project.clone();
10466
10467        cx.spawn_in(window, |_, mut cx| async move {
10468            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10469
10470            if let Some((_, path)) = result {
10471                workspace
10472                    .update_in(&mut cx, |workspace, window, cx| {
10473                        workspace.open_resolved_path(path, window, cx)
10474                    })?
10475                    .await?;
10476            }
10477            anyhow::Ok(())
10478        })
10479        .detach();
10480    }
10481
10482    pub(crate) fn navigate_to_hover_links(
10483        &mut self,
10484        kind: Option<GotoDefinitionKind>,
10485        mut definitions: Vec<HoverLink>,
10486        split: bool,
10487        window: &mut Window,
10488        cx: &mut Context<Editor>,
10489    ) -> Task<Result<Navigated>> {
10490        // If there is one definition, just open it directly
10491        if definitions.len() == 1 {
10492            let definition = definitions.pop().unwrap();
10493
10494            enum TargetTaskResult {
10495                Location(Option<Location>),
10496                AlreadyNavigated,
10497            }
10498
10499            let target_task = match definition {
10500                HoverLink::Text(link) => {
10501                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10502                }
10503                HoverLink::InlayHint(lsp_location, server_id) => {
10504                    let computation =
10505                        self.compute_target_location(lsp_location, server_id, window, cx);
10506                    cx.background_executor().spawn(async move {
10507                        let location = computation.await?;
10508                        Ok(TargetTaskResult::Location(location))
10509                    })
10510                }
10511                HoverLink::Url(url) => {
10512                    cx.open_url(&url);
10513                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10514                }
10515                HoverLink::File(path) => {
10516                    if let Some(workspace) = self.workspace() {
10517                        cx.spawn_in(window, |_, mut cx| async move {
10518                            workspace
10519                                .update_in(&mut cx, |workspace, window, cx| {
10520                                    workspace.open_resolved_path(path, window, cx)
10521                                })?
10522                                .await
10523                                .map(|_| TargetTaskResult::AlreadyNavigated)
10524                        })
10525                    } else {
10526                        Task::ready(Ok(TargetTaskResult::Location(None)))
10527                    }
10528                }
10529            };
10530            cx.spawn_in(window, |editor, mut cx| async move {
10531                let target = match target_task.await.context("target resolution task")? {
10532                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10533                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10534                    TargetTaskResult::Location(Some(target)) => target,
10535                };
10536
10537                editor.update_in(&mut cx, |editor, window, cx| {
10538                    let Some(workspace) = editor.workspace() else {
10539                        return Navigated::No;
10540                    };
10541                    let pane = workspace.read(cx).active_pane().clone();
10542
10543                    let range = target.range.to_point(target.buffer.read(cx));
10544                    let range = editor.range_for_match(&range);
10545                    let range = collapse_multiline_range(range);
10546
10547                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10548                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10549                    } else {
10550                        window.defer(cx, move |window, cx| {
10551                            let target_editor: Entity<Self> =
10552                                workspace.update(cx, |workspace, cx| {
10553                                    let pane = if split {
10554                                        workspace.adjacent_pane(window, cx)
10555                                    } else {
10556                                        workspace.active_pane().clone()
10557                                    };
10558
10559                                    workspace.open_project_item(
10560                                        pane,
10561                                        target.buffer.clone(),
10562                                        true,
10563                                        true,
10564                                        window,
10565                                        cx,
10566                                    )
10567                                });
10568                            target_editor.update(cx, |target_editor, cx| {
10569                                // When selecting a definition in a different buffer, disable the nav history
10570                                // to avoid creating a history entry at the previous cursor location.
10571                                pane.update(cx, |pane, _| pane.disable_history());
10572                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10573                                pane.update(cx, |pane, _| pane.enable_history());
10574                            });
10575                        });
10576                    }
10577                    Navigated::Yes
10578                })
10579            })
10580        } else if !definitions.is_empty() {
10581            cx.spawn_in(window, |editor, mut cx| async move {
10582                let (title, location_tasks, workspace) = editor
10583                    .update_in(&mut cx, |editor, window, cx| {
10584                        let tab_kind = match kind {
10585                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10586                            _ => "Definitions",
10587                        };
10588                        let title = definitions
10589                            .iter()
10590                            .find_map(|definition| match definition {
10591                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10592                                    let buffer = origin.buffer.read(cx);
10593                                    format!(
10594                                        "{} for {}",
10595                                        tab_kind,
10596                                        buffer
10597                                            .text_for_range(origin.range.clone())
10598                                            .collect::<String>()
10599                                    )
10600                                }),
10601                                HoverLink::InlayHint(_, _) => None,
10602                                HoverLink::Url(_) => None,
10603                                HoverLink::File(_) => None,
10604                            })
10605                            .unwrap_or(tab_kind.to_string());
10606                        let location_tasks = definitions
10607                            .into_iter()
10608                            .map(|definition| match definition {
10609                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10610                                HoverLink::InlayHint(lsp_location, server_id) => editor
10611                                    .compute_target_location(lsp_location, server_id, window, cx),
10612                                HoverLink::Url(_) => Task::ready(Ok(None)),
10613                                HoverLink::File(_) => Task::ready(Ok(None)),
10614                            })
10615                            .collect::<Vec<_>>();
10616                        (title, location_tasks, editor.workspace().clone())
10617                    })
10618                    .context("location tasks preparation")?;
10619
10620                let locations = future::join_all(location_tasks)
10621                    .await
10622                    .into_iter()
10623                    .filter_map(|location| location.transpose())
10624                    .collect::<Result<_>>()
10625                    .context("location tasks")?;
10626
10627                let Some(workspace) = workspace else {
10628                    return Ok(Navigated::No);
10629                };
10630                let opened = workspace
10631                    .update_in(&mut cx, |workspace, window, cx| {
10632                        Self::open_locations_in_multibuffer(
10633                            workspace,
10634                            locations,
10635                            title,
10636                            split,
10637                            MultibufferSelectionMode::First,
10638                            window,
10639                            cx,
10640                        )
10641                    })
10642                    .ok();
10643
10644                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10645            })
10646        } else {
10647            Task::ready(Ok(Navigated::No))
10648        }
10649    }
10650
10651    fn compute_target_location(
10652        &self,
10653        lsp_location: lsp::Location,
10654        server_id: LanguageServerId,
10655        window: &mut Window,
10656        cx: &mut Context<Self>,
10657    ) -> Task<anyhow::Result<Option<Location>>> {
10658        let Some(project) = self.project.clone() else {
10659            return Task::ready(Ok(None));
10660        };
10661
10662        cx.spawn_in(window, move |editor, mut cx| async move {
10663            let location_task = editor.update(&mut cx, |_, cx| {
10664                project.update(cx, |project, cx| {
10665                    let language_server_name = project
10666                        .language_server_statuses(cx)
10667                        .find(|(id, _)| server_id == *id)
10668                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10669                    language_server_name.map(|language_server_name| {
10670                        project.open_local_buffer_via_lsp(
10671                            lsp_location.uri.clone(),
10672                            server_id,
10673                            language_server_name,
10674                            cx,
10675                        )
10676                    })
10677                })
10678            })?;
10679            let location = match location_task {
10680                Some(task) => Some({
10681                    let target_buffer_handle = task.await.context("open local buffer")?;
10682                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10683                        let target_start = target_buffer
10684                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10685                        let target_end = target_buffer
10686                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10687                        target_buffer.anchor_after(target_start)
10688                            ..target_buffer.anchor_before(target_end)
10689                    })?;
10690                    Location {
10691                        buffer: target_buffer_handle,
10692                        range,
10693                    }
10694                }),
10695                None => None,
10696            };
10697            Ok(location)
10698        })
10699    }
10700
10701    pub fn find_all_references(
10702        &mut self,
10703        _: &FindAllReferences,
10704        window: &mut Window,
10705        cx: &mut Context<Self>,
10706    ) -> Option<Task<Result<Navigated>>> {
10707        let selection = self.selections.newest::<usize>(cx);
10708        let multi_buffer = self.buffer.read(cx);
10709        let head = selection.head();
10710
10711        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10712        let head_anchor = multi_buffer_snapshot.anchor_at(
10713            head,
10714            if head < selection.tail() {
10715                Bias::Right
10716            } else {
10717                Bias::Left
10718            },
10719        );
10720
10721        match self
10722            .find_all_references_task_sources
10723            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10724        {
10725            Ok(_) => {
10726                log::info!(
10727                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10728                );
10729                return None;
10730            }
10731            Err(i) => {
10732                self.find_all_references_task_sources.insert(i, head_anchor);
10733            }
10734        }
10735
10736        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10737        let workspace = self.workspace()?;
10738        let project = workspace.read(cx).project().clone();
10739        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10740        Some(cx.spawn_in(window, |editor, mut cx| async move {
10741            let _cleanup = defer({
10742                let mut cx = cx.clone();
10743                move || {
10744                    let _ = editor.update(&mut cx, |editor, _| {
10745                        if let Ok(i) =
10746                            editor
10747                                .find_all_references_task_sources
10748                                .binary_search_by(|anchor| {
10749                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10750                                })
10751                        {
10752                            editor.find_all_references_task_sources.remove(i);
10753                        }
10754                    });
10755                }
10756            });
10757
10758            let locations = references.await?;
10759            if locations.is_empty() {
10760                return anyhow::Ok(Navigated::No);
10761            }
10762
10763            workspace.update_in(&mut cx, |workspace, window, cx| {
10764                let title = locations
10765                    .first()
10766                    .as_ref()
10767                    .map(|location| {
10768                        let buffer = location.buffer.read(cx);
10769                        format!(
10770                            "References to `{}`",
10771                            buffer
10772                                .text_for_range(location.range.clone())
10773                                .collect::<String>()
10774                        )
10775                    })
10776                    .unwrap();
10777                Self::open_locations_in_multibuffer(
10778                    workspace,
10779                    locations,
10780                    title,
10781                    false,
10782                    MultibufferSelectionMode::First,
10783                    window,
10784                    cx,
10785                );
10786                Navigated::Yes
10787            })
10788        }))
10789    }
10790
10791    /// Opens a multibuffer with the given project locations in it
10792    pub fn open_locations_in_multibuffer(
10793        workspace: &mut Workspace,
10794        mut locations: Vec<Location>,
10795        title: String,
10796        split: bool,
10797        multibuffer_selection_mode: MultibufferSelectionMode,
10798        window: &mut Window,
10799        cx: &mut Context<Workspace>,
10800    ) {
10801        // If there are multiple definitions, open them in a multibuffer
10802        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10803        let mut locations = locations.into_iter().peekable();
10804        let mut ranges = Vec::new();
10805        let capability = workspace.project().read(cx).capability();
10806
10807        let excerpt_buffer = cx.new(|cx| {
10808            let mut multibuffer = MultiBuffer::new(capability);
10809            while let Some(location) = locations.next() {
10810                let buffer = location.buffer.read(cx);
10811                let mut ranges_for_buffer = Vec::new();
10812                let range = location.range.to_offset(buffer);
10813                ranges_for_buffer.push(range.clone());
10814
10815                while let Some(next_location) = locations.peek() {
10816                    if next_location.buffer == location.buffer {
10817                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10818                        locations.next();
10819                    } else {
10820                        break;
10821                    }
10822                }
10823
10824                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10825                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10826                    location.buffer.clone(),
10827                    ranges_for_buffer,
10828                    DEFAULT_MULTIBUFFER_CONTEXT,
10829                    cx,
10830                ))
10831            }
10832
10833            multibuffer.with_title(title)
10834        });
10835
10836        let editor = cx.new(|cx| {
10837            Editor::for_multibuffer(
10838                excerpt_buffer,
10839                Some(workspace.project().clone()),
10840                true,
10841                window,
10842                cx,
10843            )
10844        });
10845        editor.update(cx, |editor, cx| {
10846            match multibuffer_selection_mode {
10847                MultibufferSelectionMode::First => {
10848                    if let Some(first_range) = ranges.first() {
10849                        editor.change_selections(None, window, cx, |selections| {
10850                            selections.clear_disjoint();
10851                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10852                        });
10853                    }
10854                    editor.highlight_background::<Self>(
10855                        &ranges,
10856                        |theme| theme.editor_highlighted_line_background,
10857                        cx,
10858                    );
10859                }
10860                MultibufferSelectionMode::All => {
10861                    editor.change_selections(None, window, cx, |selections| {
10862                        selections.clear_disjoint();
10863                        selections.select_anchor_ranges(ranges);
10864                    });
10865                }
10866            }
10867            editor.register_buffers_with_language_servers(cx);
10868        });
10869
10870        let item = Box::new(editor);
10871        let item_id = item.item_id();
10872
10873        if split {
10874            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10875        } else {
10876            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10877                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10878                    pane.close_current_preview_item(window, cx)
10879                } else {
10880                    None
10881                }
10882            });
10883            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10884        }
10885        workspace.active_pane().update(cx, |pane, cx| {
10886            pane.set_preview_item_id(Some(item_id), cx);
10887        });
10888    }
10889
10890    pub fn rename(
10891        &mut self,
10892        _: &Rename,
10893        window: &mut Window,
10894        cx: &mut Context<Self>,
10895    ) -> Option<Task<Result<()>>> {
10896        use language::ToOffset as _;
10897
10898        let provider = self.semantics_provider.clone()?;
10899        let selection = self.selections.newest_anchor().clone();
10900        let (cursor_buffer, cursor_buffer_position) = self
10901            .buffer
10902            .read(cx)
10903            .text_anchor_for_position(selection.head(), cx)?;
10904        let (tail_buffer, cursor_buffer_position_end) = self
10905            .buffer
10906            .read(cx)
10907            .text_anchor_for_position(selection.tail(), cx)?;
10908        if tail_buffer != cursor_buffer {
10909            return None;
10910        }
10911
10912        let snapshot = cursor_buffer.read(cx).snapshot();
10913        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10914        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10915        let prepare_rename = provider
10916            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10917            .unwrap_or_else(|| Task::ready(Ok(None)));
10918        drop(snapshot);
10919
10920        Some(cx.spawn_in(window, |this, mut cx| async move {
10921            let rename_range = if let Some(range) = prepare_rename.await? {
10922                Some(range)
10923            } else {
10924                this.update(&mut cx, |this, cx| {
10925                    let buffer = this.buffer.read(cx).snapshot(cx);
10926                    let mut buffer_highlights = this
10927                        .document_highlights_for_position(selection.head(), &buffer)
10928                        .filter(|highlight| {
10929                            highlight.start.excerpt_id == selection.head().excerpt_id
10930                                && highlight.end.excerpt_id == selection.head().excerpt_id
10931                        });
10932                    buffer_highlights
10933                        .next()
10934                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10935                })?
10936            };
10937            if let Some(rename_range) = rename_range {
10938                this.update_in(&mut cx, |this, window, cx| {
10939                    let snapshot = cursor_buffer.read(cx).snapshot();
10940                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10941                    let cursor_offset_in_rename_range =
10942                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10943                    let cursor_offset_in_rename_range_end =
10944                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10945
10946                    this.take_rename(false, window, cx);
10947                    let buffer = this.buffer.read(cx).read(cx);
10948                    let cursor_offset = selection.head().to_offset(&buffer);
10949                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10950                    let rename_end = rename_start + rename_buffer_range.len();
10951                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10952                    let mut old_highlight_id = None;
10953                    let old_name: Arc<str> = buffer
10954                        .chunks(rename_start..rename_end, true)
10955                        .map(|chunk| {
10956                            if old_highlight_id.is_none() {
10957                                old_highlight_id = chunk.syntax_highlight_id;
10958                            }
10959                            chunk.text
10960                        })
10961                        .collect::<String>()
10962                        .into();
10963
10964                    drop(buffer);
10965
10966                    // Position the selection in the rename editor so that it matches the current selection.
10967                    this.show_local_selections = false;
10968                    let rename_editor = cx.new(|cx| {
10969                        let mut editor = Editor::single_line(window, cx);
10970                        editor.buffer.update(cx, |buffer, cx| {
10971                            buffer.edit([(0..0, old_name.clone())], None, cx)
10972                        });
10973                        let rename_selection_range = match cursor_offset_in_rename_range
10974                            .cmp(&cursor_offset_in_rename_range_end)
10975                        {
10976                            Ordering::Equal => {
10977                                editor.select_all(&SelectAll, window, cx);
10978                                return editor;
10979                            }
10980                            Ordering::Less => {
10981                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10982                            }
10983                            Ordering::Greater => {
10984                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10985                            }
10986                        };
10987                        if rename_selection_range.end > old_name.len() {
10988                            editor.select_all(&SelectAll, window, cx);
10989                        } else {
10990                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10991                                s.select_ranges([rename_selection_range]);
10992                            });
10993                        }
10994                        editor
10995                    });
10996                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10997                        if e == &EditorEvent::Focused {
10998                            cx.emit(EditorEvent::FocusedIn)
10999                        }
11000                    })
11001                    .detach();
11002
11003                    let write_highlights =
11004                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11005                    let read_highlights =
11006                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11007                    let ranges = write_highlights
11008                        .iter()
11009                        .flat_map(|(_, ranges)| ranges.iter())
11010                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11011                        .cloned()
11012                        .collect();
11013
11014                    this.highlight_text::<Rename>(
11015                        ranges,
11016                        HighlightStyle {
11017                            fade_out: Some(0.6),
11018                            ..Default::default()
11019                        },
11020                        cx,
11021                    );
11022                    let rename_focus_handle = rename_editor.focus_handle(cx);
11023                    window.focus(&rename_focus_handle);
11024                    let block_id = this.insert_blocks(
11025                        [BlockProperties {
11026                            style: BlockStyle::Flex,
11027                            placement: BlockPlacement::Below(range.start),
11028                            height: 1,
11029                            render: Arc::new({
11030                                let rename_editor = rename_editor.clone();
11031                                move |cx: &mut BlockContext| {
11032                                    let mut text_style = cx.editor_style.text.clone();
11033                                    if let Some(highlight_style) = old_highlight_id
11034                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11035                                    {
11036                                        text_style = text_style.highlight(highlight_style);
11037                                    }
11038                                    div()
11039                                        .block_mouse_down()
11040                                        .pl(cx.anchor_x)
11041                                        .child(EditorElement::new(
11042                                            &rename_editor,
11043                                            EditorStyle {
11044                                                background: cx.theme().system().transparent,
11045                                                local_player: cx.editor_style.local_player,
11046                                                text: text_style,
11047                                                scrollbar_width: cx.editor_style.scrollbar_width,
11048                                                syntax: cx.editor_style.syntax.clone(),
11049                                                status: cx.editor_style.status.clone(),
11050                                                inlay_hints_style: HighlightStyle {
11051                                                    font_weight: Some(FontWeight::BOLD),
11052                                                    ..make_inlay_hints_style(cx.app)
11053                                                },
11054                                                inline_completion_styles: make_suggestion_styles(
11055                                                    cx.app,
11056                                                ),
11057                                                ..EditorStyle::default()
11058                                            },
11059                                        ))
11060                                        .into_any_element()
11061                                }
11062                            }),
11063                            priority: 0,
11064                        }],
11065                        Some(Autoscroll::fit()),
11066                        cx,
11067                    )[0];
11068                    this.pending_rename = Some(RenameState {
11069                        range,
11070                        old_name,
11071                        editor: rename_editor,
11072                        block_id,
11073                    });
11074                })?;
11075            }
11076
11077            Ok(())
11078        }))
11079    }
11080
11081    pub fn confirm_rename(
11082        &mut self,
11083        _: &ConfirmRename,
11084        window: &mut Window,
11085        cx: &mut Context<Self>,
11086    ) -> Option<Task<Result<()>>> {
11087        let rename = self.take_rename(false, window, cx)?;
11088        let workspace = self.workspace()?.downgrade();
11089        let (buffer, start) = self
11090            .buffer
11091            .read(cx)
11092            .text_anchor_for_position(rename.range.start, cx)?;
11093        let (end_buffer, _) = self
11094            .buffer
11095            .read(cx)
11096            .text_anchor_for_position(rename.range.end, cx)?;
11097        if buffer != end_buffer {
11098            return None;
11099        }
11100
11101        let old_name = rename.old_name;
11102        let new_name = rename.editor.read(cx).text(cx);
11103
11104        let rename = self.semantics_provider.as_ref()?.perform_rename(
11105            &buffer,
11106            start,
11107            new_name.clone(),
11108            cx,
11109        )?;
11110
11111        Some(cx.spawn_in(window, |editor, mut cx| async move {
11112            let project_transaction = rename.await?;
11113            Self::open_project_transaction(
11114                &editor,
11115                workspace,
11116                project_transaction,
11117                format!("Rename: {}{}", old_name, new_name),
11118                cx.clone(),
11119            )
11120            .await?;
11121
11122            editor.update(&mut cx, |editor, cx| {
11123                editor.refresh_document_highlights(cx);
11124            })?;
11125            Ok(())
11126        }))
11127    }
11128
11129    fn take_rename(
11130        &mut self,
11131        moving_cursor: bool,
11132        window: &mut Window,
11133        cx: &mut Context<Self>,
11134    ) -> Option<RenameState> {
11135        let rename = self.pending_rename.take()?;
11136        if rename.editor.focus_handle(cx).is_focused(window) {
11137            window.focus(&self.focus_handle);
11138        }
11139
11140        self.remove_blocks(
11141            [rename.block_id].into_iter().collect(),
11142            Some(Autoscroll::fit()),
11143            cx,
11144        );
11145        self.clear_highlights::<Rename>(cx);
11146        self.show_local_selections = true;
11147
11148        if moving_cursor {
11149            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11150                editor.selections.newest::<usize>(cx).head()
11151            });
11152
11153            // Update the selection to match the position of the selection inside
11154            // the rename editor.
11155            let snapshot = self.buffer.read(cx).read(cx);
11156            let rename_range = rename.range.to_offset(&snapshot);
11157            let cursor_in_editor = snapshot
11158                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11159                .min(rename_range.end);
11160            drop(snapshot);
11161
11162            self.change_selections(None, window, cx, |s| {
11163                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11164            });
11165        } else {
11166            self.refresh_document_highlights(cx);
11167        }
11168
11169        Some(rename)
11170    }
11171
11172    pub fn pending_rename(&self) -> Option<&RenameState> {
11173        self.pending_rename.as_ref()
11174    }
11175
11176    fn format(
11177        &mut self,
11178        _: &Format,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) -> Option<Task<Result<()>>> {
11182        let project = match &self.project {
11183            Some(project) => project.clone(),
11184            None => return None,
11185        };
11186
11187        Some(self.perform_format(
11188            project,
11189            FormatTrigger::Manual,
11190            FormatTarget::Buffers,
11191            window,
11192            cx,
11193        ))
11194    }
11195
11196    fn format_selections(
11197        &mut self,
11198        _: &FormatSelections,
11199        window: &mut Window,
11200        cx: &mut Context<Self>,
11201    ) -> Option<Task<Result<()>>> {
11202        let project = match &self.project {
11203            Some(project) => project.clone(),
11204            None => return None,
11205        };
11206
11207        let ranges = self
11208            .selections
11209            .all_adjusted(cx)
11210            .into_iter()
11211            .map(|selection| selection.range())
11212            .collect_vec();
11213
11214        Some(self.perform_format(
11215            project,
11216            FormatTrigger::Manual,
11217            FormatTarget::Ranges(ranges),
11218            window,
11219            cx,
11220        ))
11221    }
11222
11223    fn perform_format(
11224        &mut self,
11225        project: Entity<Project>,
11226        trigger: FormatTrigger,
11227        target: FormatTarget,
11228        window: &mut Window,
11229        cx: &mut Context<Self>,
11230    ) -> Task<Result<()>> {
11231        let buffer = self.buffer.clone();
11232        let (buffers, target) = match target {
11233            FormatTarget::Buffers => {
11234                let mut buffers = buffer.read(cx).all_buffers();
11235                if trigger == FormatTrigger::Save {
11236                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11237                }
11238                (buffers, LspFormatTarget::Buffers)
11239            }
11240            FormatTarget::Ranges(selection_ranges) => {
11241                let multi_buffer = buffer.read(cx);
11242                let snapshot = multi_buffer.read(cx);
11243                let mut buffers = HashSet::default();
11244                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11245                    BTreeMap::new();
11246                for selection_range in selection_ranges {
11247                    for (buffer, buffer_range, _) in
11248                        snapshot.range_to_buffer_ranges(selection_range)
11249                    {
11250                        let buffer_id = buffer.remote_id();
11251                        let start = buffer.anchor_before(buffer_range.start);
11252                        let end = buffer.anchor_after(buffer_range.end);
11253                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11254                        buffer_id_to_ranges
11255                            .entry(buffer_id)
11256                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11257                            .or_insert_with(|| vec![start..end]);
11258                    }
11259                }
11260                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11261            }
11262        };
11263
11264        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11265        let format = project.update(cx, |project, cx| {
11266            project.format(buffers, target, true, trigger, cx)
11267        });
11268
11269        cx.spawn_in(window, |_, mut cx| async move {
11270            let transaction = futures::select_biased! {
11271                () = timeout => {
11272                    log::warn!("timed out waiting for formatting");
11273                    None
11274                }
11275                transaction = format.log_err().fuse() => transaction,
11276            };
11277
11278            buffer
11279                .update(&mut cx, |buffer, cx| {
11280                    if let Some(transaction) = transaction {
11281                        if !buffer.is_singleton() {
11282                            buffer.push_transaction(&transaction.0, cx);
11283                        }
11284                    }
11285
11286                    cx.notify();
11287                })
11288                .ok();
11289
11290            Ok(())
11291        })
11292    }
11293
11294    fn restart_language_server(
11295        &mut self,
11296        _: &RestartLanguageServer,
11297        _: &mut Window,
11298        cx: &mut Context<Self>,
11299    ) {
11300        if let Some(project) = self.project.clone() {
11301            self.buffer.update(cx, |multi_buffer, cx| {
11302                project.update(cx, |project, cx| {
11303                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11304                });
11305            })
11306        }
11307    }
11308
11309    fn cancel_language_server_work(
11310        workspace: &mut Workspace,
11311        _: &actions::CancelLanguageServerWork,
11312        _: &mut Window,
11313        cx: &mut Context<Workspace>,
11314    ) {
11315        let project = workspace.project();
11316        let buffers = workspace
11317            .active_item(cx)
11318            .and_then(|item| item.act_as::<Editor>(cx))
11319            .map_or(HashSet::default(), |editor| {
11320                editor.read(cx).buffer.read(cx).all_buffers()
11321            });
11322        project.update(cx, |project, cx| {
11323            project.cancel_language_server_work_for_buffers(buffers, cx);
11324        });
11325    }
11326
11327    fn show_character_palette(
11328        &mut self,
11329        _: &ShowCharacterPalette,
11330        window: &mut Window,
11331        _: &mut Context<Self>,
11332    ) {
11333        window.show_character_palette();
11334    }
11335
11336    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11337        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11338            let buffer = self.buffer.read(cx).snapshot(cx);
11339            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11340            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11341            let is_valid = buffer
11342                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11343                .any(|entry| {
11344                    entry.diagnostic.is_primary
11345                        && !entry.range.is_empty()
11346                        && entry.range.start == primary_range_start
11347                        && entry.diagnostic.message == active_diagnostics.primary_message
11348                });
11349
11350            if is_valid != active_diagnostics.is_valid {
11351                active_diagnostics.is_valid = is_valid;
11352                let mut new_styles = HashMap::default();
11353                for (block_id, diagnostic) in &active_diagnostics.blocks {
11354                    new_styles.insert(
11355                        *block_id,
11356                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11357                    );
11358                }
11359                self.display_map.update(cx, |display_map, _cx| {
11360                    display_map.replace_blocks(new_styles)
11361                });
11362            }
11363        }
11364    }
11365
11366    fn activate_diagnostics(
11367        &mut self,
11368        buffer_id: BufferId,
11369        group_id: usize,
11370        window: &mut Window,
11371        cx: &mut Context<Self>,
11372    ) {
11373        self.dismiss_diagnostics(cx);
11374        let snapshot = self.snapshot(window, cx);
11375        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11376            let buffer = self.buffer.read(cx).snapshot(cx);
11377
11378            let mut primary_range = None;
11379            let mut primary_message = None;
11380            let diagnostic_group = buffer
11381                .diagnostic_group(buffer_id, group_id)
11382                .filter_map(|entry| {
11383                    let start = entry.range.start;
11384                    let end = entry.range.end;
11385                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11386                        && (start.row == end.row
11387                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11388                    {
11389                        return None;
11390                    }
11391                    if entry.diagnostic.is_primary {
11392                        primary_range = Some(entry.range.clone());
11393                        primary_message = Some(entry.diagnostic.message.clone());
11394                    }
11395                    Some(entry)
11396                })
11397                .collect::<Vec<_>>();
11398            let primary_range = primary_range?;
11399            let primary_message = primary_message?;
11400
11401            let blocks = display_map
11402                .insert_blocks(
11403                    diagnostic_group.iter().map(|entry| {
11404                        let diagnostic = entry.diagnostic.clone();
11405                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11406                        BlockProperties {
11407                            style: BlockStyle::Fixed,
11408                            placement: BlockPlacement::Below(
11409                                buffer.anchor_after(entry.range.start),
11410                            ),
11411                            height: message_height,
11412                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11413                            priority: 0,
11414                        }
11415                    }),
11416                    cx,
11417                )
11418                .into_iter()
11419                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11420                .collect();
11421
11422            Some(ActiveDiagnosticGroup {
11423                primary_range: buffer.anchor_before(primary_range.start)
11424                    ..buffer.anchor_after(primary_range.end),
11425                primary_message,
11426                group_id,
11427                blocks,
11428                is_valid: true,
11429            })
11430        });
11431    }
11432
11433    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11434        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11435            self.display_map.update(cx, |display_map, cx| {
11436                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11437            });
11438            cx.notify();
11439        }
11440    }
11441
11442    pub fn set_selections_from_remote(
11443        &mut self,
11444        selections: Vec<Selection<Anchor>>,
11445        pending_selection: Option<Selection<Anchor>>,
11446        window: &mut Window,
11447        cx: &mut Context<Self>,
11448    ) {
11449        let old_cursor_position = self.selections.newest_anchor().head();
11450        self.selections.change_with(cx, |s| {
11451            s.select_anchors(selections);
11452            if let Some(pending_selection) = pending_selection {
11453                s.set_pending(pending_selection, SelectMode::Character);
11454            } else {
11455                s.clear_pending();
11456            }
11457        });
11458        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11459    }
11460
11461    fn push_to_selection_history(&mut self) {
11462        self.selection_history.push(SelectionHistoryEntry {
11463            selections: self.selections.disjoint_anchors(),
11464            select_next_state: self.select_next_state.clone(),
11465            select_prev_state: self.select_prev_state.clone(),
11466            add_selections_state: self.add_selections_state.clone(),
11467        });
11468    }
11469
11470    pub fn transact(
11471        &mut self,
11472        window: &mut Window,
11473        cx: &mut Context<Self>,
11474        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11475    ) -> Option<TransactionId> {
11476        self.start_transaction_at(Instant::now(), window, cx);
11477        update(self, window, cx);
11478        self.end_transaction_at(Instant::now(), cx)
11479    }
11480
11481    pub fn start_transaction_at(
11482        &mut self,
11483        now: Instant,
11484        window: &mut Window,
11485        cx: &mut Context<Self>,
11486    ) {
11487        self.end_selection(window, cx);
11488        if let Some(tx_id) = self
11489            .buffer
11490            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11491        {
11492            self.selection_history
11493                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11494            cx.emit(EditorEvent::TransactionBegun {
11495                transaction_id: tx_id,
11496            })
11497        }
11498    }
11499
11500    pub fn end_transaction_at(
11501        &mut self,
11502        now: Instant,
11503        cx: &mut Context<Self>,
11504    ) -> Option<TransactionId> {
11505        if let Some(transaction_id) = self
11506            .buffer
11507            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11508        {
11509            if let Some((_, end_selections)) =
11510                self.selection_history.transaction_mut(transaction_id)
11511            {
11512                *end_selections = Some(self.selections.disjoint_anchors());
11513            } else {
11514                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11515            }
11516
11517            cx.emit(EditorEvent::Edited { transaction_id });
11518            Some(transaction_id)
11519        } else {
11520            None
11521        }
11522    }
11523
11524    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11525        if self.selection_mark_mode {
11526            self.change_selections(None, window, cx, |s| {
11527                s.move_with(|_, sel| {
11528                    sel.collapse_to(sel.head(), SelectionGoal::None);
11529                });
11530            })
11531        }
11532        self.selection_mark_mode = true;
11533        cx.notify();
11534    }
11535
11536    pub fn swap_selection_ends(
11537        &mut self,
11538        _: &actions::SwapSelectionEnds,
11539        window: &mut Window,
11540        cx: &mut Context<Self>,
11541    ) {
11542        self.change_selections(None, window, cx, |s| {
11543            s.move_with(|_, sel| {
11544                if sel.start != sel.end {
11545                    sel.reversed = !sel.reversed
11546                }
11547            });
11548        });
11549        self.request_autoscroll(Autoscroll::newest(), cx);
11550        cx.notify();
11551    }
11552
11553    pub fn toggle_fold(
11554        &mut self,
11555        _: &actions::ToggleFold,
11556        window: &mut Window,
11557        cx: &mut Context<Self>,
11558    ) {
11559        if self.is_singleton(cx) {
11560            let selection = self.selections.newest::<Point>(cx);
11561
11562            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11563            let range = if selection.is_empty() {
11564                let point = selection.head().to_display_point(&display_map);
11565                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11566                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11567                    .to_point(&display_map);
11568                start..end
11569            } else {
11570                selection.range()
11571            };
11572            if display_map.folds_in_range(range).next().is_some() {
11573                self.unfold_lines(&Default::default(), window, cx)
11574            } else {
11575                self.fold(&Default::default(), window, cx)
11576            }
11577        } else {
11578            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11579            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11580                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11581                .map(|(snapshot, _, _)| snapshot.remote_id())
11582                .collect();
11583
11584            for buffer_id in buffer_ids {
11585                if self.is_buffer_folded(buffer_id, cx) {
11586                    self.unfold_buffer(buffer_id, cx);
11587                } else {
11588                    self.fold_buffer(buffer_id, cx);
11589                }
11590            }
11591        }
11592    }
11593
11594    pub fn toggle_fold_recursive(
11595        &mut self,
11596        _: &actions::ToggleFoldRecursive,
11597        window: &mut Window,
11598        cx: &mut Context<Self>,
11599    ) {
11600        let selection = self.selections.newest::<Point>(cx);
11601
11602        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11603        let range = if selection.is_empty() {
11604            let point = selection.head().to_display_point(&display_map);
11605            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11606            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11607                .to_point(&display_map);
11608            start..end
11609        } else {
11610            selection.range()
11611        };
11612        if display_map.folds_in_range(range).next().is_some() {
11613            self.unfold_recursive(&Default::default(), window, cx)
11614        } else {
11615            self.fold_recursive(&Default::default(), window, cx)
11616        }
11617    }
11618
11619    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11620        if self.is_singleton(cx) {
11621            let mut to_fold = Vec::new();
11622            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11623            let selections = self.selections.all_adjusted(cx);
11624
11625            for selection in selections {
11626                let range = selection.range().sorted();
11627                let buffer_start_row = range.start.row;
11628
11629                if range.start.row != range.end.row {
11630                    let mut found = false;
11631                    let mut row = range.start.row;
11632                    while row <= range.end.row {
11633                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11634                        {
11635                            found = true;
11636                            row = crease.range().end.row + 1;
11637                            to_fold.push(crease);
11638                        } else {
11639                            row += 1
11640                        }
11641                    }
11642                    if found {
11643                        continue;
11644                    }
11645                }
11646
11647                for row in (0..=range.start.row).rev() {
11648                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11649                        if crease.range().end.row >= buffer_start_row {
11650                            to_fold.push(crease);
11651                            if row <= range.start.row {
11652                                break;
11653                            }
11654                        }
11655                    }
11656                }
11657            }
11658
11659            self.fold_creases(to_fold, true, window, cx);
11660        } else {
11661            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11662
11663            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11664                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11665                .map(|(snapshot, _, _)| snapshot.remote_id())
11666                .collect();
11667            for buffer_id in buffer_ids {
11668                self.fold_buffer(buffer_id, cx);
11669            }
11670        }
11671    }
11672
11673    fn fold_at_level(
11674        &mut self,
11675        fold_at: &FoldAtLevel,
11676        window: &mut Window,
11677        cx: &mut Context<Self>,
11678    ) {
11679        if !self.buffer.read(cx).is_singleton() {
11680            return;
11681        }
11682
11683        let fold_at_level = fold_at.level;
11684        let snapshot = self.buffer.read(cx).snapshot(cx);
11685        let mut to_fold = Vec::new();
11686        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11687
11688        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11689            while start_row < end_row {
11690                match self
11691                    .snapshot(window, cx)
11692                    .crease_for_buffer_row(MultiBufferRow(start_row))
11693                {
11694                    Some(crease) => {
11695                        let nested_start_row = crease.range().start.row + 1;
11696                        let nested_end_row = crease.range().end.row;
11697
11698                        if current_level < fold_at_level {
11699                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11700                        } else if current_level == fold_at_level {
11701                            to_fold.push(crease);
11702                        }
11703
11704                        start_row = nested_end_row + 1;
11705                    }
11706                    None => start_row += 1,
11707                }
11708            }
11709        }
11710
11711        self.fold_creases(to_fold, true, window, cx);
11712    }
11713
11714    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11715        if self.buffer.read(cx).is_singleton() {
11716            let mut fold_ranges = Vec::new();
11717            let snapshot = self.buffer.read(cx).snapshot(cx);
11718
11719            for row in 0..snapshot.max_row().0 {
11720                if let Some(foldable_range) = self
11721                    .snapshot(window, cx)
11722                    .crease_for_buffer_row(MultiBufferRow(row))
11723                {
11724                    fold_ranges.push(foldable_range);
11725                }
11726            }
11727
11728            self.fold_creases(fold_ranges, true, window, cx);
11729        } else {
11730            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11731                editor
11732                    .update_in(&mut cx, |editor, _, cx| {
11733                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11734                            editor.fold_buffer(buffer_id, cx);
11735                        }
11736                    })
11737                    .ok();
11738            });
11739        }
11740    }
11741
11742    pub fn fold_function_bodies(
11743        &mut self,
11744        _: &actions::FoldFunctionBodies,
11745        window: &mut Window,
11746        cx: &mut Context<Self>,
11747    ) {
11748        let snapshot = self.buffer.read(cx).snapshot(cx);
11749
11750        let ranges = snapshot
11751            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11752            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11753            .collect::<Vec<_>>();
11754
11755        let creases = ranges
11756            .into_iter()
11757            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11758            .collect();
11759
11760        self.fold_creases(creases, true, window, cx);
11761    }
11762
11763    pub fn fold_recursive(
11764        &mut self,
11765        _: &actions::FoldRecursive,
11766        window: &mut Window,
11767        cx: &mut Context<Self>,
11768    ) {
11769        let mut to_fold = Vec::new();
11770        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11771        let selections = self.selections.all_adjusted(cx);
11772
11773        for selection in selections {
11774            let range = selection.range().sorted();
11775            let buffer_start_row = range.start.row;
11776
11777            if range.start.row != range.end.row {
11778                let mut found = false;
11779                for row in range.start.row..=range.end.row {
11780                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11781                        found = true;
11782                        to_fold.push(crease);
11783                    }
11784                }
11785                if found {
11786                    continue;
11787                }
11788            }
11789
11790            for row in (0..=range.start.row).rev() {
11791                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11792                    if crease.range().end.row >= buffer_start_row {
11793                        to_fold.push(crease);
11794                    } else {
11795                        break;
11796                    }
11797                }
11798            }
11799        }
11800
11801        self.fold_creases(to_fold, true, window, cx);
11802    }
11803
11804    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11805        let buffer_row = fold_at.buffer_row;
11806        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11807
11808        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11809            let autoscroll = self
11810                .selections
11811                .all::<Point>(cx)
11812                .iter()
11813                .any(|selection| crease.range().overlaps(&selection.range()));
11814
11815            self.fold_creases(vec![crease], autoscroll, window, cx);
11816        }
11817    }
11818
11819    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11820        if self.is_singleton(cx) {
11821            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11822            let buffer = &display_map.buffer_snapshot;
11823            let selections = self.selections.all::<Point>(cx);
11824            let ranges = selections
11825                .iter()
11826                .map(|s| {
11827                    let range = s.display_range(&display_map).sorted();
11828                    let mut start = range.start.to_point(&display_map);
11829                    let mut end = range.end.to_point(&display_map);
11830                    start.column = 0;
11831                    end.column = buffer.line_len(MultiBufferRow(end.row));
11832                    start..end
11833                })
11834                .collect::<Vec<_>>();
11835
11836            self.unfold_ranges(&ranges, true, true, cx);
11837        } else {
11838            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11839            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11840                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11841                .map(|(snapshot, _, _)| snapshot.remote_id())
11842                .collect();
11843            for buffer_id in buffer_ids {
11844                self.unfold_buffer(buffer_id, cx);
11845            }
11846        }
11847    }
11848
11849    pub fn unfold_recursive(
11850        &mut self,
11851        _: &UnfoldRecursive,
11852        _window: &mut Window,
11853        cx: &mut Context<Self>,
11854    ) {
11855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11856        let selections = self.selections.all::<Point>(cx);
11857        let ranges = selections
11858            .iter()
11859            .map(|s| {
11860                let mut range = s.display_range(&display_map).sorted();
11861                *range.start.column_mut() = 0;
11862                *range.end.column_mut() = display_map.line_len(range.end.row());
11863                let start = range.start.to_point(&display_map);
11864                let end = range.end.to_point(&display_map);
11865                start..end
11866            })
11867            .collect::<Vec<_>>();
11868
11869        self.unfold_ranges(&ranges, true, true, cx);
11870    }
11871
11872    pub fn unfold_at(
11873        &mut self,
11874        unfold_at: &UnfoldAt,
11875        _window: &mut Window,
11876        cx: &mut Context<Self>,
11877    ) {
11878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11879
11880        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11881            ..Point::new(
11882                unfold_at.buffer_row.0,
11883                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11884            );
11885
11886        let autoscroll = self
11887            .selections
11888            .all::<Point>(cx)
11889            .iter()
11890            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11891
11892        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11893    }
11894
11895    pub fn unfold_all(
11896        &mut self,
11897        _: &actions::UnfoldAll,
11898        _window: &mut Window,
11899        cx: &mut Context<Self>,
11900    ) {
11901        if self.buffer.read(cx).is_singleton() {
11902            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11903            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11904        } else {
11905            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11906                editor
11907                    .update(&mut cx, |editor, cx| {
11908                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11909                            editor.unfold_buffer(buffer_id, cx);
11910                        }
11911                    })
11912                    .ok();
11913            });
11914        }
11915    }
11916
11917    pub fn fold_selected_ranges(
11918        &mut self,
11919        _: &FoldSelectedRanges,
11920        window: &mut Window,
11921        cx: &mut Context<Self>,
11922    ) {
11923        let selections = self.selections.all::<Point>(cx);
11924        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11925        let line_mode = self.selections.line_mode;
11926        let ranges = selections
11927            .into_iter()
11928            .map(|s| {
11929                if line_mode {
11930                    let start = Point::new(s.start.row, 0);
11931                    let end = Point::new(
11932                        s.end.row,
11933                        display_map
11934                            .buffer_snapshot
11935                            .line_len(MultiBufferRow(s.end.row)),
11936                    );
11937                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11938                } else {
11939                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11940                }
11941            })
11942            .collect::<Vec<_>>();
11943        self.fold_creases(ranges, true, window, cx);
11944    }
11945
11946    pub fn fold_ranges<T: ToOffset + Clone>(
11947        &mut self,
11948        ranges: Vec<Range<T>>,
11949        auto_scroll: bool,
11950        window: &mut Window,
11951        cx: &mut Context<Self>,
11952    ) {
11953        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11954        let ranges = ranges
11955            .into_iter()
11956            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11957            .collect::<Vec<_>>();
11958        self.fold_creases(ranges, auto_scroll, window, cx);
11959    }
11960
11961    pub fn fold_creases<T: ToOffset + Clone>(
11962        &mut self,
11963        creases: Vec<Crease<T>>,
11964        auto_scroll: bool,
11965        window: &mut Window,
11966        cx: &mut Context<Self>,
11967    ) {
11968        if creases.is_empty() {
11969            return;
11970        }
11971
11972        let mut buffers_affected = HashSet::default();
11973        let multi_buffer = self.buffer().read(cx);
11974        for crease in &creases {
11975            if let Some((_, buffer, _)) =
11976                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11977            {
11978                buffers_affected.insert(buffer.read(cx).remote_id());
11979            };
11980        }
11981
11982        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11983
11984        if auto_scroll {
11985            self.request_autoscroll(Autoscroll::fit(), cx);
11986        }
11987
11988        cx.notify();
11989
11990        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11991            // Clear diagnostics block when folding a range that contains it.
11992            let snapshot = self.snapshot(window, cx);
11993            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11994                drop(snapshot);
11995                self.active_diagnostics = Some(active_diagnostics);
11996                self.dismiss_diagnostics(cx);
11997            } else {
11998                self.active_diagnostics = Some(active_diagnostics);
11999            }
12000        }
12001
12002        self.scrollbar_marker_state.dirty = true;
12003    }
12004
12005    /// Removes any folds whose ranges intersect any of the given ranges.
12006    pub fn unfold_ranges<T: ToOffset + Clone>(
12007        &mut self,
12008        ranges: &[Range<T>],
12009        inclusive: bool,
12010        auto_scroll: bool,
12011        cx: &mut Context<Self>,
12012    ) {
12013        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12014            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12015        });
12016    }
12017
12018    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12019        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12020            return;
12021        }
12022        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12023        self.display_map
12024            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12025        cx.emit(EditorEvent::BufferFoldToggled {
12026            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12027            folded: true,
12028        });
12029        cx.notify();
12030    }
12031
12032    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12033        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12034            return;
12035        }
12036        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12037        self.display_map.update(cx, |display_map, cx| {
12038            display_map.unfold_buffer(buffer_id, cx);
12039        });
12040        cx.emit(EditorEvent::BufferFoldToggled {
12041            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12042            folded: false,
12043        });
12044        cx.notify();
12045    }
12046
12047    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12048        self.display_map.read(cx).is_buffer_folded(buffer)
12049    }
12050
12051    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12052        self.display_map.read(cx).folded_buffers()
12053    }
12054
12055    /// Removes any folds with the given ranges.
12056    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12057        &mut self,
12058        ranges: &[Range<T>],
12059        type_id: TypeId,
12060        auto_scroll: bool,
12061        cx: &mut Context<Self>,
12062    ) {
12063        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12064            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12065        });
12066    }
12067
12068    fn remove_folds_with<T: ToOffset + Clone>(
12069        &mut self,
12070        ranges: &[Range<T>],
12071        auto_scroll: bool,
12072        cx: &mut Context<Self>,
12073        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12074    ) {
12075        if ranges.is_empty() {
12076            return;
12077        }
12078
12079        let mut buffers_affected = HashSet::default();
12080        let multi_buffer = self.buffer().read(cx);
12081        for range in ranges {
12082            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12083                buffers_affected.insert(buffer.read(cx).remote_id());
12084            };
12085        }
12086
12087        self.display_map.update(cx, update);
12088
12089        if auto_scroll {
12090            self.request_autoscroll(Autoscroll::fit(), cx);
12091        }
12092
12093        cx.notify();
12094        self.scrollbar_marker_state.dirty = true;
12095        self.active_indent_guides_state.dirty = true;
12096    }
12097
12098    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12099        self.display_map.read(cx).fold_placeholder.clone()
12100    }
12101
12102    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12103        self.buffer.update(cx, |buffer, cx| {
12104            buffer.set_all_diff_hunks_expanded(cx);
12105        });
12106    }
12107
12108    pub fn expand_all_diff_hunks(
12109        &mut self,
12110        _: &ExpandAllHunkDiffs,
12111        _window: &mut Window,
12112        cx: &mut Context<Self>,
12113    ) {
12114        self.buffer.update(cx, |buffer, cx| {
12115            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12116        });
12117    }
12118
12119    pub fn toggle_selected_diff_hunks(
12120        &mut self,
12121        _: &ToggleSelectedDiffHunks,
12122        _window: &mut Window,
12123        cx: &mut Context<Self>,
12124    ) {
12125        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12126        self.toggle_diff_hunks_in_ranges(ranges, cx);
12127    }
12128
12129    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12130        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12131        self.buffer
12132            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12133    }
12134
12135    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12136        self.buffer.update(cx, |buffer, cx| {
12137            let ranges = vec![Anchor::min()..Anchor::max()];
12138            if !buffer.all_diff_hunks_expanded()
12139                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12140            {
12141                buffer.collapse_diff_hunks(ranges, cx);
12142                true
12143            } else {
12144                false
12145            }
12146        })
12147    }
12148
12149    fn toggle_diff_hunks_in_ranges(
12150        &mut self,
12151        ranges: Vec<Range<Anchor>>,
12152        cx: &mut Context<'_, Editor>,
12153    ) {
12154        self.buffer.update(cx, |buffer, cx| {
12155            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12156                buffer.collapse_diff_hunks(ranges, cx)
12157            } else {
12158                buffer.expand_diff_hunks(ranges, cx)
12159            }
12160        })
12161    }
12162
12163    pub(crate) fn apply_all_diff_hunks(
12164        &mut self,
12165        _: &ApplyAllDiffHunks,
12166        window: &mut Window,
12167        cx: &mut Context<Self>,
12168    ) {
12169        let buffers = self.buffer.read(cx).all_buffers();
12170        for branch_buffer in buffers {
12171            branch_buffer.update(cx, |branch_buffer, cx| {
12172                branch_buffer.merge_into_base(Vec::new(), cx);
12173            });
12174        }
12175
12176        if let Some(project) = self.project.clone() {
12177            self.save(true, project, window, cx).detach_and_log_err(cx);
12178        }
12179    }
12180
12181    pub(crate) fn apply_selected_diff_hunks(
12182        &mut self,
12183        _: &ApplyDiffHunk,
12184        window: &mut Window,
12185        cx: &mut Context<Self>,
12186    ) {
12187        let snapshot = self.snapshot(window, cx);
12188        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12189        let mut ranges_by_buffer = HashMap::default();
12190        self.transact(window, cx, |editor, _window, cx| {
12191            for hunk in hunks {
12192                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12193                    ranges_by_buffer
12194                        .entry(buffer.clone())
12195                        .or_insert_with(Vec::new)
12196                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12197                }
12198            }
12199
12200            for (buffer, ranges) in ranges_by_buffer {
12201                buffer.update(cx, |buffer, cx| {
12202                    buffer.merge_into_base(ranges, cx);
12203                });
12204            }
12205        });
12206
12207        if let Some(project) = self.project.clone() {
12208            self.save(true, project, window, cx).detach_and_log_err(cx);
12209        }
12210    }
12211
12212    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12213        if hovered != self.gutter_hovered {
12214            self.gutter_hovered = hovered;
12215            cx.notify();
12216        }
12217    }
12218
12219    pub fn insert_blocks(
12220        &mut self,
12221        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12222        autoscroll: Option<Autoscroll>,
12223        cx: &mut Context<Self>,
12224    ) -> Vec<CustomBlockId> {
12225        let blocks = self
12226            .display_map
12227            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12228        if let Some(autoscroll) = autoscroll {
12229            self.request_autoscroll(autoscroll, cx);
12230        }
12231        cx.notify();
12232        blocks
12233    }
12234
12235    pub fn resize_blocks(
12236        &mut self,
12237        heights: HashMap<CustomBlockId, u32>,
12238        autoscroll: Option<Autoscroll>,
12239        cx: &mut Context<Self>,
12240    ) {
12241        self.display_map
12242            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12243        if let Some(autoscroll) = autoscroll {
12244            self.request_autoscroll(autoscroll, cx);
12245        }
12246        cx.notify();
12247    }
12248
12249    pub fn replace_blocks(
12250        &mut self,
12251        renderers: HashMap<CustomBlockId, RenderBlock>,
12252        autoscroll: Option<Autoscroll>,
12253        cx: &mut Context<Self>,
12254    ) {
12255        self.display_map
12256            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12257        if let Some(autoscroll) = autoscroll {
12258            self.request_autoscroll(autoscroll, cx);
12259        }
12260        cx.notify();
12261    }
12262
12263    pub fn remove_blocks(
12264        &mut self,
12265        block_ids: HashSet<CustomBlockId>,
12266        autoscroll: Option<Autoscroll>,
12267        cx: &mut Context<Self>,
12268    ) {
12269        self.display_map.update(cx, |display_map, cx| {
12270            display_map.remove_blocks(block_ids, cx)
12271        });
12272        if let Some(autoscroll) = autoscroll {
12273            self.request_autoscroll(autoscroll, cx);
12274        }
12275        cx.notify();
12276    }
12277
12278    pub fn row_for_block(
12279        &self,
12280        block_id: CustomBlockId,
12281        cx: &mut Context<Self>,
12282    ) -> Option<DisplayRow> {
12283        self.display_map
12284            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12285    }
12286
12287    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12288        self.focused_block = Some(focused_block);
12289    }
12290
12291    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12292        self.focused_block.take()
12293    }
12294
12295    pub fn insert_creases(
12296        &mut self,
12297        creases: impl IntoIterator<Item = Crease<Anchor>>,
12298        cx: &mut Context<Self>,
12299    ) -> Vec<CreaseId> {
12300        self.display_map
12301            .update(cx, |map, cx| map.insert_creases(creases, cx))
12302    }
12303
12304    pub fn remove_creases(
12305        &mut self,
12306        ids: impl IntoIterator<Item = CreaseId>,
12307        cx: &mut Context<Self>,
12308    ) {
12309        self.display_map
12310            .update(cx, |map, cx| map.remove_creases(ids, cx));
12311    }
12312
12313    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12314        self.display_map
12315            .update(cx, |map, cx| map.snapshot(cx))
12316            .longest_row()
12317    }
12318
12319    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12320        self.display_map
12321            .update(cx, |map, cx| map.snapshot(cx))
12322            .max_point()
12323    }
12324
12325    pub fn text(&self, cx: &App) -> String {
12326        self.buffer.read(cx).read(cx).text()
12327    }
12328
12329    pub fn is_empty(&self, cx: &App) -> bool {
12330        self.buffer.read(cx).read(cx).is_empty()
12331    }
12332
12333    pub fn text_option(&self, cx: &App) -> Option<String> {
12334        let text = self.text(cx);
12335        let text = text.trim();
12336
12337        if text.is_empty() {
12338            return None;
12339        }
12340
12341        Some(text.to_string())
12342    }
12343
12344    pub fn set_text(
12345        &mut self,
12346        text: impl Into<Arc<str>>,
12347        window: &mut Window,
12348        cx: &mut Context<Self>,
12349    ) {
12350        self.transact(window, cx, |this, _, cx| {
12351            this.buffer
12352                .read(cx)
12353                .as_singleton()
12354                .expect("you can only call set_text on editors for singleton buffers")
12355                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12356        });
12357    }
12358
12359    pub fn display_text(&self, cx: &mut App) -> String {
12360        self.display_map
12361            .update(cx, |map, cx| map.snapshot(cx))
12362            .text()
12363    }
12364
12365    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12366        let mut wrap_guides = smallvec::smallvec![];
12367
12368        if self.show_wrap_guides == Some(false) {
12369            return wrap_guides;
12370        }
12371
12372        let settings = self.buffer.read(cx).settings_at(0, cx);
12373        if settings.show_wrap_guides {
12374            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12375                wrap_guides.push((soft_wrap as usize, true));
12376            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12377                wrap_guides.push((soft_wrap as usize, true));
12378            }
12379            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12380        }
12381
12382        wrap_guides
12383    }
12384
12385    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12386        let settings = self.buffer.read(cx).settings_at(0, cx);
12387        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12388        match mode {
12389            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12390                SoftWrap::None
12391            }
12392            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12393            language_settings::SoftWrap::PreferredLineLength => {
12394                SoftWrap::Column(settings.preferred_line_length)
12395            }
12396            language_settings::SoftWrap::Bounded => {
12397                SoftWrap::Bounded(settings.preferred_line_length)
12398            }
12399        }
12400    }
12401
12402    pub fn set_soft_wrap_mode(
12403        &mut self,
12404        mode: language_settings::SoftWrap,
12405
12406        cx: &mut Context<Self>,
12407    ) {
12408        self.soft_wrap_mode_override = Some(mode);
12409        cx.notify();
12410    }
12411
12412    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12413        self.text_style_refinement = Some(style);
12414    }
12415
12416    /// called by the Element so we know what style we were most recently rendered with.
12417    pub(crate) fn set_style(
12418        &mut self,
12419        style: EditorStyle,
12420        window: &mut Window,
12421        cx: &mut Context<Self>,
12422    ) {
12423        let rem_size = window.rem_size();
12424        self.display_map.update(cx, |map, cx| {
12425            map.set_font(
12426                style.text.font(),
12427                style.text.font_size.to_pixels(rem_size),
12428                cx,
12429            )
12430        });
12431        self.style = Some(style);
12432    }
12433
12434    pub fn style(&self) -> Option<&EditorStyle> {
12435        self.style.as_ref()
12436    }
12437
12438    // Called by the element. This method is not designed to be called outside of the editor
12439    // element's layout code because it does not notify when rewrapping is computed synchronously.
12440    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12441        self.display_map
12442            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12443    }
12444
12445    pub fn set_soft_wrap(&mut self) {
12446        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12447    }
12448
12449    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12450        if self.soft_wrap_mode_override.is_some() {
12451            self.soft_wrap_mode_override.take();
12452        } else {
12453            let soft_wrap = match self.soft_wrap_mode(cx) {
12454                SoftWrap::GitDiff => return,
12455                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12456                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12457                    language_settings::SoftWrap::None
12458                }
12459            };
12460            self.soft_wrap_mode_override = Some(soft_wrap);
12461        }
12462        cx.notify();
12463    }
12464
12465    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12466        let Some(workspace) = self.workspace() else {
12467            return;
12468        };
12469        let fs = workspace.read(cx).app_state().fs.clone();
12470        let current_show = TabBarSettings::get_global(cx).show;
12471        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12472            setting.show = Some(!current_show);
12473        });
12474    }
12475
12476    pub fn toggle_indent_guides(
12477        &mut self,
12478        _: &ToggleIndentGuides,
12479        _: &mut Window,
12480        cx: &mut Context<Self>,
12481    ) {
12482        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12483            self.buffer
12484                .read(cx)
12485                .settings_at(0, cx)
12486                .indent_guides
12487                .enabled
12488        });
12489        self.show_indent_guides = Some(!currently_enabled);
12490        cx.notify();
12491    }
12492
12493    fn should_show_indent_guides(&self) -> Option<bool> {
12494        self.show_indent_guides
12495    }
12496
12497    pub fn toggle_line_numbers(
12498        &mut self,
12499        _: &ToggleLineNumbers,
12500        _: &mut Window,
12501        cx: &mut Context<Self>,
12502    ) {
12503        let mut editor_settings = EditorSettings::get_global(cx).clone();
12504        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12505        EditorSettings::override_global(editor_settings, cx);
12506    }
12507
12508    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12509        self.use_relative_line_numbers
12510            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12511    }
12512
12513    pub fn toggle_relative_line_numbers(
12514        &mut self,
12515        _: &ToggleRelativeLineNumbers,
12516        _: &mut Window,
12517        cx: &mut Context<Self>,
12518    ) {
12519        let is_relative = self.should_use_relative_line_numbers(cx);
12520        self.set_relative_line_number(Some(!is_relative), cx)
12521    }
12522
12523    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12524        self.use_relative_line_numbers = is_relative;
12525        cx.notify();
12526    }
12527
12528    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12529        self.show_gutter = show_gutter;
12530        cx.notify();
12531    }
12532
12533    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12534        self.show_scrollbars = show_scrollbars;
12535        cx.notify();
12536    }
12537
12538    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12539        self.show_line_numbers = Some(show_line_numbers);
12540        cx.notify();
12541    }
12542
12543    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12544        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12545        cx.notify();
12546    }
12547
12548    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12549        self.show_code_actions = Some(show_code_actions);
12550        cx.notify();
12551    }
12552
12553    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12554        self.show_runnables = Some(show_runnables);
12555        cx.notify();
12556    }
12557
12558    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12559        if self.display_map.read(cx).masked != masked {
12560            self.display_map.update(cx, |map, _| map.masked = masked);
12561        }
12562        cx.notify()
12563    }
12564
12565    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12566        self.show_wrap_guides = Some(show_wrap_guides);
12567        cx.notify();
12568    }
12569
12570    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12571        self.show_indent_guides = Some(show_indent_guides);
12572        cx.notify();
12573    }
12574
12575    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12576        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12577            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12578                if let Some(dir) = file.abs_path(cx).parent() {
12579                    return Some(dir.to_owned());
12580                }
12581            }
12582
12583            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12584                return Some(project_path.path.to_path_buf());
12585            }
12586        }
12587
12588        None
12589    }
12590
12591    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12592        self.active_excerpt(cx)?
12593            .1
12594            .read(cx)
12595            .file()
12596            .and_then(|f| f.as_local())
12597    }
12598
12599    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12600        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12601            let project_path = buffer.read(cx).project_path(cx)?;
12602            let project = self.project.as_ref()?.read(cx);
12603            project.absolute_path(&project_path, cx)
12604        })
12605    }
12606
12607    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12608        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12609            let project_path = buffer.read(cx).project_path(cx)?;
12610            let project = self.project.as_ref()?.read(cx);
12611            let entry = project.entry_for_path(&project_path, cx)?;
12612            let path = entry.path.to_path_buf();
12613            Some(path)
12614        })
12615    }
12616
12617    pub fn reveal_in_finder(
12618        &mut self,
12619        _: &RevealInFileManager,
12620        _window: &mut Window,
12621        cx: &mut Context<Self>,
12622    ) {
12623        if let Some(target) = self.target_file(cx) {
12624            cx.reveal_path(&target.abs_path(cx));
12625        }
12626    }
12627
12628    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12629        if let Some(path) = self.target_file_abs_path(cx) {
12630            if let Some(path) = path.to_str() {
12631                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12632            }
12633        }
12634    }
12635
12636    pub fn copy_relative_path(
12637        &mut self,
12638        _: &CopyRelativePath,
12639        _window: &mut Window,
12640        cx: &mut Context<Self>,
12641    ) {
12642        if let Some(path) = self.target_file_path(cx) {
12643            if let Some(path) = path.to_str() {
12644                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12645            }
12646        }
12647    }
12648
12649    pub fn toggle_git_blame(
12650        &mut self,
12651        _: &ToggleGitBlame,
12652        window: &mut Window,
12653        cx: &mut Context<Self>,
12654    ) {
12655        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12656
12657        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12658            self.start_git_blame(true, window, cx);
12659        }
12660
12661        cx.notify();
12662    }
12663
12664    pub fn toggle_git_blame_inline(
12665        &mut self,
12666        _: &ToggleGitBlameInline,
12667        window: &mut Window,
12668        cx: &mut Context<Self>,
12669    ) {
12670        self.toggle_git_blame_inline_internal(true, window, cx);
12671        cx.notify();
12672    }
12673
12674    pub fn git_blame_inline_enabled(&self) -> bool {
12675        self.git_blame_inline_enabled
12676    }
12677
12678    pub fn toggle_selection_menu(
12679        &mut self,
12680        _: &ToggleSelectionMenu,
12681        _: &mut Window,
12682        cx: &mut Context<Self>,
12683    ) {
12684        self.show_selection_menu = self
12685            .show_selection_menu
12686            .map(|show_selections_menu| !show_selections_menu)
12687            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12688
12689        cx.notify();
12690    }
12691
12692    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12693        self.show_selection_menu
12694            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12695    }
12696
12697    fn start_git_blame(
12698        &mut self,
12699        user_triggered: bool,
12700        window: &mut Window,
12701        cx: &mut Context<Self>,
12702    ) {
12703        if let Some(project) = self.project.as_ref() {
12704            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12705                return;
12706            };
12707
12708            if buffer.read(cx).file().is_none() {
12709                return;
12710            }
12711
12712            let focused = self.focus_handle(cx).contains_focused(window, cx);
12713
12714            let project = project.clone();
12715            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12716            self.blame_subscription =
12717                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12718            self.blame = Some(blame);
12719        }
12720    }
12721
12722    fn toggle_git_blame_inline_internal(
12723        &mut self,
12724        user_triggered: bool,
12725        window: &mut Window,
12726        cx: &mut Context<Self>,
12727    ) {
12728        if self.git_blame_inline_enabled {
12729            self.git_blame_inline_enabled = false;
12730            self.show_git_blame_inline = false;
12731            self.show_git_blame_inline_delay_task.take();
12732        } else {
12733            self.git_blame_inline_enabled = true;
12734            self.start_git_blame_inline(user_triggered, window, cx);
12735        }
12736
12737        cx.notify();
12738    }
12739
12740    fn start_git_blame_inline(
12741        &mut self,
12742        user_triggered: bool,
12743        window: &mut Window,
12744        cx: &mut Context<Self>,
12745    ) {
12746        self.start_git_blame(user_triggered, window, cx);
12747
12748        if ProjectSettings::get_global(cx)
12749            .git
12750            .inline_blame_delay()
12751            .is_some()
12752        {
12753            self.start_inline_blame_timer(window, cx);
12754        } else {
12755            self.show_git_blame_inline = true
12756        }
12757    }
12758
12759    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12760        self.blame.as_ref()
12761    }
12762
12763    pub fn show_git_blame_gutter(&self) -> bool {
12764        self.show_git_blame_gutter
12765    }
12766
12767    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12768        self.show_git_blame_gutter && self.has_blame_entries(cx)
12769    }
12770
12771    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12772        self.show_git_blame_inline
12773            && self.focus_handle.is_focused(window)
12774            && !self.newest_selection_head_on_empty_line(cx)
12775            && self.has_blame_entries(cx)
12776    }
12777
12778    fn has_blame_entries(&self, cx: &App) -> bool {
12779        self.blame()
12780            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12781    }
12782
12783    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12784        let cursor_anchor = self.selections.newest_anchor().head();
12785
12786        let snapshot = self.buffer.read(cx).snapshot(cx);
12787        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12788
12789        snapshot.line_len(buffer_row) == 0
12790    }
12791
12792    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12793        let buffer_and_selection = maybe!({
12794            let selection = self.selections.newest::<Point>(cx);
12795            let selection_range = selection.range();
12796
12797            let multi_buffer = self.buffer().read(cx);
12798            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12799            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12800
12801            let (buffer, range, _) = if selection.reversed {
12802                buffer_ranges.first()
12803            } else {
12804                buffer_ranges.last()
12805            }?;
12806
12807            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12808                ..text::ToPoint::to_point(&range.end, &buffer).row;
12809            Some((
12810                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12811                selection,
12812            ))
12813        });
12814
12815        let Some((buffer, selection)) = buffer_and_selection else {
12816            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12817        };
12818
12819        let Some(project) = self.project.as_ref() else {
12820            return Task::ready(Err(anyhow!("editor does not have project")));
12821        };
12822
12823        project.update(cx, |project, cx| {
12824            project.get_permalink_to_line(&buffer, selection, cx)
12825        })
12826    }
12827
12828    pub fn copy_permalink_to_line(
12829        &mut self,
12830        _: &CopyPermalinkToLine,
12831        window: &mut Window,
12832        cx: &mut Context<Self>,
12833    ) {
12834        let permalink_task = self.get_permalink_to_line(cx);
12835        let workspace = self.workspace();
12836
12837        cx.spawn_in(window, |_, mut cx| async move {
12838            match permalink_task.await {
12839                Ok(permalink) => {
12840                    cx.update(|_, cx| {
12841                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12842                    })
12843                    .ok();
12844                }
12845                Err(err) => {
12846                    let message = format!("Failed to copy permalink: {err}");
12847
12848                    Err::<(), anyhow::Error>(err).log_err();
12849
12850                    if let Some(workspace) = workspace {
12851                        workspace
12852                            .update_in(&mut cx, |workspace, _, cx| {
12853                                struct CopyPermalinkToLine;
12854
12855                                workspace.show_toast(
12856                                    Toast::new(
12857                                        NotificationId::unique::<CopyPermalinkToLine>(),
12858                                        message,
12859                                    ),
12860                                    cx,
12861                                )
12862                            })
12863                            .ok();
12864                    }
12865                }
12866            }
12867        })
12868        .detach();
12869    }
12870
12871    pub fn copy_file_location(
12872        &mut self,
12873        _: &CopyFileLocation,
12874        _: &mut Window,
12875        cx: &mut Context<Self>,
12876    ) {
12877        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12878        if let Some(file) = self.target_file(cx) {
12879            if let Some(path) = file.path().to_str() {
12880                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12881            }
12882        }
12883    }
12884
12885    pub fn open_permalink_to_line(
12886        &mut self,
12887        _: &OpenPermalinkToLine,
12888        window: &mut Window,
12889        cx: &mut Context<Self>,
12890    ) {
12891        let permalink_task = self.get_permalink_to_line(cx);
12892        let workspace = self.workspace();
12893
12894        cx.spawn_in(window, |_, mut cx| async move {
12895            match permalink_task.await {
12896                Ok(permalink) => {
12897                    cx.update(|_, cx| {
12898                        cx.open_url(permalink.as_ref());
12899                    })
12900                    .ok();
12901                }
12902                Err(err) => {
12903                    let message = format!("Failed to open permalink: {err}");
12904
12905                    Err::<(), anyhow::Error>(err).log_err();
12906
12907                    if let Some(workspace) = workspace {
12908                        workspace
12909                            .update(&mut cx, |workspace, cx| {
12910                                struct OpenPermalinkToLine;
12911
12912                                workspace.show_toast(
12913                                    Toast::new(
12914                                        NotificationId::unique::<OpenPermalinkToLine>(),
12915                                        message,
12916                                    ),
12917                                    cx,
12918                                )
12919                            })
12920                            .ok();
12921                    }
12922                }
12923            }
12924        })
12925        .detach();
12926    }
12927
12928    pub fn insert_uuid_v4(
12929        &mut self,
12930        _: &InsertUuidV4,
12931        window: &mut Window,
12932        cx: &mut Context<Self>,
12933    ) {
12934        self.insert_uuid(UuidVersion::V4, window, cx);
12935    }
12936
12937    pub fn insert_uuid_v7(
12938        &mut self,
12939        _: &InsertUuidV7,
12940        window: &mut Window,
12941        cx: &mut Context<Self>,
12942    ) {
12943        self.insert_uuid(UuidVersion::V7, window, cx);
12944    }
12945
12946    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12947        self.transact(window, cx, |this, window, cx| {
12948            let edits = this
12949                .selections
12950                .all::<Point>(cx)
12951                .into_iter()
12952                .map(|selection| {
12953                    let uuid = match version {
12954                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12955                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12956                    };
12957
12958                    (selection.range(), uuid.to_string())
12959                });
12960            this.edit(edits, cx);
12961            this.refresh_inline_completion(true, false, window, cx);
12962        });
12963    }
12964
12965    pub fn open_selections_in_multibuffer(
12966        &mut self,
12967        _: &OpenSelectionsInMultibuffer,
12968        window: &mut Window,
12969        cx: &mut Context<Self>,
12970    ) {
12971        let multibuffer = self.buffer.read(cx);
12972
12973        let Some(buffer) = multibuffer.as_singleton() else {
12974            return;
12975        };
12976
12977        let Some(workspace) = self.workspace() else {
12978            return;
12979        };
12980
12981        let locations = self
12982            .selections
12983            .disjoint_anchors()
12984            .iter()
12985            .map(|range| Location {
12986                buffer: buffer.clone(),
12987                range: range.start.text_anchor..range.end.text_anchor,
12988            })
12989            .collect::<Vec<_>>();
12990
12991        let title = multibuffer.title(cx).to_string();
12992
12993        cx.spawn_in(window, |_, mut cx| async move {
12994            workspace.update_in(&mut cx, |workspace, window, cx| {
12995                Self::open_locations_in_multibuffer(
12996                    workspace,
12997                    locations,
12998                    format!("Selections for '{title}'"),
12999                    false,
13000                    MultibufferSelectionMode::All,
13001                    window,
13002                    cx,
13003                );
13004            })
13005        })
13006        .detach();
13007    }
13008
13009    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13010    /// last highlight added will be used.
13011    ///
13012    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13013    pub fn highlight_rows<T: 'static>(
13014        &mut self,
13015        range: Range<Anchor>,
13016        color: Hsla,
13017        should_autoscroll: bool,
13018        cx: &mut Context<Self>,
13019    ) {
13020        let snapshot = self.buffer().read(cx).snapshot(cx);
13021        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13022        let ix = row_highlights.binary_search_by(|highlight| {
13023            Ordering::Equal
13024                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13025                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13026        });
13027
13028        if let Err(mut ix) = ix {
13029            let index = post_inc(&mut self.highlight_order);
13030
13031            // If this range intersects with the preceding highlight, then merge it with
13032            // the preceding highlight. Otherwise insert a new highlight.
13033            let mut merged = false;
13034            if ix > 0 {
13035                let prev_highlight = &mut row_highlights[ix - 1];
13036                if prev_highlight
13037                    .range
13038                    .end
13039                    .cmp(&range.start, &snapshot)
13040                    .is_ge()
13041                {
13042                    ix -= 1;
13043                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13044                        prev_highlight.range.end = range.end;
13045                    }
13046                    merged = true;
13047                    prev_highlight.index = index;
13048                    prev_highlight.color = color;
13049                    prev_highlight.should_autoscroll = should_autoscroll;
13050                }
13051            }
13052
13053            if !merged {
13054                row_highlights.insert(
13055                    ix,
13056                    RowHighlight {
13057                        range: range.clone(),
13058                        index,
13059                        color,
13060                        should_autoscroll,
13061                    },
13062                );
13063            }
13064
13065            // If any of the following highlights intersect with this one, merge them.
13066            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13067                let highlight = &row_highlights[ix];
13068                if next_highlight
13069                    .range
13070                    .start
13071                    .cmp(&highlight.range.end, &snapshot)
13072                    .is_le()
13073                {
13074                    if next_highlight
13075                        .range
13076                        .end
13077                        .cmp(&highlight.range.end, &snapshot)
13078                        .is_gt()
13079                    {
13080                        row_highlights[ix].range.end = next_highlight.range.end;
13081                    }
13082                    row_highlights.remove(ix + 1);
13083                } else {
13084                    break;
13085                }
13086            }
13087        }
13088    }
13089
13090    /// Remove any highlighted row ranges of the given type that intersect the
13091    /// given ranges.
13092    pub fn remove_highlighted_rows<T: 'static>(
13093        &mut self,
13094        ranges_to_remove: Vec<Range<Anchor>>,
13095        cx: &mut Context<Self>,
13096    ) {
13097        let snapshot = self.buffer().read(cx).snapshot(cx);
13098        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13099        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13100        row_highlights.retain(|highlight| {
13101            while let Some(range_to_remove) = ranges_to_remove.peek() {
13102                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13103                    Ordering::Less | Ordering::Equal => {
13104                        ranges_to_remove.next();
13105                    }
13106                    Ordering::Greater => {
13107                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13108                            Ordering::Less | Ordering::Equal => {
13109                                return false;
13110                            }
13111                            Ordering::Greater => break,
13112                        }
13113                    }
13114                }
13115            }
13116
13117            true
13118        })
13119    }
13120
13121    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13122    pub fn clear_row_highlights<T: 'static>(&mut self) {
13123        self.highlighted_rows.remove(&TypeId::of::<T>());
13124    }
13125
13126    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13127    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13128        self.highlighted_rows
13129            .get(&TypeId::of::<T>())
13130            .map_or(&[] as &[_], |vec| vec.as_slice())
13131            .iter()
13132            .map(|highlight| (highlight.range.clone(), highlight.color))
13133    }
13134
13135    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13136    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13137    /// Allows to ignore certain kinds of highlights.
13138    pub fn highlighted_display_rows(
13139        &self,
13140        window: &mut Window,
13141        cx: &mut App,
13142    ) -> BTreeMap<DisplayRow, Hsla> {
13143        let snapshot = self.snapshot(window, cx);
13144        let mut used_highlight_orders = HashMap::default();
13145        self.highlighted_rows
13146            .iter()
13147            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13148            .fold(
13149                BTreeMap::<DisplayRow, Hsla>::new(),
13150                |mut unique_rows, highlight| {
13151                    let start = highlight.range.start.to_display_point(&snapshot);
13152                    let end = highlight.range.end.to_display_point(&snapshot);
13153                    let start_row = start.row().0;
13154                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13155                        && end.column() == 0
13156                    {
13157                        end.row().0.saturating_sub(1)
13158                    } else {
13159                        end.row().0
13160                    };
13161                    for row in start_row..=end_row {
13162                        let used_index =
13163                            used_highlight_orders.entry(row).or_insert(highlight.index);
13164                        if highlight.index >= *used_index {
13165                            *used_index = highlight.index;
13166                            unique_rows.insert(DisplayRow(row), highlight.color);
13167                        }
13168                    }
13169                    unique_rows
13170                },
13171            )
13172    }
13173
13174    pub fn highlighted_display_row_for_autoscroll(
13175        &self,
13176        snapshot: &DisplaySnapshot,
13177    ) -> Option<DisplayRow> {
13178        self.highlighted_rows
13179            .values()
13180            .flat_map(|highlighted_rows| highlighted_rows.iter())
13181            .filter_map(|highlight| {
13182                if highlight.should_autoscroll {
13183                    Some(highlight.range.start.to_display_point(snapshot).row())
13184                } else {
13185                    None
13186                }
13187            })
13188            .min()
13189    }
13190
13191    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13192        self.highlight_background::<SearchWithinRange>(
13193            ranges,
13194            |colors| colors.editor_document_highlight_read_background,
13195            cx,
13196        )
13197    }
13198
13199    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13200        self.breadcrumb_header = Some(new_header);
13201    }
13202
13203    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13204        self.clear_background_highlights::<SearchWithinRange>(cx);
13205    }
13206
13207    pub fn highlight_background<T: 'static>(
13208        &mut self,
13209        ranges: &[Range<Anchor>],
13210        color_fetcher: fn(&ThemeColors) -> Hsla,
13211        cx: &mut Context<Self>,
13212    ) {
13213        self.background_highlights
13214            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13215        self.scrollbar_marker_state.dirty = true;
13216        cx.notify();
13217    }
13218
13219    pub fn clear_background_highlights<T: 'static>(
13220        &mut self,
13221        cx: &mut Context<Self>,
13222    ) -> Option<BackgroundHighlight> {
13223        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13224        if !text_highlights.1.is_empty() {
13225            self.scrollbar_marker_state.dirty = true;
13226            cx.notify();
13227        }
13228        Some(text_highlights)
13229    }
13230
13231    pub fn highlight_gutter<T: 'static>(
13232        &mut self,
13233        ranges: &[Range<Anchor>],
13234        color_fetcher: fn(&App) -> Hsla,
13235        cx: &mut Context<Self>,
13236    ) {
13237        self.gutter_highlights
13238            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13239        cx.notify();
13240    }
13241
13242    pub fn clear_gutter_highlights<T: 'static>(
13243        &mut self,
13244        cx: &mut Context<Self>,
13245    ) -> Option<GutterHighlight> {
13246        cx.notify();
13247        self.gutter_highlights.remove(&TypeId::of::<T>())
13248    }
13249
13250    #[cfg(feature = "test-support")]
13251    pub fn all_text_background_highlights(
13252        &self,
13253        window: &mut Window,
13254        cx: &mut Context<Self>,
13255    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13256        let snapshot = self.snapshot(window, cx);
13257        let buffer = &snapshot.buffer_snapshot;
13258        let start = buffer.anchor_before(0);
13259        let end = buffer.anchor_after(buffer.len());
13260        let theme = cx.theme().colors();
13261        self.background_highlights_in_range(start..end, &snapshot, theme)
13262    }
13263
13264    #[cfg(feature = "test-support")]
13265    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13266        let snapshot = self.buffer().read(cx).snapshot(cx);
13267
13268        let highlights = self
13269            .background_highlights
13270            .get(&TypeId::of::<items::BufferSearchHighlights>());
13271
13272        if let Some((_color, ranges)) = highlights {
13273            ranges
13274                .iter()
13275                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13276                .collect_vec()
13277        } else {
13278            vec![]
13279        }
13280    }
13281
13282    fn document_highlights_for_position<'a>(
13283        &'a self,
13284        position: Anchor,
13285        buffer: &'a MultiBufferSnapshot,
13286    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13287        let read_highlights = self
13288            .background_highlights
13289            .get(&TypeId::of::<DocumentHighlightRead>())
13290            .map(|h| &h.1);
13291        let write_highlights = self
13292            .background_highlights
13293            .get(&TypeId::of::<DocumentHighlightWrite>())
13294            .map(|h| &h.1);
13295        let left_position = position.bias_left(buffer);
13296        let right_position = position.bias_right(buffer);
13297        read_highlights
13298            .into_iter()
13299            .chain(write_highlights)
13300            .flat_map(move |ranges| {
13301                let start_ix = match ranges.binary_search_by(|probe| {
13302                    let cmp = probe.end.cmp(&left_position, buffer);
13303                    if cmp.is_ge() {
13304                        Ordering::Greater
13305                    } else {
13306                        Ordering::Less
13307                    }
13308                }) {
13309                    Ok(i) | Err(i) => i,
13310                };
13311
13312                ranges[start_ix..]
13313                    .iter()
13314                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13315            })
13316    }
13317
13318    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13319        self.background_highlights
13320            .get(&TypeId::of::<T>())
13321            .map_or(false, |(_, highlights)| !highlights.is_empty())
13322    }
13323
13324    pub fn background_highlights_in_range(
13325        &self,
13326        search_range: Range<Anchor>,
13327        display_snapshot: &DisplaySnapshot,
13328        theme: &ThemeColors,
13329    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13330        let mut results = Vec::new();
13331        for (color_fetcher, ranges) in self.background_highlights.values() {
13332            let color = color_fetcher(theme);
13333            let start_ix = match ranges.binary_search_by(|probe| {
13334                let cmp = probe
13335                    .end
13336                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13337                if cmp.is_gt() {
13338                    Ordering::Greater
13339                } else {
13340                    Ordering::Less
13341                }
13342            }) {
13343                Ok(i) | Err(i) => i,
13344            };
13345            for range in &ranges[start_ix..] {
13346                if range
13347                    .start
13348                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13349                    .is_ge()
13350                {
13351                    break;
13352                }
13353
13354                let start = range.start.to_display_point(display_snapshot);
13355                let end = range.end.to_display_point(display_snapshot);
13356                results.push((start..end, color))
13357            }
13358        }
13359        results
13360    }
13361
13362    pub fn background_highlight_row_ranges<T: 'static>(
13363        &self,
13364        search_range: Range<Anchor>,
13365        display_snapshot: &DisplaySnapshot,
13366        count: usize,
13367    ) -> Vec<RangeInclusive<DisplayPoint>> {
13368        let mut results = Vec::new();
13369        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13370            return vec![];
13371        };
13372
13373        let start_ix = match ranges.binary_search_by(|probe| {
13374            let cmp = probe
13375                .end
13376                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13377            if cmp.is_gt() {
13378                Ordering::Greater
13379            } else {
13380                Ordering::Less
13381            }
13382        }) {
13383            Ok(i) | Err(i) => i,
13384        };
13385        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13386            if let (Some(start_display), Some(end_display)) = (start, end) {
13387                results.push(
13388                    start_display.to_display_point(display_snapshot)
13389                        ..=end_display.to_display_point(display_snapshot),
13390                );
13391            }
13392        };
13393        let mut start_row: Option<Point> = None;
13394        let mut end_row: Option<Point> = None;
13395        if ranges.len() > count {
13396            return Vec::new();
13397        }
13398        for range in &ranges[start_ix..] {
13399            if range
13400                .start
13401                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13402                .is_ge()
13403            {
13404                break;
13405            }
13406            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13407            if let Some(current_row) = &end_row {
13408                if end.row == current_row.row {
13409                    continue;
13410                }
13411            }
13412            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13413            if start_row.is_none() {
13414                assert_eq!(end_row, None);
13415                start_row = Some(start);
13416                end_row = Some(end);
13417                continue;
13418            }
13419            if let Some(current_end) = end_row.as_mut() {
13420                if start.row > current_end.row + 1 {
13421                    push_region(start_row, end_row);
13422                    start_row = Some(start);
13423                    end_row = Some(end);
13424                } else {
13425                    // Merge two hunks.
13426                    *current_end = end;
13427                }
13428            } else {
13429                unreachable!();
13430            }
13431        }
13432        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13433        push_region(start_row, end_row);
13434        results
13435    }
13436
13437    pub fn gutter_highlights_in_range(
13438        &self,
13439        search_range: Range<Anchor>,
13440        display_snapshot: &DisplaySnapshot,
13441        cx: &App,
13442    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13443        let mut results = Vec::new();
13444        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13445            let color = color_fetcher(cx);
13446            let start_ix = match ranges.binary_search_by(|probe| {
13447                let cmp = probe
13448                    .end
13449                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13450                if cmp.is_gt() {
13451                    Ordering::Greater
13452                } else {
13453                    Ordering::Less
13454                }
13455            }) {
13456                Ok(i) | Err(i) => i,
13457            };
13458            for range in &ranges[start_ix..] {
13459                if range
13460                    .start
13461                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13462                    .is_ge()
13463                {
13464                    break;
13465                }
13466
13467                let start = range.start.to_display_point(display_snapshot);
13468                let end = range.end.to_display_point(display_snapshot);
13469                results.push((start..end, color))
13470            }
13471        }
13472        results
13473    }
13474
13475    /// Get the text ranges corresponding to the redaction query
13476    pub fn redacted_ranges(
13477        &self,
13478        search_range: Range<Anchor>,
13479        display_snapshot: &DisplaySnapshot,
13480        cx: &App,
13481    ) -> Vec<Range<DisplayPoint>> {
13482        display_snapshot
13483            .buffer_snapshot
13484            .redacted_ranges(search_range, |file| {
13485                if let Some(file) = file {
13486                    file.is_private()
13487                        && EditorSettings::get(
13488                            Some(SettingsLocation {
13489                                worktree_id: file.worktree_id(cx),
13490                                path: file.path().as_ref(),
13491                            }),
13492                            cx,
13493                        )
13494                        .redact_private_values
13495                } else {
13496                    false
13497                }
13498            })
13499            .map(|range| {
13500                range.start.to_display_point(display_snapshot)
13501                    ..range.end.to_display_point(display_snapshot)
13502            })
13503            .collect()
13504    }
13505
13506    pub fn highlight_text<T: 'static>(
13507        &mut self,
13508        ranges: Vec<Range<Anchor>>,
13509        style: HighlightStyle,
13510        cx: &mut Context<Self>,
13511    ) {
13512        self.display_map.update(cx, |map, _| {
13513            map.highlight_text(TypeId::of::<T>(), ranges, style)
13514        });
13515        cx.notify();
13516    }
13517
13518    pub(crate) fn highlight_inlays<T: 'static>(
13519        &mut self,
13520        highlights: Vec<InlayHighlight>,
13521        style: HighlightStyle,
13522        cx: &mut Context<Self>,
13523    ) {
13524        self.display_map.update(cx, |map, _| {
13525            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13526        });
13527        cx.notify();
13528    }
13529
13530    pub fn text_highlights<'a, T: 'static>(
13531        &'a self,
13532        cx: &'a App,
13533    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13534        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13535    }
13536
13537    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13538        let cleared = self
13539            .display_map
13540            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13541        if cleared {
13542            cx.notify();
13543        }
13544    }
13545
13546    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13547        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13548            && self.focus_handle.is_focused(window)
13549    }
13550
13551    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13552        self.show_cursor_when_unfocused = is_enabled;
13553        cx.notify();
13554    }
13555
13556    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13557        self.project
13558            .as_ref()
13559            .map(|project| project.read(cx).lsp_store())
13560    }
13561
13562    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13563        cx.notify();
13564    }
13565
13566    fn on_buffer_event(
13567        &mut self,
13568        multibuffer: &Entity<MultiBuffer>,
13569        event: &multi_buffer::Event,
13570        window: &mut Window,
13571        cx: &mut Context<Self>,
13572    ) {
13573        match event {
13574            multi_buffer::Event::Edited {
13575                singleton_buffer_edited,
13576                edited_buffer: buffer_edited,
13577            } => {
13578                self.scrollbar_marker_state.dirty = true;
13579                self.active_indent_guides_state.dirty = true;
13580                self.refresh_active_diagnostics(cx);
13581                self.refresh_code_actions(window, cx);
13582                if self.has_active_inline_completion() {
13583                    self.update_visible_inline_completion(window, cx);
13584                }
13585                if let Some(buffer) = buffer_edited {
13586                    let buffer_id = buffer.read(cx).remote_id();
13587                    if !self.registered_buffers.contains_key(&buffer_id) {
13588                        if let Some(lsp_store) = self.lsp_store(cx) {
13589                            lsp_store.update(cx, |lsp_store, cx| {
13590                                self.registered_buffers.insert(
13591                                    buffer_id,
13592                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13593                                );
13594                            })
13595                        }
13596                    }
13597                }
13598                cx.emit(EditorEvent::BufferEdited);
13599                cx.emit(SearchEvent::MatchesInvalidated);
13600                if *singleton_buffer_edited {
13601                    if let Some(project) = &self.project {
13602                        let project = project.read(cx);
13603                        #[allow(clippy::mutable_key_type)]
13604                        let languages_affected = multibuffer
13605                            .read(cx)
13606                            .all_buffers()
13607                            .into_iter()
13608                            .filter_map(|buffer| {
13609                                let buffer = buffer.read(cx);
13610                                let language = buffer.language()?;
13611                                if project.is_local()
13612                                    && project
13613                                        .language_servers_for_local_buffer(buffer, cx)
13614                                        .count()
13615                                        == 0
13616                                {
13617                                    None
13618                                } else {
13619                                    Some(language)
13620                                }
13621                            })
13622                            .cloned()
13623                            .collect::<HashSet<_>>();
13624                        if !languages_affected.is_empty() {
13625                            self.refresh_inlay_hints(
13626                                InlayHintRefreshReason::BufferEdited(languages_affected),
13627                                cx,
13628                            );
13629                        }
13630                    }
13631                }
13632
13633                let Some(project) = &self.project else { return };
13634                let (telemetry, is_via_ssh) = {
13635                    let project = project.read(cx);
13636                    let telemetry = project.client().telemetry().clone();
13637                    let is_via_ssh = project.is_via_ssh();
13638                    (telemetry, is_via_ssh)
13639                };
13640                refresh_linked_ranges(self, window, cx);
13641                telemetry.log_edit_event("editor", is_via_ssh);
13642            }
13643            multi_buffer::Event::ExcerptsAdded {
13644                buffer,
13645                predecessor,
13646                excerpts,
13647            } => {
13648                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13649                let buffer_id = buffer.read(cx).remote_id();
13650                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13651                    if let Some(project) = &self.project {
13652                        get_unstaged_changes_for_buffers(
13653                            project,
13654                            [buffer.clone()],
13655                            self.buffer.clone(),
13656                            cx,
13657                        );
13658                    }
13659                }
13660                cx.emit(EditorEvent::ExcerptsAdded {
13661                    buffer: buffer.clone(),
13662                    predecessor: *predecessor,
13663                    excerpts: excerpts.clone(),
13664                });
13665                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13666            }
13667            multi_buffer::Event::ExcerptsRemoved { ids } => {
13668                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13669                let buffer = self.buffer.read(cx);
13670                self.registered_buffers
13671                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13672                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13673            }
13674            multi_buffer::Event::ExcerptsEdited { ids } => {
13675                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13676            }
13677            multi_buffer::Event::ExcerptsExpanded { ids } => {
13678                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13679                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13680            }
13681            multi_buffer::Event::Reparsed(buffer_id) => {
13682                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13683
13684                cx.emit(EditorEvent::Reparsed(*buffer_id));
13685            }
13686            multi_buffer::Event::DiffHunksToggled => {
13687                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13688            }
13689            multi_buffer::Event::LanguageChanged(buffer_id) => {
13690                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13691                cx.emit(EditorEvent::Reparsed(*buffer_id));
13692                cx.notify();
13693            }
13694            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13695            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13696            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13697                cx.emit(EditorEvent::TitleChanged)
13698            }
13699            // multi_buffer::Event::DiffBaseChanged => {
13700            //     self.scrollbar_marker_state.dirty = true;
13701            //     cx.emit(EditorEvent::DiffBaseChanged);
13702            //     cx.notify();
13703            // }
13704            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13705            multi_buffer::Event::DiagnosticsUpdated => {
13706                self.refresh_active_diagnostics(cx);
13707                self.scrollbar_marker_state.dirty = true;
13708                cx.notify();
13709            }
13710            _ => {}
13711        };
13712    }
13713
13714    fn on_display_map_changed(
13715        &mut self,
13716        _: Entity<DisplayMap>,
13717        _: &mut Window,
13718        cx: &mut Context<Self>,
13719    ) {
13720        cx.notify();
13721    }
13722
13723    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13724        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13725        self.refresh_inline_completion(true, false, window, cx);
13726        self.refresh_inlay_hints(
13727            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13728                self.selections.newest_anchor().head(),
13729                &self.buffer.read(cx).snapshot(cx),
13730                cx,
13731            )),
13732            cx,
13733        );
13734
13735        let old_cursor_shape = self.cursor_shape;
13736
13737        {
13738            let editor_settings = EditorSettings::get_global(cx);
13739            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13740            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13741            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13742        }
13743
13744        if old_cursor_shape != self.cursor_shape {
13745            cx.emit(EditorEvent::CursorShapeChanged);
13746        }
13747
13748        let project_settings = ProjectSettings::get_global(cx);
13749        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13750
13751        if self.mode == EditorMode::Full {
13752            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13753            if self.git_blame_inline_enabled != inline_blame_enabled {
13754                self.toggle_git_blame_inline_internal(false, window, cx);
13755            }
13756        }
13757
13758        cx.notify();
13759    }
13760
13761    pub fn set_searchable(&mut self, searchable: bool) {
13762        self.searchable = searchable;
13763    }
13764
13765    pub fn searchable(&self) -> bool {
13766        self.searchable
13767    }
13768
13769    fn open_proposed_changes_editor(
13770        &mut self,
13771        _: &OpenProposedChangesEditor,
13772        window: &mut Window,
13773        cx: &mut Context<Self>,
13774    ) {
13775        let Some(workspace) = self.workspace() else {
13776            cx.propagate();
13777            return;
13778        };
13779
13780        let selections = self.selections.all::<usize>(cx);
13781        let multi_buffer = self.buffer.read(cx);
13782        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13783        let mut new_selections_by_buffer = HashMap::default();
13784        for selection in selections {
13785            for (buffer, range, _) in
13786                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13787            {
13788                let mut range = range.to_point(buffer);
13789                range.start.column = 0;
13790                range.end.column = buffer.line_len(range.end.row);
13791                new_selections_by_buffer
13792                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13793                    .or_insert(Vec::new())
13794                    .push(range)
13795            }
13796        }
13797
13798        let proposed_changes_buffers = new_selections_by_buffer
13799            .into_iter()
13800            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13801            .collect::<Vec<_>>();
13802        let proposed_changes_editor = cx.new(|cx| {
13803            ProposedChangesEditor::new(
13804                "Proposed changes",
13805                proposed_changes_buffers,
13806                self.project.clone(),
13807                window,
13808                cx,
13809            )
13810        });
13811
13812        window.defer(cx, move |window, cx| {
13813            workspace.update(cx, |workspace, cx| {
13814                workspace.active_pane().update(cx, |pane, cx| {
13815                    pane.add_item(
13816                        Box::new(proposed_changes_editor),
13817                        true,
13818                        true,
13819                        None,
13820                        window,
13821                        cx,
13822                    );
13823                });
13824            });
13825        });
13826    }
13827
13828    pub fn open_excerpts_in_split(
13829        &mut self,
13830        _: &OpenExcerptsSplit,
13831        window: &mut Window,
13832        cx: &mut Context<Self>,
13833    ) {
13834        self.open_excerpts_common(None, true, window, cx)
13835    }
13836
13837    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13838        self.open_excerpts_common(None, false, window, cx)
13839    }
13840
13841    fn open_excerpts_common(
13842        &mut self,
13843        jump_data: Option<JumpData>,
13844        split: bool,
13845        window: &mut Window,
13846        cx: &mut Context<Self>,
13847    ) {
13848        let Some(workspace) = self.workspace() else {
13849            cx.propagate();
13850            return;
13851        };
13852
13853        if self.buffer.read(cx).is_singleton() {
13854            cx.propagate();
13855            return;
13856        }
13857
13858        let mut new_selections_by_buffer = HashMap::default();
13859        match &jump_data {
13860            Some(JumpData::MultiBufferPoint {
13861                excerpt_id,
13862                position,
13863                anchor,
13864                line_offset_from_top,
13865            }) => {
13866                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13867                if let Some(buffer) = multi_buffer_snapshot
13868                    .buffer_id_for_excerpt(*excerpt_id)
13869                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13870                {
13871                    let buffer_snapshot = buffer.read(cx).snapshot();
13872                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13873                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13874                    } else {
13875                        buffer_snapshot.clip_point(*position, Bias::Left)
13876                    };
13877                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13878                    new_selections_by_buffer.insert(
13879                        buffer,
13880                        (
13881                            vec![jump_to_offset..jump_to_offset],
13882                            Some(*line_offset_from_top),
13883                        ),
13884                    );
13885                }
13886            }
13887            Some(JumpData::MultiBufferRow {
13888                row,
13889                line_offset_from_top,
13890            }) => {
13891                let point = MultiBufferPoint::new(row.0, 0);
13892                if let Some((buffer, buffer_point, _)) =
13893                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13894                {
13895                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13896                    new_selections_by_buffer
13897                        .entry(buffer)
13898                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13899                        .0
13900                        .push(buffer_offset..buffer_offset)
13901                }
13902            }
13903            None => {
13904                let selections = self.selections.all::<usize>(cx);
13905                let multi_buffer = self.buffer.read(cx);
13906                for selection in selections {
13907                    for (buffer, mut range, _) in multi_buffer
13908                        .snapshot(cx)
13909                        .range_to_buffer_ranges(selection.range())
13910                    {
13911                        // When editing branch buffers, jump to the corresponding location
13912                        // in their base buffer.
13913                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13914                        let buffer = buffer_handle.read(cx);
13915                        if let Some(base_buffer) = buffer.base_buffer() {
13916                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13917                            buffer_handle = base_buffer;
13918                        }
13919
13920                        if selection.reversed {
13921                            mem::swap(&mut range.start, &mut range.end);
13922                        }
13923                        new_selections_by_buffer
13924                            .entry(buffer_handle)
13925                            .or_insert((Vec::new(), None))
13926                            .0
13927                            .push(range)
13928                    }
13929                }
13930            }
13931        }
13932
13933        if new_selections_by_buffer.is_empty() {
13934            return;
13935        }
13936
13937        // We defer the pane interaction because we ourselves are a workspace item
13938        // and activating a new item causes the pane to call a method on us reentrantly,
13939        // which panics if we're on the stack.
13940        window.defer(cx, move |window, cx| {
13941            workspace.update(cx, |workspace, cx| {
13942                let pane = if split {
13943                    workspace.adjacent_pane(window, cx)
13944                } else {
13945                    workspace.active_pane().clone()
13946                };
13947
13948                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13949                    let editor = buffer
13950                        .read(cx)
13951                        .file()
13952                        .is_none()
13953                        .then(|| {
13954                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13955                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13956                            // Instead, we try to activate the existing editor in the pane first.
13957                            let (editor, pane_item_index) =
13958                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13959                                    let editor = item.downcast::<Editor>()?;
13960                                    let singleton_buffer =
13961                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13962                                    if singleton_buffer == buffer {
13963                                        Some((editor, i))
13964                                    } else {
13965                                        None
13966                                    }
13967                                })?;
13968                            pane.update(cx, |pane, cx| {
13969                                pane.activate_item(pane_item_index, true, true, window, cx)
13970                            });
13971                            Some(editor)
13972                        })
13973                        .flatten()
13974                        .unwrap_or_else(|| {
13975                            workspace.open_project_item::<Self>(
13976                                pane.clone(),
13977                                buffer,
13978                                true,
13979                                true,
13980                                window,
13981                                cx,
13982                            )
13983                        });
13984
13985                    editor.update(cx, |editor, cx| {
13986                        let autoscroll = match scroll_offset {
13987                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13988                            None => Autoscroll::newest(),
13989                        };
13990                        let nav_history = editor.nav_history.take();
13991                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13992                            s.select_ranges(ranges);
13993                        });
13994                        editor.nav_history = nav_history;
13995                    });
13996                }
13997            })
13998        });
13999    }
14000
14001    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14002        let snapshot = self.buffer.read(cx).read(cx);
14003        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14004        Some(
14005            ranges
14006                .iter()
14007                .map(move |range| {
14008                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14009                })
14010                .collect(),
14011        )
14012    }
14013
14014    fn selection_replacement_ranges(
14015        &self,
14016        range: Range<OffsetUtf16>,
14017        cx: &mut App,
14018    ) -> Vec<Range<OffsetUtf16>> {
14019        let selections = self.selections.all::<OffsetUtf16>(cx);
14020        let newest_selection = selections
14021            .iter()
14022            .max_by_key(|selection| selection.id)
14023            .unwrap();
14024        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14025        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14026        let snapshot = self.buffer.read(cx).read(cx);
14027        selections
14028            .into_iter()
14029            .map(|mut selection| {
14030                selection.start.0 =
14031                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14032                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14033                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14034                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14035            })
14036            .collect()
14037    }
14038
14039    fn report_editor_event(
14040        &self,
14041        event_type: &'static str,
14042        file_extension: Option<String>,
14043        cx: &App,
14044    ) {
14045        if cfg!(any(test, feature = "test-support")) {
14046            return;
14047        }
14048
14049        let Some(project) = &self.project else { return };
14050
14051        // If None, we are in a file without an extension
14052        let file = self
14053            .buffer
14054            .read(cx)
14055            .as_singleton()
14056            .and_then(|b| b.read(cx).file());
14057        let file_extension = file_extension.or(file
14058            .as_ref()
14059            .and_then(|file| Path::new(file.file_name(cx)).extension())
14060            .and_then(|e| e.to_str())
14061            .map(|a| a.to_string()));
14062
14063        let vim_mode = cx
14064            .global::<SettingsStore>()
14065            .raw_user_settings()
14066            .get("vim_mode")
14067            == Some(&serde_json::Value::Bool(true));
14068
14069        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14070            == language::language_settings::InlineCompletionProvider::Copilot;
14071        let copilot_enabled_for_language = self
14072            .buffer
14073            .read(cx)
14074            .settings_at(0, cx)
14075            .show_inline_completions;
14076
14077        let project = project.read(cx);
14078        telemetry::event!(
14079            event_type,
14080            file_extension,
14081            vim_mode,
14082            copilot_enabled,
14083            copilot_enabled_for_language,
14084            is_via_ssh = project.is_via_ssh(),
14085        );
14086    }
14087
14088    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14089    /// with each line being an array of {text, highlight} objects.
14090    fn copy_highlight_json(
14091        &mut self,
14092        _: &CopyHighlightJson,
14093        window: &mut Window,
14094        cx: &mut Context<Self>,
14095    ) {
14096        #[derive(Serialize)]
14097        struct Chunk<'a> {
14098            text: String,
14099            highlight: Option<&'a str>,
14100        }
14101
14102        let snapshot = self.buffer.read(cx).snapshot(cx);
14103        let range = self
14104            .selected_text_range(false, window, cx)
14105            .and_then(|selection| {
14106                if selection.range.is_empty() {
14107                    None
14108                } else {
14109                    Some(selection.range)
14110                }
14111            })
14112            .unwrap_or_else(|| 0..snapshot.len());
14113
14114        let chunks = snapshot.chunks(range, true);
14115        let mut lines = Vec::new();
14116        let mut line: VecDeque<Chunk> = VecDeque::new();
14117
14118        let Some(style) = self.style.as_ref() else {
14119            return;
14120        };
14121
14122        for chunk in chunks {
14123            let highlight = chunk
14124                .syntax_highlight_id
14125                .and_then(|id| id.name(&style.syntax));
14126            let mut chunk_lines = chunk.text.split('\n').peekable();
14127            while let Some(text) = chunk_lines.next() {
14128                let mut merged_with_last_token = false;
14129                if let Some(last_token) = line.back_mut() {
14130                    if last_token.highlight == highlight {
14131                        last_token.text.push_str(text);
14132                        merged_with_last_token = true;
14133                    }
14134                }
14135
14136                if !merged_with_last_token {
14137                    line.push_back(Chunk {
14138                        text: text.into(),
14139                        highlight,
14140                    });
14141                }
14142
14143                if chunk_lines.peek().is_some() {
14144                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14145                        line.pop_front();
14146                    }
14147                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14148                        line.pop_back();
14149                    }
14150
14151                    lines.push(mem::take(&mut line));
14152                }
14153            }
14154        }
14155
14156        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14157            return;
14158        };
14159        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14160    }
14161
14162    pub fn open_context_menu(
14163        &mut self,
14164        _: &OpenContextMenu,
14165        window: &mut Window,
14166        cx: &mut Context<Self>,
14167    ) {
14168        self.request_autoscroll(Autoscroll::newest(), cx);
14169        let position = self.selections.newest_display(cx).start;
14170        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14171    }
14172
14173    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14174        &self.inlay_hint_cache
14175    }
14176
14177    pub fn replay_insert_event(
14178        &mut self,
14179        text: &str,
14180        relative_utf16_range: Option<Range<isize>>,
14181        window: &mut Window,
14182        cx: &mut Context<Self>,
14183    ) {
14184        if !self.input_enabled {
14185            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14186            return;
14187        }
14188        if let Some(relative_utf16_range) = relative_utf16_range {
14189            let selections = self.selections.all::<OffsetUtf16>(cx);
14190            self.change_selections(None, window, cx, |s| {
14191                let new_ranges = selections.into_iter().map(|range| {
14192                    let start = OffsetUtf16(
14193                        range
14194                            .head()
14195                            .0
14196                            .saturating_add_signed(relative_utf16_range.start),
14197                    );
14198                    let end = OffsetUtf16(
14199                        range
14200                            .head()
14201                            .0
14202                            .saturating_add_signed(relative_utf16_range.end),
14203                    );
14204                    start..end
14205                });
14206                s.select_ranges(new_ranges);
14207            });
14208        }
14209
14210        self.handle_input(text, window, cx);
14211    }
14212
14213    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14214        let Some(provider) = self.semantics_provider.as_ref() else {
14215            return false;
14216        };
14217
14218        let mut supports = false;
14219        self.buffer().read(cx).for_each_buffer(|buffer| {
14220            supports |= provider.supports_inlay_hints(buffer, cx);
14221        });
14222        supports
14223    }
14224    pub fn is_focused(&self, window: &mut Window) -> bool {
14225        self.focus_handle.is_focused(window)
14226    }
14227
14228    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14229        cx.emit(EditorEvent::Focused);
14230
14231        if let Some(descendant) = self
14232            .last_focused_descendant
14233            .take()
14234            .and_then(|descendant| descendant.upgrade())
14235        {
14236            window.focus(&descendant);
14237        } else {
14238            if let Some(blame) = self.blame.as_ref() {
14239                blame.update(cx, GitBlame::focus)
14240            }
14241
14242            self.blink_manager.update(cx, BlinkManager::enable);
14243            self.show_cursor_names(window, cx);
14244            self.buffer.update(cx, |buffer, cx| {
14245                buffer.finalize_last_transaction(cx);
14246                if self.leader_peer_id.is_none() {
14247                    buffer.set_active_selections(
14248                        &self.selections.disjoint_anchors(),
14249                        self.selections.line_mode,
14250                        self.cursor_shape,
14251                        cx,
14252                    );
14253                }
14254            });
14255        }
14256    }
14257
14258    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14259        cx.emit(EditorEvent::FocusedIn)
14260    }
14261
14262    fn handle_focus_out(
14263        &mut self,
14264        event: FocusOutEvent,
14265        _window: &mut Window,
14266        _cx: &mut Context<Self>,
14267    ) {
14268        if event.blurred != self.focus_handle {
14269            self.last_focused_descendant = Some(event.blurred);
14270        }
14271    }
14272
14273    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14274        self.blink_manager.update(cx, BlinkManager::disable);
14275        self.buffer
14276            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14277
14278        if let Some(blame) = self.blame.as_ref() {
14279            blame.update(cx, GitBlame::blur)
14280        }
14281        if !self.hover_state.focused(window, cx) {
14282            hide_hover(self, cx);
14283        }
14284
14285        self.hide_context_menu(window, cx);
14286        cx.emit(EditorEvent::Blurred);
14287        cx.notify();
14288    }
14289
14290    pub fn register_action<A: Action>(
14291        &mut self,
14292        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14293    ) -> Subscription {
14294        let id = self.next_editor_action_id.post_inc();
14295        let listener = Arc::new(listener);
14296        self.editor_actions.borrow_mut().insert(
14297            id,
14298            Box::new(move |window, _| {
14299                let listener = listener.clone();
14300                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14301                    let action = action.downcast_ref().unwrap();
14302                    if phase == DispatchPhase::Bubble {
14303                        listener(action, window, cx)
14304                    }
14305                })
14306            }),
14307        );
14308
14309        let editor_actions = self.editor_actions.clone();
14310        Subscription::new(move || {
14311            editor_actions.borrow_mut().remove(&id);
14312        })
14313    }
14314
14315    pub fn file_header_size(&self) -> u32 {
14316        FILE_HEADER_HEIGHT
14317    }
14318
14319    pub fn revert(
14320        &mut self,
14321        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14322        window: &mut Window,
14323        cx: &mut Context<Self>,
14324    ) {
14325        self.buffer().update(cx, |multi_buffer, cx| {
14326            for (buffer_id, changes) in revert_changes {
14327                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14328                    buffer.update(cx, |buffer, cx| {
14329                        buffer.edit(
14330                            changes.into_iter().map(|(range, text)| {
14331                                (range, text.to_string().map(Arc::<str>::from))
14332                            }),
14333                            None,
14334                            cx,
14335                        );
14336                    });
14337                }
14338            }
14339        });
14340        self.change_selections(None, window, cx, |selections| selections.refresh());
14341    }
14342
14343    pub fn to_pixel_point(
14344        &self,
14345        source: multi_buffer::Anchor,
14346        editor_snapshot: &EditorSnapshot,
14347        window: &mut Window,
14348    ) -> Option<gpui::Point<Pixels>> {
14349        let source_point = source.to_display_point(editor_snapshot);
14350        self.display_to_pixel_point(source_point, editor_snapshot, window)
14351    }
14352
14353    pub fn display_to_pixel_point(
14354        &self,
14355        source: DisplayPoint,
14356        editor_snapshot: &EditorSnapshot,
14357        window: &mut Window,
14358    ) -> Option<gpui::Point<Pixels>> {
14359        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14360        let text_layout_details = self.text_layout_details(window);
14361        let scroll_top = text_layout_details
14362            .scroll_anchor
14363            .scroll_position(editor_snapshot)
14364            .y;
14365
14366        if source.row().as_f32() < scroll_top.floor() {
14367            return None;
14368        }
14369        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14370        let source_y = line_height * (source.row().as_f32() - scroll_top);
14371        Some(gpui::Point::new(source_x, source_y))
14372    }
14373
14374    pub fn has_active_completions_menu(&self) -> bool {
14375        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14376            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14377        })
14378    }
14379
14380    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14381        self.addons
14382            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14383    }
14384
14385    pub fn unregister_addon<T: Addon>(&mut self) {
14386        self.addons.remove(&std::any::TypeId::of::<T>());
14387    }
14388
14389    pub fn addon<T: Addon>(&self) -> Option<&T> {
14390        let type_id = std::any::TypeId::of::<T>();
14391        self.addons
14392            .get(&type_id)
14393            .and_then(|item| item.to_any().downcast_ref::<T>())
14394    }
14395
14396    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14397        let text_layout_details = self.text_layout_details(window);
14398        let style = &text_layout_details.editor_style;
14399        let font_id = window.text_system().resolve_font(&style.text.font());
14400        let font_size = style.text.font_size.to_pixels(window.rem_size());
14401        let line_height = style.text.line_height_in_pixels(window.rem_size());
14402        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14403
14404        gpui::Size::new(em_width, line_height)
14405    }
14406}
14407
14408fn get_unstaged_changes_for_buffers(
14409    project: &Entity<Project>,
14410    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14411    buffer: Entity<MultiBuffer>,
14412    cx: &mut App,
14413) {
14414    let mut tasks = Vec::new();
14415    project.update(cx, |project, cx| {
14416        for buffer in buffers {
14417            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14418        }
14419    });
14420    cx.spawn(|mut cx| async move {
14421        let change_sets = futures::future::join_all(tasks).await;
14422        buffer
14423            .update(&mut cx, |buffer, cx| {
14424                for change_set in change_sets {
14425                    if let Some(change_set) = change_set.log_err() {
14426                        buffer.add_change_set(change_set, cx);
14427                    }
14428                }
14429            })
14430            .ok();
14431    })
14432    .detach();
14433}
14434
14435fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14436    let tab_size = tab_size.get() as usize;
14437    let mut width = offset;
14438
14439    for ch in text.chars() {
14440        width += if ch == '\t' {
14441            tab_size - (width % tab_size)
14442        } else {
14443            1
14444        };
14445    }
14446
14447    width - offset
14448}
14449
14450#[cfg(test)]
14451mod tests {
14452    use super::*;
14453
14454    #[test]
14455    fn test_string_size_with_expanded_tabs() {
14456        let nz = |val| NonZeroU32::new(val).unwrap();
14457        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14458        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14459        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14460        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14461        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14462        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14463        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14464        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14465    }
14466}
14467
14468/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14469struct WordBreakingTokenizer<'a> {
14470    input: &'a str,
14471}
14472
14473impl<'a> WordBreakingTokenizer<'a> {
14474    fn new(input: &'a str) -> Self {
14475        Self { input }
14476    }
14477}
14478
14479fn is_char_ideographic(ch: char) -> bool {
14480    use unicode_script::Script::*;
14481    use unicode_script::UnicodeScript;
14482    matches!(ch.script(), Han | Tangut | Yi)
14483}
14484
14485fn is_grapheme_ideographic(text: &str) -> bool {
14486    text.chars().any(is_char_ideographic)
14487}
14488
14489fn is_grapheme_whitespace(text: &str) -> bool {
14490    text.chars().any(|x| x.is_whitespace())
14491}
14492
14493fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14494    text.chars().next().map_or(false, |ch| {
14495        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14496    })
14497}
14498
14499#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14500struct WordBreakToken<'a> {
14501    token: &'a str,
14502    grapheme_len: usize,
14503    is_whitespace: bool,
14504}
14505
14506impl<'a> Iterator for WordBreakingTokenizer<'a> {
14507    /// Yields a span, the count of graphemes in the token, and whether it was
14508    /// whitespace. Note that it also breaks at word boundaries.
14509    type Item = WordBreakToken<'a>;
14510
14511    fn next(&mut self) -> Option<Self::Item> {
14512        use unicode_segmentation::UnicodeSegmentation;
14513        if self.input.is_empty() {
14514            return None;
14515        }
14516
14517        let mut iter = self.input.graphemes(true).peekable();
14518        let mut offset = 0;
14519        let mut graphemes = 0;
14520        if let Some(first_grapheme) = iter.next() {
14521            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14522            offset += first_grapheme.len();
14523            graphemes += 1;
14524            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14525                if let Some(grapheme) = iter.peek().copied() {
14526                    if should_stay_with_preceding_ideograph(grapheme) {
14527                        offset += grapheme.len();
14528                        graphemes += 1;
14529                    }
14530                }
14531            } else {
14532                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14533                let mut next_word_bound = words.peek().copied();
14534                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14535                    next_word_bound = words.next();
14536                }
14537                while let Some(grapheme) = iter.peek().copied() {
14538                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14539                        break;
14540                    };
14541                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14542                        break;
14543                    };
14544                    offset += grapheme.len();
14545                    graphemes += 1;
14546                    iter.next();
14547                }
14548            }
14549            let token = &self.input[..offset];
14550            self.input = &self.input[offset..];
14551            if is_whitespace {
14552                Some(WordBreakToken {
14553                    token: " ",
14554                    grapheme_len: 1,
14555                    is_whitespace: true,
14556                })
14557            } else {
14558                Some(WordBreakToken {
14559                    token,
14560                    grapheme_len: graphemes,
14561                    is_whitespace: false,
14562                })
14563            }
14564        } else {
14565            None
14566        }
14567    }
14568}
14569
14570#[test]
14571fn test_word_breaking_tokenizer() {
14572    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14573        ("", &[]),
14574        ("  ", &[(" ", 1, true)]),
14575        ("Ʒ", &[("Ʒ", 1, false)]),
14576        ("Ǽ", &[("Ǽ", 1, false)]),
14577        ("", &[("", 1, false)]),
14578        ("⋑⋑", &[("⋑⋑", 2, false)]),
14579        (
14580            "原理,进而",
14581            &[
14582                ("", 1, false),
14583                ("理,", 2, false),
14584                ("", 1, false),
14585                ("", 1, false),
14586            ],
14587        ),
14588        (
14589            "hello world",
14590            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14591        ),
14592        (
14593            "hello, world",
14594            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14595        ),
14596        (
14597            "  hello world",
14598            &[
14599                (" ", 1, true),
14600                ("hello", 5, false),
14601                (" ", 1, true),
14602                ("world", 5, false),
14603            ],
14604        ),
14605        (
14606            "这是什么 \n 钢笔",
14607            &[
14608                ("", 1, false),
14609                ("", 1, false),
14610                ("", 1, false),
14611                ("", 1, false),
14612                (" ", 1, true),
14613                ("", 1, false),
14614                ("", 1, false),
14615            ],
14616        ),
14617        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14618    ];
14619
14620    for (input, result) in tests {
14621        assert_eq!(
14622            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14623            result
14624                .iter()
14625                .copied()
14626                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14627                    token,
14628                    grapheme_len,
14629                    is_whitespace,
14630                })
14631                .collect::<Vec<_>>()
14632        );
14633    }
14634}
14635
14636fn wrap_with_prefix(
14637    line_prefix: String,
14638    unwrapped_text: String,
14639    wrap_column: usize,
14640    tab_size: NonZeroU32,
14641) -> String {
14642    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14643    let mut wrapped_text = String::new();
14644    let mut current_line = line_prefix.clone();
14645
14646    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14647    let mut current_line_len = line_prefix_len;
14648    for WordBreakToken {
14649        token,
14650        grapheme_len,
14651        is_whitespace,
14652    } in tokenizer
14653    {
14654        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14655            wrapped_text.push_str(current_line.trim_end());
14656            wrapped_text.push('\n');
14657            current_line.truncate(line_prefix.len());
14658            current_line_len = line_prefix_len;
14659            if !is_whitespace {
14660                current_line.push_str(token);
14661                current_line_len += grapheme_len;
14662            }
14663        } else if !is_whitespace {
14664            current_line.push_str(token);
14665            current_line_len += grapheme_len;
14666        } else if current_line_len != line_prefix_len {
14667            current_line.push(' ');
14668            current_line_len += 1;
14669        }
14670    }
14671
14672    if !current_line.is_empty() {
14673        wrapped_text.push_str(&current_line);
14674    }
14675    wrapped_text
14676}
14677
14678#[test]
14679fn test_wrap_with_prefix() {
14680    assert_eq!(
14681        wrap_with_prefix(
14682            "# ".to_string(),
14683            "abcdefg".to_string(),
14684            4,
14685            NonZeroU32::new(4).unwrap()
14686        ),
14687        "# abcdefg"
14688    );
14689    assert_eq!(
14690        wrap_with_prefix(
14691            "".to_string(),
14692            "\thello world".to_string(),
14693            8,
14694            NonZeroU32::new(4).unwrap()
14695        ),
14696        "hello\nworld"
14697    );
14698    assert_eq!(
14699        wrap_with_prefix(
14700            "// ".to_string(),
14701            "xx \nyy zz aa bb cc".to_string(),
14702            12,
14703            NonZeroU32::new(4).unwrap()
14704        ),
14705        "// xx yy zz\n// aa bb cc"
14706    );
14707    assert_eq!(
14708        wrap_with_prefix(
14709            String::new(),
14710            "这是什么 \n 钢笔".to_string(),
14711            3,
14712            NonZeroU32::new(4).unwrap()
14713        ),
14714        "这是什\n么 钢\n"
14715    );
14716}
14717
14718pub trait CollaborationHub {
14719    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14720    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14721    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14722}
14723
14724impl CollaborationHub for Entity<Project> {
14725    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14726        self.read(cx).collaborators()
14727    }
14728
14729    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14730        self.read(cx).user_store().read(cx).participant_indices()
14731    }
14732
14733    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14734        let this = self.read(cx);
14735        let user_ids = this.collaborators().values().map(|c| c.user_id);
14736        this.user_store().read_with(cx, |user_store, cx| {
14737            user_store.participant_names(user_ids, cx)
14738        })
14739    }
14740}
14741
14742pub trait SemanticsProvider {
14743    fn hover(
14744        &self,
14745        buffer: &Entity<Buffer>,
14746        position: text::Anchor,
14747        cx: &mut App,
14748    ) -> Option<Task<Vec<project::Hover>>>;
14749
14750    fn inlay_hints(
14751        &self,
14752        buffer_handle: Entity<Buffer>,
14753        range: Range<text::Anchor>,
14754        cx: &mut App,
14755    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14756
14757    fn resolve_inlay_hint(
14758        &self,
14759        hint: InlayHint,
14760        buffer_handle: Entity<Buffer>,
14761        server_id: LanguageServerId,
14762        cx: &mut App,
14763    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14764
14765    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14766
14767    fn document_highlights(
14768        &self,
14769        buffer: &Entity<Buffer>,
14770        position: text::Anchor,
14771        cx: &mut App,
14772    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14773
14774    fn definitions(
14775        &self,
14776        buffer: &Entity<Buffer>,
14777        position: text::Anchor,
14778        kind: GotoDefinitionKind,
14779        cx: &mut App,
14780    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14781
14782    fn range_for_rename(
14783        &self,
14784        buffer: &Entity<Buffer>,
14785        position: text::Anchor,
14786        cx: &mut App,
14787    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14788
14789    fn perform_rename(
14790        &self,
14791        buffer: &Entity<Buffer>,
14792        position: text::Anchor,
14793        new_name: String,
14794        cx: &mut App,
14795    ) -> Option<Task<Result<ProjectTransaction>>>;
14796}
14797
14798pub trait CompletionProvider {
14799    fn completions(
14800        &self,
14801        buffer: &Entity<Buffer>,
14802        buffer_position: text::Anchor,
14803        trigger: CompletionContext,
14804        window: &mut Window,
14805        cx: &mut Context<Editor>,
14806    ) -> Task<Result<Vec<Completion>>>;
14807
14808    fn resolve_completions(
14809        &self,
14810        buffer: Entity<Buffer>,
14811        completion_indices: Vec<usize>,
14812        completions: Rc<RefCell<Box<[Completion]>>>,
14813        cx: &mut Context<Editor>,
14814    ) -> Task<Result<bool>>;
14815
14816    fn apply_additional_edits_for_completion(
14817        &self,
14818        _buffer: Entity<Buffer>,
14819        _completions: Rc<RefCell<Box<[Completion]>>>,
14820        _completion_index: usize,
14821        _push_to_history: bool,
14822        _cx: &mut Context<Editor>,
14823    ) -> Task<Result<Option<language::Transaction>>> {
14824        Task::ready(Ok(None))
14825    }
14826
14827    fn is_completion_trigger(
14828        &self,
14829        buffer: &Entity<Buffer>,
14830        position: language::Anchor,
14831        text: &str,
14832        trigger_in_words: bool,
14833        cx: &mut Context<Editor>,
14834    ) -> bool;
14835
14836    fn sort_completions(&self) -> bool {
14837        true
14838    }
14839}
14840
14841pub trait CodeActionProvider {
14842    fn id(&self) -> Arc<str>;
14843
14844    fn code_actions(
14845        &self,
14846        buffer: &Entity<Buffer>,
14847        range: Range<text::Anchor>,
14848        window: &mut Window,
14849        cx: &mut App,
14850    ) -> Task<Result<Vec<CodeAction>>>;
14851
14852    fn apply_code_action(
14853        &self,
14854        buffer_handle: Entity<Buffer>,
14855        action: CodeAction,
14856        excerpt_id: ExcerptId,
14857        push_to_history: bool,
14858        window: &mut Window,
14859        cx: &mut App,
14860    ) -> Task<Result<ProjectTransaction>>;
14861}
14862
14863impl CodeActionProvider for Entity<Project> {
14864    fn id(&self) -> Arc<str> {
14865        "project".into()
14866    }
14867
14868    fn code_actions(
14869        &self,
14870        buffer: &Entity<Buffer>,
14871        range: Range<text::Anchor>,
14872        _window: &mut Window,
14873        cx: &mut App,
14874    ) -> Task<Result<Vec<CodeAction>>> {
14875        self.update(cx, |project, cx| {
14876            project.code_actions(buffer, range, None, cx)
14877        })
14878    }
14879
14880    fn apply_code_action(
14881        &self,
14882        buffer_handle: Entity<Buffer>,
14883        action: CodeAction,
14884        _excerpt_id: ExcerptId,
14885        push_to_history: bool,
14886        _window: &mut Window,
14887        cx: &mut App,
14888    ) -> Task<Result<ProjectTransaction>> {
14889        self.update(cx, |project, cx| {
14890            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14891        })
14892    }
14893}
14894
14895fn snippet_completions(
14896    project: &Project,
14897    buffer: &Entity<Buffer>,
14898    buffer_position: text::Anchor,
14899    cx: &mut App,
14900) -> Task<Result<Vec<Completion>>> {
14901    let language = buffer.read(cx).language_at(buffer_position);
14902    let language_name = language.as_ref().map(|language| language.lsp_id());
14903    let snippet_store = project.snippets().read(cx);
14904    let snippets = snippet_store.snippets_for(language_name, cx);
14905
14906    if snippets.is_empty() {
14907        return Task::ready(Ok(vec![]));
14908    }
14909    let snapshot = buffer.read(cx).text_snapshot();
14910    let chars: String = snapshot
14911        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14912        .collect();
14913
14914    let scope = language.map(|language| language.default_scope());
14915    let executor = cx.background_executor().clone();
14916
14917    cx.background_executor().spawn(async move {
14918        let classifier = CharClassifier::new(scope).for_completion(true);
14919        let mut last_word = chars
14920            .chars()
14921            .take_while(|c| classifier.is_word(*c))
14922            .collect::<String>();
14923        last_word = last_word.chars().rev().collect();
14924
14925        if last_word.is_empty() {
14926            return Ok(vec![]);
14927        }
14928
14929        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14930        let to_lsp = |point: &text::Anchor| {
14931            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14932            point_to_lsp(end)
14933        };
14934        let lsp_end = to_lsp(&buffer_position);
14935
14936        let candidates = snippets
14937            .iter()
14938            .enumerate()
14939            .flat_map(|(ix, snippet)| {
14940                snippet
14941                    .prefix
14942                    .iter()
14943                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14944            })
14945            .collect::<Vec<StringMatchCandidate>>();
14946
14947        let mut matches = fuzzy::match_strings(
14948            &candidates,
14949            &last_word,
14950            last_word.chars().any(|c| c.is_uppercase()),
14951            100,
14952            &Default::default(),
14953            executor,
14954        )
14955        .await;
14956
14957        // Remove all candidates where the query's start does not match the start of any word in the candidate
14958        if let Some(query_start) = last_word.chars().next() {
14959            matches.retain(|string_match| {
14960                split_words(&string_match.string).any(|word| {
14961                    // Check that the first codepoint of the word as lowercase matches the first
14962                    // codepoint of the query as lowercase
14963                    word.chars()
14964                        .flat_map(|codepoint| codepoint.to_lowercase())
14965                        .zip(query_start.to_lowercase())
14966                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14967                })
14968            });
14969        }
14970
14971        let matched_strings = matches
14972            .into_iter()
14973            .map(|m| m.string)
14974            .collect::<HashSet<_>>();
14975
14976        let result: Vec<Completion> = snippets
14977            .into_iter()
14978            .filter_map(|snippet| {
14979                let matching_prefix = snippet
14980                    .prefix
14981                    .iter()
14982                    .find(|prefix| matched_strings.contains(*prefix))?;
14983                let start = as_offset - last_word.len();
14984                let start = snapshot.anchor_before(start);
14985                let range = start..buffer_position;
14986                let lsp_start = to_lsp(&start);
14987                let lsp_range = lsp::Range {
14988                    start: lsp_start,
14989                    end: lsp_end,
14990                };
14991                Some(Completion {
14992                    old_range: range,
14993                    new_text: snippet.body.clone(),
14994                    resolved: false,
14995                    label: CodeLabel {
14996                        text: matching_prefix.clone(),
14997                        runs: vec![],
14998                        filter_range: 0..matching_prefix.len(),
14999                    },
15000                    server_id: LanguageServerId(usize::MAX),
15001                    documentation: snippet
15002                        .description
15003                        .clone()
15004                        .map(CompletionDocumentation::SingleLine),
15005                    lsp_completion: lsp::CompletionItem {
15006                        label: snippet.prefix.first().unwrap().clone(),
15007                        kind: Some(CompletionItemKind::SNIPPET),
15008                        label_details: snippet.description.as_ref().map(|description| {
15009                            lsp::CompletionItemLabelDetails {
15010                                detail: Some(description.clone()),
15011                                description: None,
15012                            }
15013                        }),
15014                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15015                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15016                            lsp::InsertReplaceEdit {
15017                                new_text: snippet.body.clone(),
15018                                insert: lsp_range,
15019                                replace: lsp_range,
15020                            },
15021                        )),
15022                        filter_text: Some(snippet.body.clone()),
15023                        sort_text: Some(char::MAX.to_string()),
15024                        ..Default::default()
15025                    },
15026                    confirm: None,
15027                })
15028            })
15029            .collect();
15030
15031        Ok(result)
15032    })
15033}
15034
15035impl CompletionProvider for Entity<Project> {
15036    fn completions(
15037        &self,
15038        buffer: &Entity<Buffer>,
15039        buffer_position: text::Anchor,
15040        options: CompletionContext,
15041        _window: &mut Window,
15042        cx: &mut Context<Editor>,
15043    ) -> Task<Result<Vec<Completion>>> {
15044        self.update(cx, |project, cx| {
15045            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15046            let project_completions = project.completions(buffer, buffer_position, options, cx);
15047            cx.background_executor().spawn(async move {
15048                let mut completions = project_completions.await?;
15049                let snippets_completions = snippets.await?;
15050                completions.extend(snippets_completions);
15051                Ok(completions)
15052            })
15053        })
15054    }
15055
15056    fn resolve_completions(
15057        &self,
15058        buffer: Entity<Buffer>,
15059        completion_indices: Vec<usize>,
15060        completions: Rc<RefCell<Box<[Completion]>>>,
15061        cx: &mut Context<Editor>,
15062    ) -> Task<Result<bool>> {
15063        self.update(cx, |project, cx| {
15064            project.lsp_store().update(cx, |lsp_store, cx| {
15065                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15066            })
15067        })
15068    }
15069
15070    fn apply_additional_edits_for_completion(
15071        &self,
15072        buffer: Entity<Buffer>,
15073        completions: Rc<RefCell<Box<[Completion]>>>,
15074        completion_index: usize,
15075        push_to_history: bool,
15076        cx: &mut Context<Editor>,
15077    ) -> Task<Result<Option<language::Transaction>>> {
15078        self.update(cx, |project, cx| {
15079            project.lsp_store().update(cx, |lsp_store, cx| {
15080                lsp_store.apply_additional_edits_for_completion(
15081                    buffer,
15082                    completions,
15083                    completion_index,
15084                    push_to_history,
15085                    cx,
15086                )
15087            })
15088        })
15089    }
15090
15091    fn is_completion_trigger(
15092        &self,
15093        buffer: &Entity<Buffer>,
15094        position: language::Anchor,
15095        text: &str,
15096        trigger_in_words: bool,
15097        cx: &mut Context<Editor>,
15098    ) -> bool {
15099        let mut chars = text.chars();
15100        let char = if let Some(char) = chars.next() {
15101            char
15102        } else {
15103            return false;
15104        };
15105        if chars.next().is_some() {
15106            return false;
15107        }
15108
15109        let buffer = buffer.read(cx);
15110        let snapshot = buffer.snapshot();
15111        if !snapshot.settings_at(position, cx).show_completions_on_input {
15112            return false;
15113        }
15114        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15115        if trigger_in_words && classifier.is_word(char) {
15116            return true;
15117        }
15118
15119        buffer.completion_triggers().contains(text)
15120    }
15121}
15122
15123impl SemanticsProvider for Entity<Project> {
15124    fn hover(
15125        &self,
15126        buffer: &Entity<Buffer>,
15127        position: text::Anchor,
15128        cx: &mut App,
15129    ) -> Option<Task<Vec<project::Hover>>> {
15130        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15131    }
15132
15133    fn document_highlights(
15134        &self,
15135        buffer: &Entity<Buffer>,
15136        position: text::Anchor,
15137        cx: &mut App,
15138    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15139        Some(self.update(cx, |project, cx| {
15140            project.document_highlights(buffer, position, cx)
15141        }))
15142    }
15143
15144    fn definitions(
15145        &self,
15146        buffer: &Entity<Buffer>,
15147        position: text::Anchor,
15148        kind: GotoDefinitionKind,
15149        cx: &mut App,
15150    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15151        Some(self.update(cx, |project, cx| match kind {
15152            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15153            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15154            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15155            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15156        }))
15157    }
15158
15159    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15160        // TODO: make this work for remote projects
15161        self.read(cx)
15162            .language_servers_for_local_buffer(buffer.read(cx), cx)
15163            .any(
15164                |(_, server)| match server.capabilities().inlay_hint_provider {
15165                    Some(lsp::OneOf::Left(enabled)) => enabled,
15166                    Some(lsp::OneOf::Right(_)) => true,
15167                    None => false,
15168                },
15169            )
15170    }
15171
15172    fn inlay_hints(
15173        &self,
15174        buffer_handle: Entity<Buffer>,
15175        range: Range<text::Anchor>,
15176        cx: &mut App,
15177    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15178        Some(self.update(cx, |project, cx| {
15179            project.inlay_hints(buffer_handle, range, cx)
15180        }))
15181    }
15182
15183    fn resolve_inlay_hint(
15184        &self,
15185        hint: InlayHint,
15186        buffer_handle: Entity<Buffer>,
15187        server_id: LanguageServerId,
15188        cx: &mut App,
15189    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15190        Some(self.update(cx, |project, cx| {
15191            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15192        }))
15193    }
15194
15195    fn range_for_rename(
15196        &self,
15197        buffer: &Entity<Buffer>,
15198        position: text::Anchor,
15199        cx: &mut App,
15200    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15201        Some(self.update(cx, |project, cx| {
15202            let buffer = buffer.clone();
15203            let task = project.prepare_rename(buffer.clone(), position, cx);
15204            cx.spawn(|_, mut cx| async move {
15205                Ok(match task.await? {
15206                    PrepareRenameResponse::Success(range) => Some(range),
15207                    PrepareRenameResponse::InvalidPosition => None,
15208                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15209                        // Fallback on using TreeSitter info to determine identifier range
15210                        buffer.update(&mut cx, |buffer, _| {
15211                            let snapshot = buffer.snapshot();
15212                            let (range, kind) = snapshot.surrounding_word(position);
15213                            if kind != Some(CharKind::Word) {
15214                                return None;
15215                            }
15216                            Some(
15217                                snapshot.anchor_before(range.start)
15218                                    ..snapshot.anchor_after(range.end),
15219                            )
15220                        })?
15221                    }
15222                })
15223            })
15224        }))
15225    }
15226
15227    fn perform_rename(
15228        &self,
15229        buffer: &Entity<Buffer>,
15230        position: text::Anchor,
15231        new_name: String,
15232        cx: &mut App,
15233    ) -> Option<Task<Result<ProjectTransaction>>> {
15234        Some(self.update(cx, |project, cx| {
15235            project.perform_rename(buffer.clone(), position, new_name, cx)
15236        }))
15237    }
15238}
15239
15240fn inlay_hint_settings(
15241    location: Anchor,
15242    snapshot: &MultiBufferSnapshot,
15243    cx: &mut Context<Editor>,
15244) -> InlayHintSettings {
15245    let file = snapshot.file_at(location);
15246    let language = snapshot.language_at(location).map(|l| l.name());
15247    language_settings(language, file, cx).inlay_hints
15248}
15249
15250fn consume_contiguous_rows(
15251    contiguous_row_selections: &mut Vec<Selection<Point>>,
15252    selection: &Selection<Point>,
15253    display_map: &DisplaySnapshot,
15254    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15255) -> (MultiBufferRow, MultiBufferRow) {
15256    contiguous_row_selections.push(selection.clone());
15257    let start_row = MultiBufferRow(selection.start.row);
15258    let mut end_row = ending_row(selection, display_map);
15259
15260    while let Some(next_selection) = selections.peek() {
15261        if next_selection.start.row <= end_row.0 {
15262            end_row = ending_row(next_selection, display_map);
15263            contiguous_row_selections.push(selections.next().unwrap().clone());
15264        } else {
15265            break;
15266        }
15267    }
15268    (start_row, end_row)
15269}
15270
15271fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15272    if next_selection.end.column > 0 || next_selection.is_empty() {
15273        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15274    } else {
15275        MultiBufferRow(next_selection.end.row)
15276    }
15277}
15278
15279impl EditorSnapshot {
15280    pub fn remote_selections_in_range<'a>(
15281        &'a self,
15282        range: &'a Range<Anchor>,
15283        collaboration_hub: &dyn CollaborationHub,
15284        cx: &'a App,
15285    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15286        let participant_names = collaboration_hub.user_names(cx);
15287        let participant_indices = collaboration_hub.user_participant_indices(cx);
15288        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15289        let collaborators_by_replica_id = collaborators_by_peer_id
15290            .iter()
15291            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15292            .collect::<HashMap<_, _>>();
15293        self.buffer_snapshot
15294            .selections_in_range(range, false)
15295            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15296                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15297                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15298                let user_name = participant_names.get(&collaborator.user_id).cloned();
15299                Some(RemoteSelection {
15300                    replica_id,
15301                    selection,
15302                    cursor_shape,
15303                    line_mode,
15304                    participant_index,
15305                    peer_id: collaborator.peer_id,
15306                    user_name,
15307                })
15308            })
15309    }
15310
15311    pub fn hunks_for_ranges(
15312        &self,
15313        ranges: impl Iterator<Item = Range<Point>>,
15314    ) -> Vec<MultiBufferDiffHunk> {
15315        let mut hunks = Vec::new();
15316        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15317            HashMap::default();
15318        for query_range in ranges {
15319            let query_rows =
15320                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15321            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15322                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15323            ) {
15324                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15325                // when the caret is just above or just below the deleted hunk.
15326                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15327                let related_to_selection = if allow_adjacent {
15328                    hunk.row_range.overlaps(&query_rows)
15329                        || hunk.row_range.start == query_rows.end
15330                        || hunk.row_range.end == query_rows.start
15331                } else {
15332                    hunk.row_range.overlaps(&query_rows)
15333                };
15334                if related_to_selection {
15335                    if !processed_buffer_rows
15336                        .entry(hunk.buffer_id)
15337                        .or_default()
15338                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15339                    {
15340                        continue;
15341                    }
15342                    hunks.push(hunk);
15343                }
15344            }
15345        }
15346
15347        hunks
15348    }
15349
15350    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15351        self.display_snapshot.buffer_snapshot.language_at(position)
15352    }
15353
15354    pub fn is_focused(&self) -> bool {
15355        self.is_focused
15356    }
15357
15358    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15359        self.placeholder_text.as_ref()
15360    }
15361
15362    pub fn scroll_position(&self) -> gpui::Point<f32> {
15363        self.scroll_anchor.scroll_position(&self.display_snapshot)
15364    }
15365
15366    fn gutter_dimensions(
15367        &self,
15368        font_id: FontId,
15369        font_size: Pixels,
15370        max_line_number_width: Pixels,
15371        cx: &App,
15372    ) -> Option<GutterDimensions> {
15373        if !self.show_gutter {
15374            return None;
15375        }
15376
15377        let descent = cx.text_system().descent(font_id, font_size);
15378        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15379        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15380
15381        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15382            matches!(
15383                ProjectSettings::get_global(cx).git.git_gutter,
15384                Some(GitGutterSetting::TrackedFiles)
15385            )
15386        });
15387        let gutter_settings = EditorSettings::get_global(cx).gutter;
15388        let show_line_numbers = self
15389            .show_line_numbers
15390            .unwrap_or(gutter_settings.line_numbers);
15391        let line_gutter_width = if show_line_numbers {
15392            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15393            let min_width_for_number_on_gutter = em_advance * 4.0;
15394            max_line_number_width.max(min_width_for_number_on_gutter)
15395        } else {
15396            0.0.into()
15397        };
15398
15399        let show_code_actions = self
15400            .show_code_actions
15401            .unwrap_or(gutter_settings.code_actions);
15402
15403        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15404
15405        let git_blame_entries_width =
15406            self.git_blame_gutter_max_author_length
15407                .map(|max_author_length| {
15408                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15409
15410                    /// The number of characters to dedicate to gaps and margins.
15411                    const SPACING_WIDTH: usize = 4;
15412
15413                    let max_char_count = max_author_length
15414                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15415                        + ::git::SHORT_SHA_LENGTH
15416                        + MAX_RELATIVE_TIMESTAMP.len()
15417                        + SPACING_WIDTH;
15418
15419                    em_advance * max_char_count
15420                });
15421
15422        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15423        left_padding += if show_code_actions || show_runnables {
15424            em_width * 3.0
15425        } else if show_git_gutter && show_line_numbers {
15426            em_width * 2.0
15427        } else if show_git_gutter || show_line_numbers {
15428            em_width
15429        } else {
15430            px(0.)
15431        };
15432
15433        let right_padding = if gutter_settings.folds && show_line_numbers {
15434            em_width * 4.0
15435        } else if gutter_settings.folds {
15436            em_width * 3.0
15437        } else if show_line_numbers {
15438            em_width
15439        } else {
15440            px(0.)
15441        };
15442
15443        Some(GutterDimensions {
15444            left_padding,
15445            right_padding,
15446            width: line_gutter_width + left_padding + right_padding,
15447            margin: -descent,
15448            git_blame_entries_width,
15449        })
15450    }
15451
15452    pub fn render_crease_toggle(
15453        &self,
15454        buffer_row: MultiBufferRow,
15455        row_contains_cursor: bool,
15456        editor: Entity<Editor>,
15457        window: &mut Window,
15458        cx: &mut App,
15459    ) -> Option<AnyElement> {
15460        let folded = self.is_line_folded(buffer_row);
15461        let mut is_foldable = false;
15462
15463        if let Some(crease) = self
15464            .crease_snapshot
15465            .query_row(buffer_row, &self.buffer_snapshot)
15466        {
15467            is_foldable = true;
15468            match crease {
15469                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15470                    if let Some(render_toggle) = render_toggle {
15471                        let toggle_callback =
15472                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15473                                if folded {
15474                                    editor.update(cx, |editor, cx| {
15475                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15476                                    });
15477                                } else {
15478                                    editor.update(cx, |editor, cx| {
15479                                        editor.unfold_at(
15480                                            &crate::UnfoldAt { buffer_row },
15481                                            window,
15482                                            cx,
15483                                        )
15484                                    });
15485                                }
15486                            });
15487                        return Some((render_toggle)(
15488                            buffer_row,
15489                            folded,
15490                            toggle_callback,
15491                            window,
15492                            cx,
15493                        ));
15494                    }
15495                }
15496            }
15497        }
15498
15499        is_foldable |= self.starts_indent(buffer_row);
15500
15501        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15502            Some(
15503                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15504                    .toggle_state(folded)
15505                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15506                        if folded {
15507                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15508                        } else {
15509                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15510                        }
15511                    }))
15512                    .into_any_element(),
15513            )
15514        } else {
15515            None
15516        }
15517    }
15518
15519    pub fn render_crease_trailer(
15520        &self,
15521        buffer_row: MultiBufferRow,
15522        window: &mut Window,
15523        cx: &mut App,
15524    ) -> Option<AnyElement> {
15525        let folded = self.is_line_folded(buffer_row);
15526        if let Crease::Inline { render_trailer, .. } = self
15527            .crease_snapshot
15528            .query_row(buffer_row, &self.buffer_snapshot)?
15529        {
15530            let render_trailer = render_trailer.as_ref()?;
15531            Some(render_trailer(buffer_row, folded, window, cx))
15532        } else {
15533            None
15534        }
15535    }
15536}
15537
15538impl Deref for EditorSnapshot {
15539    type Target = DisplaySnapshot;
15540
15541    fn deref(&self) -> &Self::Target {
15542        &self.display_snapshot
15543    }
15544}
15545
15546#[derive(Clone, Debug, PartialEq, Eq)]
15547pub enum EditorEvent {
15548    InputIgnored {
15549        text: Arc<str>,
15550    },
15551    InputHandled {
15552        utf16_range_to_replace: Option<Range<isize>>,
15553        text: Arc<str>,
15554    },
15555    ExcerptsAdded {
15556        buffer: Entity<Buffer>,
15557        predecessor: ExcerptId,
15558        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15559    },
15560    ExcerptsRemoved {
15561        ids: Vec<ExcerptId>,
15562    },
15563    BufferFoldToggled {
15564        ids: Vec<ExcerptId>,
15565        folded: bool,
15566    },
15567    ExcerptsEdited {
15568        ids: Vec<ExcerptId>,
15569    },
15570    ExcerptsExpanded {
15571        ids: Vec<ExcerptId>,
15572    },
15573    BufferEdited,
15574    Edited {
15575        transaction_id: clock::Lamport,
15576    },
15577    Reparsed(BufferId),
15578    Focused,
15579    FocusedIn,
15580    Blurred,
15581    DirtyChanged,
15582    Saved,
15583    TitleChanged,
15584    DiffBaseChanged,
15585    SelectionsChanged {
15586        local: bool,
15587    },
15588    ScrollPositionChanged {
15589        local: bool,
15590        autoscroll: bool,
15591    },
15592    Closed,
15593    TransactionUndone {
15594        transaction_id: clock::Lamport,
15595    },
15596    TransactionBegun {
15597        transaction_id: clock::Lamport,
15598    },
15599    Reloaded,
15600    CursorShapeChanged,
15601}
15602
15603impl EventEmitter<EditorEvent> for Editor {}
15604
15605impl Focusable for Editor {
15606    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15607        self.focus_handle.clone()
15608    }
15609}
15610
15611impl Render for Editor {
15612    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15613        let settings = ThemeSettings::get_global(cx);
15614
15615        let mut text_style = match self.mode {
15616            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15617                color: cx.theme().colors().editor_foreground,
15618                font_family: settings.ui_font.family.clone(),
15619                font_features: settings.ui_font.features.clone(),
15620                font_fallbacks: settings.ui_font.fallbacks.clone(),
15621                font_size: rems(0.875).into(),
15622                font_weight: settings.ui_font.weight,
15623                line_height: relative(settings.buffer_line_height.value()),
15624                ..Default::default()
15625            },
15626            EditorMode::Full => TextStyle {
15627                color: cx.theme().colors().editor_foreground,
15628                font_family: settings.buffer_font.family.clone(),
15629                font_features: settings.buffer_font.features.clone(),
15630                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15631                font_size: settings.buffer_font_size().into(),
15632                font_weight: settings.buffer_font.weight,
15633                line_height: relative(settings.buffer_line_height.value()),
15634                ..Default::default()
15635            },
15636        };
15637        if let Some(text_style_refinement) = &self.text_style_refinement {
15638            text_style.refine(text_style_refinement)
15639        }
15640
15641        let background = match self.mode {
15642            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15643            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15644            EditorMode::Full => cx.theme().colors().editor_background,
15645        };
15646
15647        EditorElement::new(
15648            &cx.entity(),
15649            EditorStyle {
15650                background,
15651                local_player: cx.theme().players().local(),
15652                text: text_style,
15653                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15654                syntax: cx.theme().syntax().clone(),
15655                status: cx.theme().status().clone(),
15656                inlay_hints_style: make_inlay_hints_style(cx),
15657                inline_completion_styles: make_suggestion_styles(cx),
15658                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15659            },
15660        )
15661    }
15662}
15663
15664impl EntityInputHandler for Editor {
15665    fn text_for_range(
15666        &mut self,
15667        range_utf16: Range<usize>,
15668        adjusted_range: &mut Option<Range<usize>>,
15669        _: &mut Window,
15670        cx: &mut Context<Self>,
15671    ) -> Option<String> {
15672        let snapshot = self.buffer.read(cx).read(cx);
15673        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15674        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15675        if (start.0..end.0) != range_utf16 {
15676            adjusted_range.replace(start.0..end.0);
15677        }
15678        Some(snapshot.text_for_range(start..end).collect())
15679    }
15680
15681    fn selected_text_range(
15682        &mut self,
15683        ignore_disabled_input: bool,
15684        _: &mut Window,
15685        cx: &mut Context<Self>,
15686    ) -> Option<UTF16Selection> {
15687        // Prevent the IME menu from appearing when holding down an alphabetic key
15688        // while input is disabled.
15689        if !ignore_disabled_input && !self.input_enabled {
15690            return None;
15691        }
15692
15693        let selection = self.selections.newest::<OffsetUtf16>(cx);
15694        let range = selection.range();
15695
15696        Some(UTF16Selection {
15697            range: range.start.0..range.end.0,
15698            reversed: selection.reversed,
15699        })
15700    }
15701
15702    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15703        let snapshot = self.buffer.read(cx).read(cx);
15704        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15705        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15706    }
15707
15708    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15709        self.clear_highlights::<InputComposition>(cx);
15710        self.ime_transaction.take();
15711    }
15712
15713    fn replace_text_in_range(
15714        &mut self,
15715        range_utf16: Option<Range<usize>>,
15716        text: &str,
15717        window: &mut Window,
15718        cx: &mut Context<Self>,
15719    ) {
15720        if !self.input_enabled {
15721            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15722            return;
15723        }
15724
15725        self.transact(window, cx, |this, window, cx| {
15726            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15727                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15728                Some(this.selection_replacement_ranges(range_utf16, cx))
15729            } else {
15730                this.marked_text_ranges(cx)
15731            };
15732
15733            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15734                let newest_selection_id = this.selections.newest_anchor().id;
15735                this.selections
15736                    .all::<OffsetUtf16>(cx)
15737                    .iter()
15738                    .zip(ranges_to_replace.iter())
15739                    .find_map(|(selection, range)| {
15740                        if selection.id == newest_selection_id {
15741                            Some(
15742                                (range.start.0 as isize - selection.head().0 as isize)
15743                                    ..(range.end.0 as isize - selection.head().0 as isize),
15744                            )
15745                        } else {
15746                            None
15747                        }
15748                    })
15749            });
15750
15751            cx.emit(EditorEvent::InputHandled {
15752                utf16_range_to_replace: range_to_replace,
15753                text: text.into(),
15754            });
15755
15756            if let Some(new_selected_ranges) = new_selected_ranges {
15757                this.change_selections(None, window, cx, |selections| {
15758                    selections.select_ranges(new_selected_ranges)
15759                });
15760                this.backspace(&Default::default(), window, cx);
15761            }
15762
15763            this.handle_input(text, window, cx);
15764        });
15765
15766        if let Some(transaction) = self.ime_transaction {
15767            self.buffer.update(cx, |buffer, cx| {
15768                buffer.group_until_transaction(transaction, cx);
15769            });
15770        }
15771
15772        self.unmark_text(window, cx);
15773    }
15774
15775    fn replace_and_mark_text_in_range(
15776        &mut self,
15777        range_utf16: Option<Range<usize>>,
15778        text: &str,
15779        new_selected_range_utf16: Option<Range<usize>>,
15780        window: &mut Window,
15781        cx: &mut Context<Self>,
15782    ) {
15783        if !self.input_enabled {
15784            return;
15785        }
15786
15787        let transaction = self.transact(window, cx, |this, window, cx| {
15788            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15789                let snapshot = this.buffer.read(cx).read(cx);
15790                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15791                    for marked_range in &mut marked_ranges {
15792                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15793                        marked_range.start.0 += relative_range_utf16.start;
15794                        marked_range.start =
15795                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15796                        marked_range.end =
15797                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15798                    }
15799                }
15800                Some(marked_ranges)
15801            } else if let Some(range_utf16) = range_utf16 {
15802                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15803                Some(this.selection_replacement_ranges(range_utf16, cx))
15804            } else {
15805                None
15806            };
15807
15808            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15809                let newest_selection_id = this.selections.newest_anchor().id;
15810                this.selections
15811                    .all::<OffsetUtf16>(cx)
15812                    .iter()
15813                    .zip(ranges_to_replace.iter())
15814                    .find_map(|(selection, range)| {
15815                        if selection.id == newest_selection_id {
15816                            Some(
15817                                (range.start.0 as isize - selection.head().0 as isize)
15818                                    ..(range.end.0 as isize - selection.head().0 as isize),
15819                            )
15820                        } else {
15821                            None
15822                        }
15823                    })
15824            });
15825
15826            cx.emit(EditorEvent::InputHandled {
15827                utf16_range_to_replace: range_to_replace,
15828                text: text.into(),
15829            });
15830
15831            if let Some(ranges) = ranges_to_replace {
15832                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15833            }
15834
15835            let marked_ranges = {
15836                let snapshot = this.buffer.read(cx).read(cx);
15837                this.selections
15838                    .disjoint_anchors()
15839                    .iter()
15840                    .map(|selection| {
15841                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15842                    })
15843                    .collect::<Vec<_>>()
15844            };
15845
15846            if text.is_empty() {
15847                this.unmark_text(window, cx);
15848            } else {
15849                this.highlight_text::<InputComposition>(
15850                    marked_ranges.clone(),
15851                    HighlightStyle {
15852                        underline: Some(UnderlineStyle {
15853                            thickness: px(1.),
15854                            color: None,
15855                            wavy: false,
15856                        }),
15857                        ..Default::default()
15858                    },
15859                    cx,
15860                );
15861            }
15862
15863            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15864            let use_autoclose = this.use_autoclose;
15865            let use_auto_surround = this.use_auto_surround;
15866            this.set_use_autoclose(false);
15867            this.set_use_auto_surround(false);
15868            this.handle_input(text, window, cx);
15869            this.set_use_autoclose(use_autoclose);
15870            this.set_use_auto_surround(use_auto_surround);
15871
15872            if let Some(new_selected_range) = new_selected_range_utf16 {
15873                let snapshot = this.buffer.read(cx).read(cx);
15874                let new_selected_ranges = marked_ranges
15875                    .into_iter()
15876                    .map(|marked_range| {
15877                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15878                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15879                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15880                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15881                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15882                    })
15883                    .collect::<Vec<_>>();
15884
15885                drop(snapshot);
15886                this.change_selections(None, window, cx, |selections| {
15887                    selections.select_ranges(new_selected_ranges)
15888                });
15889            }
15890        });
15891
15892        self.ime_transaction = self.ime_transaction.or(transaction);
15893        if let Some(transaction) = self.ime_transaction {
15894            self.buffer.update(cx, |buffer, cx| {
15895                buffer.group_until_transaction(transaction, cx);
15896            });
15897        }
15898
15899        if self.text_highlights::<InputComposition>(cx).is_none() {
15900            self.ime_transaction.take();
15901        }
15902    }
15903
15904    fn bounds_for_range(
15905        &mut self,
15906        range_utf16: Range<usize>,
15907        element_bounds: gpui::Bounds<Pixels>,
15908        window: &mut Window,
15909        cx: &mut Context<Self>,
15910    ) -> Option<gpui::Bounds<Pixels>> {
15911        let text_layout_details = self.text_layout_details(window);
15912        let gpui::Size {
15913            width: em_width,
15914            height: line_height,
15915        } = self.character_size(window);
15916
15917        let snapshot = self.snapshot(window, cx);
15918        let scroll_position = snapshot.scroll_position();
15919        let scroll_left = scroll_position.x * em_width;
15920
15921        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15922        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15923            + self.gutter_dimensions.width
15924            + self.gutter_dimensions.margin;
15925        let y = line_height * (start.row().as_f32() - scroll_position.y);
15926
15927        Some(Bounds {
15928            origin: element_bounds.origin + point(x, y),
15929            size: size(em_width, line_height),
15930        })
15931    }
15932
15933    fn character_index_for_point(
15934        &mut self,
15935        point: gpui::Point<Pixels>,
15936        _window: &mut Window,
15937        _cx: &mut Context<Self>,
15938    ) -> Option<usize> {
15939        let position_map = self.last_position_map.as_ref()?;
15940        if !position_map.text_hitbox.contains(&point) {
15941            return None;
15942        }
15943        let display_point = position_map.point_for_position(point).previous_valid;
15944        let anchor = position_map
15945            .snapshot
15946            .display_point_to_anchor(display_point, Bias::Left);
15947        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
15948        Some(utf16_offset.0)
15949    }
15950}
15951
15952trait SelectionExt {
15953    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15954    fn spanned_rows(
15955        &self,
15956        include_end_if_at_line_start: bool,
15957        map: &DisplaySnapshot,
15958    ) -> Range<MultiBufferRow>;
15959}
15960
15961impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15962    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15963        let start = self
15964            .start
15965            .to_point(&map.buffer_snapshot)
15966            .to_display_point(map);
15967        let end = self
15968            .end
15969            .to_point(&map.buffer_snapshot)
15970            .to_display_point(map);
15971        if self.reversed {
15972            end..start
15973        } else {
15974            start..end
15975        }
15976    }
15977
15978    fn spanned_rows(
15979        &self,
15980        include_end_if_at_line_start: bool,
15981        map: &DisplaySnapshot,
15982    ) -> Range<MultiBufferRow> {
15983        let start = self.start.to_point(&map.buffer_snapshot);
15984        let mut end = self.end.to_point(&map.buffer_snapshot);
15985        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15986            end.row -= 1;
15987        }
15988
15989        let buffer_start = map.prev_line_boundary(start).0;
15990        let buffer_end = map.next_line_boundary(end).0;
15991        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15992    }
15993}
15994
15995impl<T: InvalidationRegion> InvalidationStack<T> {
15996    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15997    where
15998        S: Clone + ToOffset,
15999    {
16000        while let Some(region) = self.last() {
16001            let all_selections_inside_invalidation_ranges =
16002                if selections.len() == region.ranges().len() {
16003                    selections
16004                        .iter()
16005                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16006                        .all(|(selection, invalidation_range)| {
16007                            let head = selection.head().to_offset(buffer);
16008                            invalidation_range.start <= head && invalidation_range.end >= head
16009                        })
16010                } else {
16011                    false
16012                };
16013
16014            if all_selections_inside_invalidation_ranges {
16015                break;
16016            } else {
16017                self.pop();
16018            }
16019        }
16020    }
16021}
16022
16023impl<T> Default for InvalidationStack<T> {
16024    fn default() -> Self {
16025        Self(Default::default())
16026    }
16027}
16028
16029impl<T> Deref for InvalidationStack<T> {
16030    type Target = Vec<T>;
16031
16032    fn deref(&self) -> &Self::Target {
16033        &self.0
16034    }
16035}
16036
16037impl<T> DerefMut for InvalidationStack<T> {
16038    fn deref_mut(&mut self) -> &mut Self::Target {
16039        &mut self.0
16040    }
16041}
16042
16043impl InvalidationRegion for SnippetState {
16044    fn ranges(&self) -> &[Range<Anchor>] {
16045        &self.ranges[self.active_index]
16046    }
16047}
16048
16049pub fn diagnostic_block_renderer(
16050    diagnostic: Diagnostic,
16051    max_message_rows: Option<u8>,
16052    allow_closing: bool,
16053    _is_valid: bool,
16054) -> RenderBlock {
16055    let (text_without_backticks, code_ranges) =
16056        highlight_diagnostic_message(&diagnostic, max_message_rows);
16057
16058    Arc::new(move |cx: &mut BlockContext| {
16059        let group_id: SharedString = cx.block_id.to_string().into();
16060
16061        let mut text_style = cx.window.text_style().clone();
16062        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16063        let theme_settings = ThemeSettings::get_global(cx);
16064        text_style.font_family = theme_settings.buffer_font.family.clone();
16065        text_style.font_style = theme_settings.buffer_font.style;
16066        text_style.font_features = theme_settings.buffer_font.features.clone();
16067        text_style.font_weight = theme_settings.buffer_font.weight;
16068
16069        let multi_line_diagnostic = diagnostic.message.contains('\n');
16070
16071        let buttons = |diagnostic: &Diagnostic| {
16072            if multi_line_diagnostic {
16073                v_flex()
16074            } else {
16075                h_flex()
16076            }
16077            .when(allow_closing, |div| {
16078                div.children(diagnostic.is_primary.then(|| {
16079                    IconButton::new("close-block", IconName::XCircle)
16080                        .icon_color(Color::Muted)
16081                        .size(ButtonSize::Compact)
16082                        .style(ButtonStyle::Transparent)
16083                        .visible_on_hover(group_id.clone())
16084                        .on_click(move |_click, window, cx| {
16085                            window.dispatch_action(Box::new(Cancel), cx)
16086                        })
16087                        .tooltip(|window, cx| {
16088                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16089                        })
16090                }))
16091            })
16092            .child(
16093                IconButton::new("copy-block", IconName::Copy)
16094                    .icon_color(Color::Muted)
16095                    .size(ButtonSize::Compact)
16096                    .style(ButtonStyle::Transparent)
16097                    .visible_on_hover(group_id.clone())
16098                    .on_click({
16099                        let message = diagnostic.message.clone();
16100                        move |_click, _, cx| {
16101                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16102                        }
16103                    })
16104                    .tooltip(Tooltip::text("Copy diagnostic message")),
16105            )
16106        };
16107
16108        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16109            AvailableSpace::min_size(),
16110            cx.window,
16111            cx.app,
16112        );
16113
16114        h_flex()
16115            .id(cx.block_id)
16116            .group(group_id.clone())
16117            .relative()
16118            .size_full()
16119            .block_mouse_down()
16120            .pl(cx.gutter_dimensions.width)
16121            .w(cx.max_width - cx.gutter_dimensions.full_width())
16122            .child(
16123                div()
16124                    .flex()
16125                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16126                    .flex_shrink(),
16127            )
16128            .child(buttons(&diagnostic))
16129            .child(div().flex().flex_shrink_0().child(
16130                StyledText::new(text_without_backticks.clone()).with_highlights(
16131                    &text_style,
16132                    code_ranges.iter().map(|range| {
16133                        (
16134                            range.clone(),
16135                            HighlightStyle {
16136                                font_weight: Some(FontWeight::BOLD),
16137                                ..Default::default()
16138                            },
16139                        )
16140                    }),
16141                ),
16142            ))
16143            .into_any_element()
16144    })
16145}
16146
16147fn inline_completion_edit_text(
16148    current_snapshot: &BufferSnapshot,
16149    edits: &[(Range<Anchor>, String)],
16150    edit_preview: &EditPreview,
16151    include_deletions: bool,
16152    cx: &App,
16153) -> HighlightedText {
16154    let edits = edits
16155        .iter()
16156        .map(|(anchor, text)| {
16157            (
16158                anchor.start.text_anchor..anchor.end.text_anchor,
16159                text.clone(),
16160            )
16161        })
16162        .collect::<Vec<_>>();
16163
16164    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16165}
16166
16167pub fn highlight_diagnostic_message(
16168    diagnostic: &Diagnostic,
16169    mut max_message_rows: Option<u8>,
16170) -> (SharedString, Vec<Range<usize>>) {
16171    let mut text_without_backticks = String::new();
16172    let mut code_ranges = Vec::new();
16173
16174    if let Some(source) = &diagnostic.source {
16175        text_without_backticks.push_str(source);
16176        code_ranges.push(0..source.len());
16177        text_without_backticks.push_str(": ");
16178    }
16179
16180    let mut prev_offset = 0;
16181    let mut in_code_block = false;
16182    let has_row_limit = max_message_rows.is_some();
16183    let mut newline_indices = diagnostic
16184        .message
16185        .match_indices('\n')
16186        .filter(|_| has_row_limit)
16187        .map(|(ix, _)| ix)
16188        .fuse()
16189        .peekable();
16190
16191    for (quote_ix, _) in diagnostic
16192        .message
16193        .match_indices('`')
16194        .chain([(diagnostic.message.len(), "")])
16195    {
16196        let mut first_newline_ix = None;
16197        let mut last_newline_ix = None;
16198        while let Some(newline_ix) = newline_indices.peek() {
16199            if *newline_ix < quote_ix {
16200                if first_newline_ix.is_none() {
16201                    first_newline_ix = Some(*newline_ix);
16202                }
16203                last_newline_ix = Some(*newline_ix);
16204
16205                if let Some(rows_left) = &mut max_message_rows {
16206                    if *rows_left == 0 {
16207                        break;
16208                    } else {
16209                        *rows_left -= 1;
16210                    }
16211                }
16212                let _ = newline_indices.next();
16213            } else {
16214                break;
16215            }
16216        }
16217        let prev_len = text_without_backticks.len();
16218        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16219        text_without_backticks.push_str(new_text);
16220        if in_code_block {
16221            code_ranges.push(prev_len..text_without_backticks.len());
16222        }
16223        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16224        in_code_block = !in_code_block;
16225        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16226            text_without_backticks.push_str("...");
16227            break;
16228        }
16229    }
16230
16231    (text_without_backticks.into(), code_ranges)
16232}
16233
16234fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16235    match severity {
16236        DiagnosticSeverity::ERROR => colors.error,
16237        DiagnosticSeverity::WARNING => colors.warning,
16238        DiagnosticSeverity::INFORMATION => colors.info,
16239        DiagnosticSeverity::HINT => colors.info,
16240        _ => colors.ignored,
16241    }
16242}
16243
16244pub fn styled_runs_for_code_label<'a>(
16245    label: &'a CodeLabel,
16246    syntax_theme: &'a theme::SyntaxTheme,
16247) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16248    let fade_out = HighlightStyle {
16249        fade_out: Some(0.35),
16250        ..Default::default()
16251    };
16252
16253    let mut prev_end = label.filter_range.end;
16254    label
16255        .runs
16256        .iter()
16257        .enumerate()
16258        .flat_map(move |(ix, (range, highlight_id))| {
16259            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16260                style
16261            } else {
16262                return Default::default();
16263            };
16264            let mut muted_style = style;
16265            muted_style.highlight(fade_out);
16266
16267            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16268            if range.start >= label.filter_range.end {
16269                if range.start > prev_end {
16270                    runs.push((prev_end..range.start, fade_out));
16271                }
16272                runs.push((range.clone(), muted_style));
16273            } else if range.end <= label.filter_range.end {
16274                runs.push((range.clone(), style));
16275            } else {
16276                runs.push((range.start..label.filter_range.end, style));
16277                runs.push((label.filter_range.end..range.end, muted_style));
16278            }
16279            prev_end = cmp::max(prev_end, range.end);
16280
16281            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16282                runs.push((prev_end..label.text.len(), fade_out));
16283            }
16284
16285            runs
16286        })
16287}
16288
16289pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16290    let mut prev_index = 0;
16291    let mut prev_codepoint: Option<char> = None;
16292    text.char_indices()
16293        .chain([(text.len(), '\0')])
16294        .filter_map(move |(index, codepoint)| {
16295            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16296            let is_boundary = index == text.len()
16297                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16298                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16299            if is_boundary {
16300                let chunk = &text[prev_index..index];
16301                prev_index = index;
16302                Some(chunk)
16303            } else {
16304                None
16305            }
16306        })
16307}
16308
16309pub trait RangeToAnchorExt: Sized {
16310    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16311
16312    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16313        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16314        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16315    }
16316}
16317
16318impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16319    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16320        let start_offset = self.start.to_offset(snapshot);
16321        let end_offset = self.end.to_offset(snapshot);
16322        if start_offset == end_offset {
16323            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16324        } else {
16325            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16326        }
16327    }
16328}
16329
16330pub trait RowExt {
16331    fn as_f32(&self) -> f32;
16332
16333    fn next_row(&self) -> Self;
16334
16335    fn previous_row(&self) -> Self;
16336
16337    fn minus(&self, other: Self) -> u32;
16338}
16339
16340impl RowExt for DisplayRow {
16341    fn as_f32(&self) -> f32 {
16342        self.0 as f32
16343    }
16344
16345    fn next_row(&self) -> Self {
16346        Self(self.0 + 1)
16347    }
16348
16349    fn previous_row(&self) -> Self {
16350        Self(self.0.saturating_sub(1))
16351    }
16352
16353    fn minus(&self, other: Self) -> u32 {
16354        self.0 - other.0
16355    }
16356}
16357
16358impl RowExt for MultiBufferRow {
16359    fn as_f32(&self) -> f32 {
16360        self.0 as f32
16361    }
16362
16363    fn next_row(&self) -> Self {
16364        Self(self.0 + 1)
16365    }
16366
16367    fn previous_row(&self) -> Self {
16368        Self(self.0.saturating_sub(1))
16369    }
16370
16371    fn minus(&self, other: Self) -> u32 {
16372        self.0 - other.0
16373    }
16374}
16375
16376trait RowRangeExt {
16377    type Row;
16378
16379    fn len(&self) -> usize;
16380
16381    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16382}
16383
16384impl RowRangeExt for Range<MultiBufferRow> {
16385    type Row = MultiBufferRow;
16386
16387    fn len(&self) -> usize {
16388        (self.end.0 - self.start.0) as usize
16389    }
16390
16391    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16392        (self.start.0..self.end.0).map(MultiBufferRow)
16393    }
16394}
16395
16396impl RowRangeExt for Range<DisplayRow> {
16397    type Row = DisplayRow;
16398
16399    fn len(&self) -> usize {
16400        (self.end.0 - self.start.0) as usize
16401    }
16402
16403    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16404        (self.start.0..self.end.0).map(DisplayRow)
16405    }
16406}
16407
16408/// If select range has more than one line, we
16409/// just point the cursor to range.start.
16410fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16411    if range.start.row == range.end.row {
16412        range
16413    } else {
16414        range.start..range.start
16415    }
16416}
16417pub struct KillRing(ClipboardItem);
16418impl Global for KillRing {}
16419
16420const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16421
16422fn all_edits_insertions_or_deletions(
16423    edits: &Vec<(Range<Anchor>, String)>,
16424    snapshot: &MultiBufferSnapshot,
16425) -> bool {
16426    let mut all_insertions = true;
16427    let mut all_deletions = true;
16428
16429    for (range, new_text) in edits.iter() {
16430        let range_is_empty = range.to_offset(&snapshot).is_empty();
16431        let text_is_empty = new_text.is_empty();
16432
16433        if range_is_empty != text_is_empty {
16434            if range_is_empty {
16435                all_deletions = false;
16436            } else {
16437                all_insertions = false;
16438            }
16439        } else {
16440            return false;
16441        }
16442
16443        if !all_insertions && !all_deletions {
16444            return false;
16445        }
16446    }
16447    all_insertions || all_deletions
16448}