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_uncommitted_changes_for_buffer(
 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        start_row: DisplayRow,
 5425        line_layouts: &[LineWithInvisibles],
 5426        style: &EditorStyle,
 5427        accept_keystroke: &gpui::Keystroke,
 5428        window: &Window,
 5429        cx: &mut Context<Editor>,
 5430    ) -> Option<AnyElement> {
 5431        let provider = self.inline_completion_provider.as_ref()?;
 5432
 5433        if provider.provider.needs_terms_acceptance(cx) {
 5434            return Some(
 5435                h_flex()
 5436                    .h(self.edit_prediction_cursor_popover_height())
 5437                    .min_w(min_width)
 5438                    .flex_1()
 5439                    .px_2()
 5440                    .gap_3()
 5441                    .elevation_2(cx)
 5442                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5443                    .id("accept-terms")
 5444                    .cursor_pointer()
 5445                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5446                    .on_click(cx.listener(|this, _event, window, cx| {
 5447                        cx.stop_propagation();
 5448                        this.toggle_zed_predict_onboarding(window, cx)
 5449                    }))
 5450                    .child(
 5451                        h_flex()
 5452                            .w_full()
 5453                            .gap_2()
 5454                            .child(Icon::new(IconName::ZedPredict))
 5455                            .child(Label::new("Accept Terms of Service"))
 5456                            .child(div().w_full())
 5457                            .child(Icon::new(IconName::ArrowUpRight))
 5458                            .into_any_element(),
 5459                    )
 5460                    .into_any(),
 5461            );
 5462        }
 5463
 5464        let is_refreshing = provider.provider.is_refreshing(cx);
 5465
 5466        fn pending_completion_container() -> Div {
 5467            h_flex()
 5468                .flex_1()
 5469                .gap_3()
 5470                .child(Icon::new(IconName::ZedPredict))
 5471        }
 5472
 5473        let completion = match &self.active_inline_completion {
 5474            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5475                completion,
 5476                cursor_point,
 5477                start_row,
 5478                line_layouts,
 5479                style,
 5480                cx,
 5481            )?,
 5482
 5483            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5484                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5485                    stale_completion,
 5486                    cursor_point,
 5487                    start_row,
 5488                    line_layouts,
 5489                    style,
 5490                    cx,
 5491                )?,
 5492
 5493                None => {
 5494                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5495                }
 5496            },
 5497
 5498            None => pending_completion_container().child(Label::new("No Prediction")),
 5499        };
 5500
 5501        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5502        let completion = completion.font(buffer_font.clone());
 5503
 5504        let completion = if is_refreshing {
 5505            completion
 5506                .with_animation(
 5507                    "loading-completion",
 5508                    Animation::new(Duration::from_secs(2))
 5509                        .repeat()
 5510                        .with_easing(pulsating_between(0.4, 0.8)),
 5511                    |label, delta| label.opacity(delta),
 5512                )
 5513                .into_any_element()
 5514        } else {
 5515            completion.into_any_element()
 5516        };
 5517
 5518        let has_completion = self.active_inline_completion.is_some();
 5519
 5520        let is_move = self
 5521            .active_inline_completion
 5522            .as_ref()
 5523            .map_or(false, |c| c.is_move());
 5524
 5525        Some(
 5526            h_flex()
 5527                .h(self.edit_prediction_cursor_popover_height())
 5528                .min_w(min_width)
 5529                .max_w(max_width)
 5530                .flex_1()
 5531                .px_2()
 5532                .gap_3()
 5533                .elevation_2(cx)
 5534                .child(completion)
 5535                .child(
 5536                    h_flex()
 5537                        .border_l_1()
 5538                        .border_color(cx.theme().colors().border_variant)
 5539                        .pl_2()
 5540                        .child(
 5541                            h_flex()
 5542                                .font(buffer_font.clone())
 5543                                .p_1()
 5544                                .rounded_sm()
 5545                                .children(ui::render_modifiers(
 5546                                    &accept_keystroke.modifiers,
 5547                                    PlatformStyle::platform(),
 5548                                    if window.modifiers() == accept_keystroke.modifiers {
 5549                                        Some(Color::Accent)
 5550                                    } else {
 5551                                        None
 5552                                    },
 5553                                    !is_move,
 5554                                )),
 5555                        )
 5556                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5557                        .child(if is_move {
 5558                            div()
 5559                                .child(ui::Key::new(&accept_keystroke.key, None))
 5560                                .font(buffer_font.clone())
 5561                                .into_any()
 5562                        } else {
 5563                            Label::new("Preview").color(Color::Muted).into_any_element()
 5564                        }),
 5565                )
 5566                .into_any(),
 5567        )
 5568    }
 5569
 5570    fn render_edit_prediction_cursor_popover_preview(
 5571        &self,
 5572        completion: &InlineCompletionState,
 5573        cursor_point: Point,
 5574        start_row: DisplayRow,
 5575        line_layouts: &[LineWithInvisibles],
 5576        style: &EditorStyle,
 5577        cx: &mut Context<Editor>,
 5578    ) -> Option<Div> {
 5579        use text::ToPoint as _;
 5580
 5581        fn render_relative_row_jump(
 5582            prefix: impl Into<String>,
 5583            current_row: u32,
 5584            target_row: u32,
 5585        ) -> Div {
 5586            let (row_diff, arrow) = if target_row < current_row {
 5587                (current_row - target_row, IconName::ArrowUp)
 5588            } else {
 5589                (target_row - current_row, IconName::ArrowDown)
 5590            };
 5591
 5592            h_flex()
 5593                .child(
 5594                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5595                        .color(Color::Muted)
 5596                        .size(LabelSize::Small),
 5597                )
 5598                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5599        }
 5600
 5601        match &completion.completion {
 5602            InlineCompletion::Edit {
 5603                edits,
 5604                edit_preview,
 5605                snapshot,
 5606                display_mode: _,
 5607            } => {
 5608                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5609
 5610                let highlighted_edits = crate::inline_completion_edit_text(
 5611                    &snapshot,
 5612                    &edits,
 5613                    edit_preview.as_ref()?,
 5614                    true,
 5615                    cx,
 5616                );
 5617
 5618                let len_total = highlighted_edits.text.len();
 5619                let first_line = &highlighted_edits.text
 5620                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5621                let first_line_len = first_line.len();
 5622
 5623                let first_highlight_start = highlighted_edits
 5624                    .highlights
 5625                    .first()
 5626                    .map_or(0, |(range, _)| range.start);
 5627                let drop_prefix_len = first_line
 5628                    .char_indices()
 5629                    .find(|(_, c)| !c.is_whitespace())
 5630                    .map_or(first_highlight_start, |(ix, _)| {
 5631                        ix.min(first_highlight_start)
 5632                    });
 5633
 5634                let preview_text = &first_line[drop_prefix_len..];
 5635                let preview_len = preview_text.len();
 5636                let highlights = highlighted_edits
 5637                    .highlights
 5638                    .into_iter()
 5639                    .take_until(|(range, _)| range.start > first_line_len)
 5640                    .map(|(range, style)| {
 5641                        (
 5642                            range.start - drop_prefix_len
 5643                                ..(range.end - drop_prefix_len).min(preview_len),
 5644                            style,
 5645                        )
 5646                    });
 5647
 5648                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5649                    .with_highlights(&style.text, highlights);
 5650
 5651                let preview = h_flex()
 5652                    .gap_1()
 5653                    .child(styled_text)
 5654                    .when(len_total > first_line_len, |parent| parent.child(""));
 5655
 5656                let left = if first_edit_row != cursor_point.row {
 5657                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5658                        .into_any_element()
 5659                } else {
 5660                    Icon::new(IconName::ZedPredict).into_any_element()
 5661                };
 5662
 5663                Some(h_flex().flex_1().gap_3().child(left).child(preview))
 5664            }
 5665
 5666            InlineCompletion::Move {
 5667                target,
 5668                range_around_target,
 5669                snapshot,
 5670            } => {
 5671                let highlighted_text = snapshot.highlighted_text_for_range(
 5672                    range_around_target.clone(),
 5673                    None,
 5674                    &style.syntax,
 5675                );
 5676                let cursor_color = self.current_user_player_color(cx).cursor;
 5677
 5678                let start_point = range_around_target.start.to_point(&snapshot);
 5679                let end_point = range_around_target.end.to_point(&snapshot);
 5680                let target_point = target.text_anchor.to_point(&snapshot);
 5681
 5682                let cursor_relative_position = line_layouts
 5683                    .get(start_point.row.saturating_sub(start_row.0) as usize)
 5684                    .map(|line| {
 5685                        let start_column_x = line.x_for_index(start_point.column as usize);
 5686                        let target_column_x = line.x_for_index(target_point.column as usize);
 5687                        target_column_x - start_column_x
 5688                    });
 5689
 5690                let fade_before = start_point.column > 0;
 5691                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5692
 5693                let background = cx.theme().colors().elevated_surface_background;
 5694
 5695                Some(
 5696                    h_flex()
 5697                        .gap_3()
 5698                        .flex_1()
 5699                        .child(render_relative_row_jump(
 5700                            "Jump ",
 5701                            cursor_point.row,
 5702                            target.text_anchor.to_point(&snapshot).row,
 5703                        ))
 5704                        .when(!highlighted_text.text.is_empty(), |parent| {
 5705                            parent.child(
 5706                                h_flex()
 5707                                    .relative()
 5708                                    .child(highlighted_text.to_styled_text(&style.text))
 5709                                    .when(fade_before, |parent| {
 5710                                        parent.child(
 5711                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5712                                                linear_gradient(
 5713                                                    90.,
 5714                                                    linear_color_stop(background, 0.),
 5715                                                    linear_color_stop(background.opacity(0.), 1.),
 5716                                                ),
 5717                                            ),
 5718                                        )
 5719                                    })
 5720                                    .when(fade_after, |parent| {
 5721                                        parent.child(
 5722                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5723                                                linear_gradient(
 5724                                                    -90.,
 5725                                                    linear_color_stop(background, 0.),
 5726                                                    linear_color_stop(background.opacity(0.), 1.),
 5727                                                ),
 5728                                            ),
 5729                                        )
 5730                                    })
 5731                                    .when_some(cursor_relative_position, |parent, position| {
 5732                                        parent.child(
 5733                                            div()
 5734                                                .w(px(2.))
 5735                                                .h_full()
 5736                                                .bg(cursor_color)
 5737                                                .absolute()
 5738                                                .top_0()
 5739                                                .left(position),
 5740                                        )
 5741                                    }),
 5742                            )
 5743                        }),
 5744                )
 5745            }
 5746        }
 5747    }
 5748
 5749    fn render_context_menu(
 5750        &self,
 5751        style: &EditorStyle,
 5752        max_height_in_lines: u32,
 5753        y_flipped: bool,
 5754        window: &mut Window,
 5755        cx: &mut Context<Editor>,
 5756    ) -> Option<AnyElement> {
 5757        let menu = self.context_menu.borrow();
 5758        let menu = menu.as_ref()?;
 5759        if !menu.visible() {
 5760            return None;
 5761        };
 5762        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5763    }
 5764
 5765    fn render_context_menu_aside(
 5766        &self,
 5767        style: &EditorStyle,
 5768        max_size: Size<Pixels>,
 5769        cx: &mut Context<Editor>,
 5770    ) -> Option<AnyElement> {
 5771        self.context_menu.borrow().as_ref().and_then(|menu| {
 5772            if menu.visible() {
 5773                menu.render_aside(
 5774                    style,
 5775                    max_size,
 5776                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5777                    cx,
 5778                )
 5779            } else {
 5780                None
 5781            }
 5782        })
 5783    }
 5784
 5785    fn hide_context_menu(
 5786        &mut self,
 5787        window: &mut Window,
 5788        cx: &mut Context<Self>,
 5789    ) -> Option<CodeContextMenu> {
 5790        cx.notify();
 5791        self.completion_tasks.clear();
 5792        let context_menu = self.context_menu.borrow_mut().take();
 5793        self.stale_inline_completion_in_menu.take();
 5794        if context_menu.is_some() {
 5795            self.update_visible_inline_completion(window, cx);
 5796        }
 5797        context_menu
 5798    }
 5799
 5800    fn show_snippet_choices(
 5801        &mut self,
 5802        choices: &Vec<String>,
 5803        selection: Range<Anchor>,
 5804        cx: &mut Context<Self>,
 5805    ) {
 5806        if selection.start.buffer_id.is_none() {
 5807            return;
 5808        }
 5809        let buffer_id = selection.start.buffer_id.unwrap();
 5810        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5811        let id = post_inc(&mut self.next_completion_id);
 5812
 5813        if let Some(buffer) = buffer {
 5814            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5815                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5816            ));
 5817        }
 5818    }
 5819
 5820    pub fn insert_snippet(
 5821        &mut self,
 5822        insertion_ranges: &[Range<usize>],
 5823        snippet: Snippet,
 5824        window: &mut Window,
 5825        cx: &mut Context<Self>,
 5826    ) -> Result<()> {
 5827        struct Tabstop<T> {
 5828            is_end_tabstop: bool,
 5829            ranges: Vec<Range<T>>,
 5830            choices: Option<Vec<String>>,
 5831        }
 5832
 5833        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5834            let snippet_text: Arc<str> = snippet.text.clone().into();
 5835            buffer.edit(
 5836                insertion_ranges
 5837                    .iter()
 5838                    .cloned()
 5839                    .map(|range| (range, snippet_text.clone())),
 5840                Some(AutoindentMode::EachLine),
 5841                cx,
 5842            );
 5843
 5844            let snapshot = &*buffer.read(cx);
 5845            let snippet = &snippet;
 5846            snippet
 5847                .tabstops
 5848                .iter()
 5849                .map(|tabstop| {
 5850                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5851                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5852                    });
 5853                    let mut tabstop_ranges = tabstop
 5854                        .ranges
 5855                        .iter()
 5856                        .flat_map(|tabstop_range| {
 5857                            let mut delta = 0_isize;
 5858                            insertion_ranges.iter().map(move |insertion_range| {
 5859                                let insertion_start = insertion_range.start as isize + delta;
 5860                                delta +=
 5861                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5862
 5863                                let start = ((insertion_start + tabstop_range.start) as usize)
 5864                                    .min(snapshot.len());
 5865                                let end = ((insertion_start + tabstop_range.end) as usize)
 5866                                    .min(snapshot.len());
 5867                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5868                            })
 5869                        })
 5870                        .collect::<Vec<_>>();
 5871                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5872
 5873                    Tabstop {
 5874                        is_end_tabstop,
 5875                        ranges: tabstop_ranges,
 5876                        choices: tabstop.choices.clone(),
 5877                    }
 5878                })
 5879                .collect::<Vec<_>>()
 5880        });
 5881        if let Some(tabstop) = tabstops.first() {
 5882            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5883                s.select_ranges(tabstop.ranges.iter().cloned());
 5884            });
 5885
 5886            if let Some(choices) = &tabstop.choices {
 5887                if let Some(selection) = tabstop.ranges.first() {
 5888                    self.show_snippet_choices(choices, selection.clone(), cx)
 5889                }
 5890            }
 5891
 5892            // If we're already at the last tabstop and it's at the end of the snippet,
 5893            // we're done, we don't need to keep the state around.
 5894            if !tabstop.is_end_tabstop {
 5895                let choices = tabstops
 5896                    .iter()
 5897                    .map(|tabstop| tabstop.choices.clone())
 5898                    .collect();
 5899
 5900                let ranges = tabstops
 5901                    .into_iter()
 5902                    .map(|tabstop| tabstop.ranges)
 5903                    .collect::<Vec<_>>();
 5904
 5905                self.snippet_stack.push(SnippetState {
 5906                    active_index: 0,
 5907                    ranges,
 5908                    choices,
 5909                });
 5910            }
 5911
 5912            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5913            if self.autoclose_regions.is_empty() {
 5914                let snapshot = self.buffer.read(cx).snapshot(cx);
 5915                for selection in &mut self.selections.all::<Point>(cx) {
 5916                    let selection_head = selection.head();
 5917                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5918                        continue;
 5919                    };
 5920
 5921                    let mut bracket_pair = None;
 5922                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5923                    let prev_chars = snapshot
 5924                        .reversed_chars_at(selection_head)
 5925                        .collect::<String>();
 5926                    for (pair, enabled) in scope.brackets() {
 5927                        if enabled
 5928                            && pair.close
 5929                            && prev_chars.starts_with(pair.start.as_str())
 5930                            && next_chars.starts_with(pair.end.as_str())
 5931                        {
 5932                            bracket_pair = Some(pair.clone());
 5933                            break;
 5934                        }
 5935                    }
 5936                    if let Some(pair) = bracket_pair {
 5937                        let start = snapshot.anchor_after(selection_head);
 5938                        let end = snapshot.anchor_after(selection_head);
 5939                        self.autoclose_regions.push(AutocloseRegion {
 5940                            selection_id: selection.id,
 5941                            range: start..end,
 5942                            pair,
 5943                        });
 5944                    }
 5945                }
 5946            }
 5947        }
 5948        Ok(())
 5949    }
 5950
 5951    pub fn move_to_next_snippet_tabstop(
 5952        &mut self,
 5953        window: &mut Window,
 5954        cx: &mut Context<Self>,
 5955    ) -> bool {
 5956        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5957    }
 5958
 5959    pub fn move_to_prev_snippet_tabstop(
 5960        &mut self,
 5961        window: &mut Window,
 5962        cx: &mut Context<Self>,
 5963    ) -> bool {
 5964        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5965    }
 5966
 5967    pub fn move_to_snippet_tabstop(
 5968        &mut self,
 5969        bias: Bias,
 5970        window: &mut Window,
 5971        cx: &mut Context<Self>,
 5972    ) -> bool {
 5973        if let Some(mut snippet) = self.snippet_stack.pop() {
 5974            match bias {
 5975                Bias::Left => {
 5976                    if snippet.active_index > 0 {
 5977                        snippet.active_index -= 1;
 5978                    } else {
 5979                        self.snippet_stack.push(snippet);
 5980                        return false;
 5981                    }
 5982                }
 5983                Bias::Right => {
 5984                    if snippet.active_index + 1 < snippet.ranges.len() {
 5985                        snippet.active_index += 1;
 5986                    } else {
 5987                        self.snippet_stack.push(snippet);
 5988                        return false;
 5989                    }
 5990                }
 5991            }
 5992            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5993                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5994                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5995                });
 5996
 5997                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5998                    if let Some(selection) = current_ranges.first() {
 5999                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6000                    }
 6001                }
 6002
 6003                // If snippet state is not at the last tabstop, push it back on the stack
 6004                if snippet.active_index + 1 < snippet.ranges.len() {
 6005                    self.snippet_stack.push(snippet);
 6006                }
 6007                return true;
 6008            }
 6009        }
 6010
 6011        false
 6012    }
 6013
 6014    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6015        self.transact(window, cx, |this, window, cx| {
 6016            this.select_all(&SelectAll, window, cx);
 6017            this.insert("", window, cx);
 6018        });
 6019    }
 6020
 6021    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6022        self.transact(window, cx, |this, window, cx| {
 6023            this.select_autoclose_pair(window, cx);
 6024            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6025            if !this.linked_edit_ranges.is_empty() {
 6026                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6027                let snapshot = this.buffer.read(cx).snapshot(cx);
 6028
 6029                for selection in selections.iter() {
 6030                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6031                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6032                    if selection_start.buffer_id != selection_end.buffer_id {
 6033                        continue;
 6034                    }
 6035                    if let Some(ranges) =
 6036                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6037                    {
 6038                        for (buffer, entries) in ranges {
 6039                            linked_ranges.entry(buffer).or_default().extend(entries);
 6040                        }
 6041                    }
 6042                }
 6043            }
 6044
 6045            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6046            if !this.selections.line_mode {
 6047                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6048                for selection in &mut selections {
 6049                    if selection.is_empty() {
 6050                        let old_head = selection.head();
 6051                        let mut new_head =
 6052                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6053                                .to_point(&display_map);
 6054                        if let Some((buffer, line_buffer_range)) = display_map
 6055                            .buffer_snapshot
 6056                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6057                        {
 6058                            let indent_size =
 6059                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6060                            let indent_len = match indent_size.kind {
 6061                                IndentKind::Space => {
 6062                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6063                                }
 6064                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6065                            };
 6066                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6067                                let indent_len = indent_len.get();
 6068                                new_head = cmp::min(
 6069                                    new_head,
 6070                                    MultiBufferPoint::new(
 6071                                        old_head.row,
 6072                                        ((old_head.column - 1) / indent_len) * indent_len,
 6073                                    ),
 6074                                );
 6075                            }
 6076                        }
 6077
 6078                        selection.set_head(new_head, SelectionGoal::None);
 6079                    }
 6080                }
 6081            }
 6082
 6083            this.signature_help_state.set_backspace_pressed(true);
 6084            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6085                s.select(selections)
 6086            });
 6087            this.insert("", window, cx);
 6088            let empty_str: Arc<str> = Arc::from("");
 6089            for (buffer, edits) in linked_ranges {
 6090                let snapshot = buffer.read(cx).snapshot();
 6091                use text::ToPoint as TP;
 6092
 6093                let edits = edits
 6094                    .into_iter()
 6095                    .map(|range| {
 6096                        let end_point = TP::to_point(&range.end, &snapshot);
 6097                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6098
 6099                        if end_point == start_point {
 6100                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6101                                .saturating_sub(1);
 6102                            start_point =
 6103                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6104                        };
 6105
 6106                        (start_point..end_point, empty_str.clone())
 6107                    })
 6108                    .sorted_by_key(|(range, _)| range.start)
 6109                    .collect::<Vec<_>>();
 6110                buffer.update(cx, |this, cx| {
 6111                    this.edit(edits, None, cx);
 6112                })
 6113            }
 6114            this.refresh_inline_completion(true, false, window, cx);
 6115            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6116        });
 6117    }
 6118
 6119    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6120        self.transact(window, cx, |this, window, cx| {
 6121            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6122                let line_mode = s.line_mode;
 6123                s.move_with(|map, selection| {
 6124                    if selection.is_empty() && !line_mode {
 6125                        let cursor = movement::right(map, selection.head());
 6126                        selection.end = cursor;
 6127                        selection.reversed = true;
 6128                        selection.goal = SelectionGoal::None;
 6129                    }
 6130                })
 6131            });
 6132            this.insert("", window, cx);
 6133            this.refresh_inline_completion(true, false, window, cx);
 6134        });
 6135    }
 6136
 6137    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6138        if self.move_to_prev_snippet_tabstop(window, cx) {
 6139            return;
 6140        }
 6141
 6142        self.outdent(&Outdent, window, cx);
 6143    }
 6144
 6145    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6146        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6147            return;
 6148        }
 6149
 6150        let mut selections = self.selections.all_adjusted(cx);
 6151        let buffer = self.buffer.read(cx);
 6152        let snapshot = buffer.snapshot(cx);
 6153        let rows_iter = selections.iter().map(|s| s.head().row);
 6154        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6155
 6156        let mut edits = Vec::new();
 6157        let mut prev_edited_row = 0;
 6158        let mut row_delta = 0;
 6159        for selection in &mut selections {
 6160            if selection.start.row != prev_edited_row {
 6161                row_delta = 0;
 6162            }
 6163            prev_edited_row = selection.end.row;
 6164
 6165            // If the selection is non-empty, then increase the indentation of the selected lines.
 6166            if !selection.is_empty() {
 6167                row_delta =
 6168                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6169                continue;
 6170            }
 6171
 6172            // If the selection is empty and the cursor is in the leading whitespace before the
 6173            // suggested indentation, then auto-indent the line.
 6174            let cursor = selection.head();
 6175            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6176            if let Some(suggested_indent) =
 6177                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6178            {
 6179                if cursor.column < suggested_indent.len
 6180                    && cursor.column <= current_indent.len
 6181                    && current_indent.len <= suggested_indent.len
 6182                {
 6183                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6184                    selection.end = selection.start;
 6185                    if row_delta == 0 {
 6186                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6187                            cursor.row,
 6188                            current_indent,
 6189                            suggested_indent,
 6190                        ));
 6191                        row_delta = suggested_indent.len - current_indent.len;
 6192                    }
 6193                    continue;
 6194                }
 6195            }
 6196
 6197            // Otherwise, insert a hard or soft tab.
 6198            let settings = buffer.settings_at(cursor, cx);
 6199            let tab_size = if settings.hard_tabs {
 6200                IndentSize::tab()
 6201            } else {
 6202                let tab_size = settings.tab_size.get();
 6203                let char_column = snapshot
 6204                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6205                    .flat_map(str::chars)
 6206                    .count()
 6207                    + row_delta as usize;
 6208                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6209                IndentSize::spaces(chars_to_next_tab_stop)
 6210            };
 6211            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6212            selection.end = selection.start;
 6213            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6214            row_delta += tab_size.len;
 6215        }
 6216
 6217        self.transact(window, cx, |this, window, cx| {
 6218            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6219            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6220                s.select(selections)
 6221            });
 6222            this.refresh_inline_completion(true, false, window, cx);
 6223        });
 6224    }
 6225
 6226    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6227        if self.read_only(cx) {
 6228            return;
 6229        }
 6230        let mut selections = self.selections.all::<Point>(cx);
 6231        let mut prev_edited_row = 0;
 6232        let mut row_delta = 0;
 6233        let mut edits = Vec::new();
 6234        let buffer = self.buffer.read(cx);
 6235        let snapshot = buffer.snapshot(cx);
 6236        for selection in &mut selections {
 6237            if selection.start.row != prev_edited_row {
 6238                row_delta = 0;
 6239            }
 6240            prev_edited_row = selection.end.row;
 6241
 6242            row_delta =
 6243                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6244        }
 6245
 6246        self.transact(window, cx, |this, window, cx| {
 6247            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6248            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6249                s.select(selections)
 6250            });
 6251        });
 6252    }
 6253
 6254    fn indent_selection(
 6255        buffer: &MultiBuffer,
 6256        snapshot: &MultiBufferSnapshot,
 6257        selection: &mut Selection<Point>,
 6258        edits: &mut Vec<(Range<Point>, String)>,
 6259        delta_for_start_row: u32,
 6260        cx: &App,
 6261    ) -> u32 {
 6262        let settings = buffer.settings_at(selection.start, cx);
 6263        let tab_size = settings.tab_size.get();
 6264        let indent_kind = if settings.hard_tabs {
 6265            IndentKind::Tab
 6266        } else {
 6267            IndentKind::Space
 6268        };
 6269        let mut start_row = selection.start.row;
 6270        let mut end_row = selection.end.row + 1;
 6271
 6272        // If a selection ends at the beginning of a line, don't indent
 6273        // that last line.
 6274        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6275            end_row -= 1;
 6276        }
 6277
 6278        // Avoid re-indenting a row that has already been indented by a
 6279        // previous selection, but still update this selection's column
 6280        // to reflect that indentation.
 6281        if delta_for_start_row > 0 {
 6282            start_row += 1;
 6283            selection.start.column += delta_for_start_row;
 6284            if selection.end.row == selection.start.row {
 6285                selection.end.column += delta_for_start_row;
 6286            }
 6287        }
 6288
 6289        let mut delta_for_end_row = 0;
 6290        let has_multiple_rows = start_row + 1 != end_row;
 6291        for row in start_row..end_row {
 6292            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6293            let indent_delta = match (current_indent.kind, indent_kind) {
 6294                (IndentKind::Space, IndentKind::Space) => {
 6295                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6296                    IndentSize::spaces(columns_to_next_tab_stop)
 6297                }
 6298                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6299                (_, IndentKind::Tab) => IndentSize::tab(),
 6300            };
 6301
 6302            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6303                0
 6304            } else {
 6305                selection.start.column
 6306            };
 6307            let row_start = Point::new(row, start);
 6308            edits.push((
 6309                row_start..row_start,
 6310                indent_delta.chars().collect::<String>(),
 6311            ));
 6312
 6313            // Update this selection's endpoints to reflect the indentation.
 6314            if row == selection.start.row {
 6315                selection.start.column += indent_delta.len;
 6316            }
 6317            if row == selection.end.row {
 6318                selection.end.column += indent_delta.len;
 6319                delta_for_end_row = indent_delta.len;
 6320            }
 6321        }
 6322
 6323        if selection.start.row == selection.end.row {
 6324            delta_for_start_row + delta_for_end_row
 6325        } else {
 6326            delta_for_end_row
 6327        }
 6328    }
 6329
 6330    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6331        if self.read_only(cx) {
 6332            return;
 6333        }
 6334        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6335        let selections = self.selections.all::<Point>(cx);
 6336        let mut deletion_ranges = Vec::new();
 6337        let mut last_outdent = None;
 6338        {
 6339            let buffer = self.buffer.read(cx);
 6340            let snapshot = buffer.snapshot(cx);
 6341            for selection in &selections {
 6342                let settings = buffer.settings_at(selection.start, cx);
 6343                let tab_size = settings.tab_size.get();
 6344                let mut rows = selection.spanned_rows(false, &display_map);
 6345
 6346                // Avoid re-outdenting a row that has already been outdented by a
 6347                // previous selection.
 6348                if let Some(last_row) = last_outdent {
 6349                    if last_row == rows.start {
 6350                        rows.start = rows.start.next_row();
 6351                    }
 6352                }
 6353                let has_multiple_rows = rows.len() > 1;
 6354                for row in rows.iter_rows() {
 6355                    let indent_size = snapshot.indent_size_for_line(row);
 6356                    if indent_size.len > 0 {
 6357                        let deletion_len = match indent_size.kind {
 6358                            IndentKind::Space => {
 6359                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6360                                if columns_to_prev_tab_stop == 0 {
 6361                                    tab_size
 6362                                } else {
 6363                                    columns_to_prev_tab_stop
 6364                                }
 6365                            }
 6366                            IndentKind::Tab => 1,
 6367                        };
 6368                        let start = if has_multiple_rows
 6369                            || deletion_len > selection.start.column
 6370                            || indent_size.len < selection.start.column
 6371                        {
 6372                            0
 6373                        } else {
 6374                            selection.start.column - deletion_len
 6375                        };
 6376                        deletion_ranges.push(
 6377                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6378                        );
 6379                        last_outdent = Some(row);
 6380                    }
 6381                }
 6382            }
 6383        }
 6384
 6385        self.transact(window, cx, |this, window, cx| {
 6386            this.buffer.update(cx, |buffer, cx| {
 6387                let empty_str: Arc<str> = Arc::default();
 6388                buffer.edit(
 6389                    deletion_ranges
 6390                        .into_iter()
 6391                        .map(|range| (range, empty_str.clone())),
 6392                    None,
 6393                    cx,
 6394                );
 6395            });
 6396            let selections = this.selections.all::<usize>(cx);
 6397            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6398                s.select(selections)
 6399            });
 6400        });
 6401    }
 6402
 6403    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6404        if self.read_only(cx) {
 6405            return;
 6406        }
 6407        let selections = self
 6408            .selections
 6409            .all::<usize>(cx)
 6410            .into_iter()
 6411            .map(|s| s.range());
 6412
 6413        self.transact(window, cx, |this, window, cx| {
 6414            this.buffer.update(cx, |buffer, cx| {
 6415                buffer.autoindent_ranges(selections, cx);
 6416            });
 6417            let selections = this.selections.all::<usize>(cx);
 6418            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6419                s.select(selections)
 6420            });
 6421        });
 6422    }
 6423
 6424    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6425        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6426        let selections = self.selections.all::<Point>(cx);
 6427
 6428        let mut new_cursors = Vec::new();
 6429        let mut edit_ranges = Vec::new();
 6430        let mut selections = selections.iter().peekable();
 6431        while let Some(selection) = selections.next() {
 6432            let mut rows = selection.spanned_rows(false, &display_map);
 6433            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6434
 6435            // Accumulate contiguous regions of rows that we want to delete.
 6436            while let Some(next_selection) = selections.peek() {
 6437                let next_rows = next_selection.spanned_rows(false, &display_map);
 6438                if next_rows.start <= rows.end {
 6439                    rows.end = next_rows.end;
 6440                    selections.next().unwrap();
 6441                } else {
 6442                    break;
 6443                }
 6444            }
 6445
 6446            let buffer = &display_map.buffer_snapshot;
 6447            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6448            let edit_end;
 6449            let cursor_buffer_row;
 6450            if buffer.max_point().row >= rows.end.0 {
 6451                // If there's a line after the range, delete the \n from the end of the row range
 6452                // and position the cursor on the next line.
 6453                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6454                cursor_buffer_row = rows.end;
 6455            } else {
 6456                // If there isn't a line after the range, delete the \n from the line before the
 6457                // start of the row range and position the cursor there.
 6458                edit_start = edit_start.saturating_sub(1);
 6459                edit_end = buffer.len();
 6460                cursor_buffer_row = rows.start.previous_row();
 6461            }
 6462
 6463            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6464            *cursor.column_mut() =
 6465                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6466
 6467            new_cursors.push((
 6468                selection.id,
 6469                buffer.anchor_after(cursor.to_point(&display_map)),
 6470            ));
 6471            edit_ranges.push(edit_start..edit_end);
 6472        }
 6473
 6474        self.transact(window, cx, |this, window, cx| {
 6475            let buffer = this.buffer.update(cx, |buffer, cx| {
 6476                let empty_str: Arc<str> = Arc::default();
 6477                buffer.edit(
 6478                    edit_ranges
 6479                        .into_iter()
 6480                        .map(|range| (range, empty_str.clone())),
 6481                    None,
 6482                    cx,
 6483                );
 6484                buffer.snapshot(cx)
 6485            });
 6486            let new_selections = new_cursors
 6487                .into_iter()
 6488                .map(|(id, cursor)| {
 6489                    let cursor = cursor.to_point(&buffer);
 6490                    Selection {
 6491                        id,
 6492                        start: cursor,
 6493                        end: cursor,
 6494                        reversed: false,
 6495                        goal: SelectionGoal::None,
 6496                    }
 6497                })
 6498                .collect();
 6499
 6500            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6501                s.select(new_selections);
 6502            });
 6503        });
 6504    }
 6505
 6506    pub fn join_lines_impl(
 6507        &mut self,
 6508        insert_whitespace: bool,
 6509        window: &mut Window,
 6510        cx: &mut Context<Self>,
 6511    ) {
 6512        if self.read_only(cx) {
 6513            return;
 6514        }
 6515        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6516        for selection in self.selections.all::<Point>(cx) {
 6517            let start = MultiBufferRow(selection.start.row);
 6518            // Treat single line selections as if they include the next line. Otherwise this action
 6519            // would do nothing for single line selections individual cursors.
 6520            let end = if selection.start.row == selection.end.row {
 6521                MultiBufferRow(selection.start.row + 1)
 6522            } else {
 6523                MultiBufferRow(selection.end.row)
 6524            };
 6525
 6526            if let Some(last_row_range) = row_ranges.last_mut() {
 6527                if start <= last_row_range.end {
 6528                    last_row_range.end = end;
 6529                    continue;
 6530                }
 6531            }
 6532            row_ranges.push(start..end);
 6533        }
 6534
 6535        let snapshot = self.buffer.read(cx).snapshot(cx);
 6536        let mut cursor_positions = Vec::new();
 6537        for row_range in &row_ranges {
 6538            let anchor = snapshot.anchor_before(Point::new(
 6539                row_range.end.previous_row().0,
 6540                snapshot.line_len(row_range.end.previous_row()),
 6541            ));
 6542            cursor_positions.push(anchor..anchor);
 6543        }
 6544
 6545        self.transact(window, cx, |this, window, cx| {
 6546            for row_range in row_ranges.into_iter().rev() {
 6547                for row in row_range.iter_rows().rev() {
 6548                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6549                    let next_line_row = row.next_row();
 6550                    let indent = snapshot.indent_size_for_line(next_line_row);
 6551                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6552
 6553                    let replace =
 6554                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6555                            " "
 6556                        } else {
 6557                            ""
 6558                        };
 6559
 6560                    this.buffer.update(cx, |buffer, cx| {
 6561                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6562                    });
 6563                }
 6564            }
 6565
 6566            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6567                s.select_anchor_ranges(cursor_positions)
 6568            });
 6569        });
 6570    }
 6571
 6572    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6573        self.join_lines_impl(true, window, cx);
 6574    }
 6575
 6576    pub fn sort_lines_case_sensitive(
 6577        &mut self,
 6578        _: &SortLinesCaseSensitive,
 6579        window: &mut Window,
 6580        cx: &mut Context<Self>,
 6581    ) {
 6582        self.manipulate_lines(window, cx, |lines| lines.sort())
 6583    }
 6584
 6585    pub fn sort_lines_case_insensitive(
 6586        &mut self,
 6587        _: &SortLinesCaseInsensitive,
 6588        window: &mut Window,
 6589        cx: &mut Context<Self>,
 6590    ) {
 6591        self.manipulate_lines(window, cx, |lines| {
 6592            lines.sort_by_key(|line| line.to_lowercase())
 6593        })
 6594    }
 6595
 6596    pub fn unique_lines_case_insensitive(
 6597        &mut self,
 6598        _: &UniqueLinesCaseInsensitive,
 6599        window: &mut Window,
 6600        cx: &mut Context<Self>,
 6601    ) {
 6602        self.manipulate_lines(window, cx, |lines| {
 6603            let mut seen = HashSet::default();
 6604            lines.retain(|line| seen.insert(line.to_lowercase()));
 6605        })
 6606    }
 6607
 6608    pub fn unique_lines_case_sensitive(
 6609        &mut self,
 6610        _: &UniqueLinesCaseSensitive,
 6611        window: &mut Window,
 6612        cx: &mut Context<Self>,
 6613    ) {
 6614        self.manipulate_lines(window, cx, |lines| {
 6615            let mut seen = HashSet::default();
 6616            lines.retain(|line| seen.insert(*line));
 6617        })
 6618    }
 6619
 6620    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6621        let mut revert_changes = HashMap::default();
 6622        let snapshot = self.snapshot(window, cx);
 6623        for hunk in snapshot
 6624            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6625        {
 6626            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6627        }
 6628        if !revert_changes.is_empty() {
 6629            self.transact(window, cx, |editor, window, cx| {
 6630                editor.revert(revert_changes, window, cx);
 6631            });
 6632        }
 6633    }
 6634
 6635    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6636        let Some(project) = self.project.clone() else {
 6637            return;
 6638        };
 6639        self.reload(project, window, cx)
 6640            .detach_and_notify_err(window, cx);
 6641    }
 6642
 6643    pub fn revert_selected_hunks(
 6644        &mut self,
 6645        _: &RevertSelectedHunks,
 6646        window: &mut Window,
 6647        cx: &mut Context<Self>,
 6648    ) {
 6649        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6650        self.revert_hunks_in_ranges(selections, window, cx);
 6651    }
 6652
 6653    fn revert_hunks_in_ranges(
 6654        &mut self,
 6655        ranges: impl Iterator<Item = Range<Point>>,
 6656        window: &mut Window,
 6657        cx: &mut Context<Editor>,
 6658    ) {
 6659        let mut revert_changes = HashMap::default();
 6660        let snapshot = self.snapshot(window, cx);
 6661        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6662            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6663        }
 6664        if !revert_changes.is_empty() {
 6665            self.transact(window, cx, |editor, window, cx| {
 6666                editor.revert(revert_changes, window, cx);
 6667            });
 6668        }
 6669    }
 6670
 6671    pub fn open_active_item_in_terminal(
 6672        &mut self,
 6673        _: &OpenInTerminal,
 6674        window: &mut Window,
 6675        cx: &mut Context<Self>,
 6676    ) {
 6677        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6678            let project_path = buffer.read(cx).project_path(cx)?;
 6679            let project = self.project.as_ref()?.read(cx);
 6680            let entry = project.entry_for_path(&project_path, cx)?;
 6681            let parent = match &entry.canonical_path {
 6682                Some(canonical_path) => canonical_path.to_path_buf(),
 6683                None => project.absolute_path(&project_path, cx)?,
 6684            }
 6685            .parent()?
 6686            .to_path_buf();
 6687            Some(parent)
 6688        }) {
 6689            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6690        }
 6691    }
 6692
 6693    pub fn prepare_revert_change(
 6694        &self,
 6695        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6696        hunk: &MultiBufferDiffHunk,
 6697        cx: &mut App,
 6698    ) -> Option<()> {
 6699        let buffer = self.buffer.read(cx);
 6700        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6701        let buffer = buffer.buffer(hunk.buffer_id)?;
 6702        let buffer = buffer.read(cx);
 6703        let original_text = change_set
 6704            .read(cx)
 6705            .base_text
 6706            .as_ref()?
 6707            .as_rope()
 6708            .slice(hunk.diff_base_byte_range.clone());
 6709        let buffer_snapshot = buffer.snapshot();
 6710        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6711        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6712            probe
 6713                .0
 6714                .start
 6715                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6716                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6717        }) {
 6718            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6719            Some(())
 6720        } else {
 6721            None
 6722        }
 6723    }
 6724
 6725    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6726        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6727    }
 6728
 6729    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6730        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6731    }
 6732
 6733    fn manipulate_lines<Fn>(
 6734        &mut self,
 6735        window: &mut Window,
 6736        cx: &mut Context<Self>,
 6737        mut callback: Fn,
 6738    ) where
 6739        Fn: FnMut(&mut Vec<&str>),
 6740    {
 6741        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6742        let buffer = self.buffer.read(cx).snapshot(cx);
 6743
 6744        let mut edits = Vec::new();
 6745
 6746        let selections = self.selections.all::<Point>(cx);
 6747        let mut selections = selections.iter().peekable();
 6748        let mut contiguous_row_selections = Vec::new();
 6749        let mut new_selections = Vec::new();
 6750        let mut added_lines = 0;
 6751        let mut removed_lines = 0;
 6752
 6753        while let Some(selection) = selections.next() {
 6754            let (start_row, end_row) = consume_contiguous_rows(
 6755                &mut contiguous_row_selections,
 6756                selection,
 6757                &display_map,
 6758                &mut selections,
 6759            );
 6760
 6761            let start_point = Point::new(start_row.0, 0);
 6762            let end_point = Point::new(
 6763                end_row.previous_row().0,
 6764                buffer.line_len(end_row.previous_row()),
 6765            );
 6766            let text = buffer
 6767                .text_for_range(start_point..end_point)
 6768                .collect::<String>();
 6769
 6770            let mut lines = text.split('\n').collect_vec();
 6771
 6772            let lines_before = lines.len();
 6773            callback(&mut lines);
 6774            let lines_after = lines.len();
 6775
 6776            edits.push((start_point..end_point, lines.join("\n")));
 6777
 6778            // Selections must change based on added and removed line count
 6779            let start_row =
 6780                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6781            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6782            new_selections.push(Selection {
 6783                id: selection.id,
 6784                start: start_row,
 6785                end: end_row,
 6786                goal: SelectionGoal::None,
 6787                reversed: selection.reversed,
 6788            });
 6789
 6790            if lines_after > lines_before {
 6791                added_lines += lines_after - lines_before;
 6792            } else if lines_before > lines_after {
 6793                removed_lines += lines_before - lines_after;
 6794            }
 6795        }
 6796
 6797        self.transact(window, cx, |this, window, cx| {
 6798            let buffer = this.buffer.update(cx, |buffer, cx| {
 6799                buffer.edit(edits, None, cx);
 6800                buffer.snapshot(cx)
 6801            });
 6802
 6803            // Recalculate offsets on newly edited buffer
 6804            let new_selections = new_selections
 6805                .iter()
 6806                .map(|s| {
 6807                    let start_point = Point::new(s.start.0, 0);
 6808                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6809                    Selection {
 6810                        id: s.id,
 6811                        start: buffer.point_to_offset(start_point),
 6812                        end: buffer.point_to_offset(end_point),
 6813                        goal: s.goal,
 6814                        reversed: s.reversed,
 6815                    }
 6816                })
 6817                .collect();
 6818
 6819            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6820                s.select(new_selections);
 6821            });
 6822
 6823            this.request_autoscroll(Autoscroll::fit(), cx);
 6824        });
 6825    }
 6826
 6827    pub fn convert_to_upper_case(
 6828        &mut self,
 6829        _: &ConvertToUpperCase,
 6830        window: &mut Window,
 6831        cx: &mut Context<Self>,
 6832    ) {
 6833        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6834    }
 6835
 6836    pub fn convert_to_lower_case(
 6837        &mut self,
 6838        _: &ConvertToLowerCase,
 6839        window: &mut Window,
 6840        cx: &mut Context<Self>,
 6841    ) {
 6842        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6843    }
 6844
 6845    pub fn convert_to_title_case(
 6846        &mut self,
 6847        _: &ConvertToTitleCase,
 6848        window: &mut Window,
 6849        cx: &mut Context<Self>,
 6850    ) {
 6851        self.manipulate_text(window, cx, |text| {
 6852            text.split('\n')
 6853                .map(|line| line.to_case(Case::Title))
 6854                .join("\n")
 6855        })
 6856    }
 6857
 6858    pub fn convert_to_snake_case(
 6859        &mut self,
 6860        _: &ConvertToSnakeCase,
 6861        window: &mut Window,
 6862        cx: &mut Context<Self>,
 6863    ) {
 6864        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6865    }
 6866
 6867    pub fn convert_to_kebab_case(
 6868        &mut self,
 6869        _: &ConvertToKebabCase,
 6870        window: &mut Window,
 6871        cx: &mut Context<Self>,
 6872    ) {
 6873        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6874    }
 6875
 6876    pub fn convert_to_upper_camel_case(
 6877        &mut self,
 6878        _: &ConvertToUpperCamelCase,
 6879        window: &mut Window,
 6880        cx: &mut Context<Self>,
 6881    ) {
 6882        self.manipulate_text(window, cx, |text| {
 6883            text.split('\n')
 6884                .map(|line| line.to_case(Case::UpperCamel))
 6885                .join("\n")
 6886        })
 6887    }
 6888
 6889    pub fn convert_to_lower_camel_case(
 6890        &mut self,
 6891        _: &ConvertToLowerCamelCase,
 6892        window: &mut Window,
 6893        cx: &mut Context<Self>,
 6894    ) {
 6895        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6896    }
 6897
 6898    pub fn convert_to_opposite_case(
 6899        &mut self,
 6900        _: &ConvertToOppositeCase,
 6901        window: &mut Window,
 6902        cx: &mut Context<Self>,
 6903    ) {
 6904        self.manipulate_text(window, cx, |text| {
 6905            text.chars()
 6906                .fold(String::with_capacity(text.len()), |mut t, c| {
 6907                    if c.is_uppercase() {
 6908                        t.extend(c.to_lowercase());
 6909                    } else {
 6910                        t.extend(c.to_uppercase());
 6911                    }
 6912                    t
 6913                })
 6914        })
 6915    }
 6916
 6917    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6918    where
 6919        Fn: FnMut(&str) -> String,
 6920    {
 6921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6922        let buffer = self.buffer.read(cx).snapshot(cx);
 6923
 6924        let mut new_selections = Vec::new();
 6925        let mut edits = Vec::new();
 6926        let mut selection_adjustment = 0i32;
 6927
 6928        for selection in self.selections.all::<usize>(cx) {
 6929            let selection_is_empty = selection.is_empty();
 6930
 6931            let (start, end) = if selection_is_empty {
 6932                let word_range = movement::surrounding_word(
 6933                    &display_map,
 6934                    selection.start.to_display_point(&display_map),
 6935                );
 6936                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6937                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6938                (start, end)
 6939            } else {
 6940                (selection.start, selection.end)
 6941            };
 6942
 6943            let text = buffer.text_for_range(start..end).collect::<String>();
 6944            let old_length = text.len() as i32;
 6945            let text = callback(&text);
 6946
 6947            new_selections.push(Selection {
 6948                start: (start as i32 - selection_adjustment) as usize,
 6949                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6950                goal: SelectionGoal::None,
 6951                ..selection
 6952            });
 6953
 6954            selection_adjustment += old_length - text.len() as i32;
 6955
 6956            edits.push((start..end, text));
 6957        }
 6958
 6959        self.transact(window, cx, |this, window, cx| {
 6960            this.buffer.update(cx, |buffer, cx| {
 6961                buffer.edit(edits, None, cx);
 6962            });
 6963
 6964            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6965                s.select(new_selections);
 6966            });
 6967
 6968            this.request_autoscroll(Autoscroll::fit(), cx);
 6969        });
 6970    }
 6971
 6972    pub fn duplicate(
 6973        &mut self,
 6974        upwards: bool,
 6975        whole_lines: bool,
 6976        window: &mut Window,
 6977        cx: &mut Context<Self>,
 6978    ) {
 6979        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6980        let buffer = &display_map.buffer_snapshot;
 6981        let selections = self.selections.all::<Point>(cx);
 6982
 6983        let mut edits = Vec::new();
 6984        let mut selections_iter = selections.iter().peekable();
 6985        while let Some(selection) = selections_iter.next() {
 6986            let mut rows = selection.spanned_rows(false, &display_map);
 6987            // duplicate line-wise
 6988            if whole_lines || selection.start == selection.end {
 6989                // Avoid duplicating the same lines twice.
 6990                while let Some(next_selection) = selections_iter.peek() {
 6991                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6992                    if next_rows.start < rows.end {
 6993                        rows.end = next_rows.end;
 6994                        selections_iter.next().unwrap();
 6995                    } else {
 6996                        break;
 6997                    }
 6998                }
 6999
 7000                // Copy the text from the selected row region and splice it either at the start
 7001                // or end of the region.
 7002                let start = Point::new(rows.start.0, 0);
 7003                let end = Point::new(
 7004                    rows.end.previous_row().0,
 7005                    buffer.line_len(rows.end.previous_row()),
 7006                );
 7007                let text = buffer
 7008                    .text_for_range(start..end)
 7009                    .chain(Some("\n"))
 7010                    .collect::<String>();
 7011                let insert_location = if upwards {
 7012                    Point::new(rows.end.0, 0)
 7013                } else {
 7014                    start
 7015                };
 7016                edits.push((insert_location..insert_location, text));
 7017            } else {
 7018                // duplicate character-wise
 7019                let start = selection.start;
 7020                let end = selection.end;
 7021                let text = buffer.text_for_range(start..end).collect::<String>();
 7022                edits.push((selection.end..selection.end, text));
 7023            }
 7024        }
 7025
 7026        self.transact(window, cx, |this, _, cx| {
 7027            this.buffer.update(cx, |buffer, cx| {
 7028                buffer.edit(edits, None, cx);
 7029            });
 7030
 7031            this.request_autoscroll(Autoscroll::fit(), cx);
 7032        });
 7033    }
 7034
 7035    pub fn duplicate_line_up(
 7036        &mut self,
 7037        _: &DuplicateLineUp,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.duplicate(true, true, window, cx);
 7042    }
 7043
 7044    pub fn duplicate_line_down(
 7045        &mut self,
 7046        _: &DuplicateLineDown,
 7047        window: &mut Window,
 7048        cx: &mut Context<Self>,
 7049    ) {
 7050        self.duplicate(false, true, window, cx);
 7051    }
 7052
 7053    pub fn duplicate_selection(
 7054        &mut self,
 7055        _: &DuplicateSelection,
 7056        window: &mut Window,
 7057        cx: &mut Context<Self>,
 7058    ) {
 7059        self.duplicate(false, false, window, cx);
 7060    }
 7061
 7062    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7063        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7064        let buffer = self.buffer.read(cx).snapshot(cx);
 7065
 7066        let mut edits = Vec::new();
 7067        let mut unfold_ranges = Vec::new();
 7068        let mut refold_creases = Vec::new();
 7069
 7070        let selections = self.selections.all::<Point>(cx);
 7071        let mut selections = selections.iter().peekable();
 7072        let mut contiguous_row_selections = Vec::new();
 7073        let mut new_selections = Vec::new();
 7074
 7075        while let Some(selection) = selections.next() {
 7076            // Find all the selections that span a contiguous row range
 7077            let (start_row, end_row) = consume_contiguous_rows(
 7078                &mut contiguous_row_selections,
 7079                selection,
 7080                &display_map,
 7081                &mut selections,
 7082            );
 7083
 7084            // Move the text spanned by the row range to be before the line preceding the row range
 7085            if start_row.0 > 0 {
 7086                let range_to_move = Point::new(
 7087                    start_row.previous_row().0,
 7088                    buffer.line_len(start_row.previous_row()),
 7089                )
 7090                    ..Point::new(
 7091                        end_row.previous_row().0,
 7092                        buffer.line_len(end_row.previous_row()),
 7093                    );
 7094                let insertion_point = display_map
 7095                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7096                    .0;
 7097
 7098                // Don't move lines across excerpts
 7099                if buffer
 7100                    .excerpt_containing(insertion_point..range_to_move.end)
 7101                    .is_some()
 7102                {
 7103                    let text = buffer
 7104                        .text_for_range(range_to_move.clone())
 7105                        .flat_map(|s| s.chars())
 7106                        .skip(1)
 7107                        .chain(['\n'])
 7108                        .collect::<String>();
 7109
 7110                    edits.push((
 7111                        buffer.anchor_after(range_to_move.start)
 7112                            ..buffer.anchor_before(range_to_move.end),
 7113                        String::new(),
 7114                    ));
 7115                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7116                    edits.push((insertion_anchor..insertion_anchor, text));
 7117
 7118                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7119
 7120                    // Move selections up
 7121                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7122                        |mut selection| {
 7123                            selection.start.row -= row_delta;
 7124                            selection.end.row -= row_delta;
 7125                            selection
 7126                        },
 7127                    ));
 7128
 7129                    // Move folds up
 7130                    unfold_ranges.push(range_to_move.clone());
 7131                    for fold in display_map.folds_in_range(
 7132                        buffer.anchor_before(range_to_move.start)
 7133                            ..buffer.anchor_after(range_to_move.end),
 7134                    ) {
 7135                        let mut start = fold.range.start.to_point(&buffer);
 7136                        let mut end = fold.range.end.to_point(&buffer);
 7137                        start.row -= row_delta;
 7138                        end.row -= row_delta;
 7139                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7140                    }
 7141                }
 7142            }
 7143
 7144            // If we didn't move line(s), preserve the existing selections
 7145            new_selections.append(&mut contiguous_row_selections);
 7146        }
 7147
 7148        self.transact(window, cx, |this, window, cx| {
 7149            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7150            this.buffer.update(cx, |buffer, cx| {
 7151                for (range, text) in edits {
 7152                    buffer.edit([(range, text)], None, cx);
 7153                }
 7154            });
 7155            this.fold_creases(refold_creases, true, window, cx);
 7156            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7157                s.select(new_selections);
 7158            })
 7159        });
 7160    }
 7161
 7162    pub fn move_line_down(
 7163        &mut self,
 7164        _: &MoveLineDown,
 7165        window: &mut Window,
 7166        cx: &mut Context<Self>,
 7167    ) {
 7168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7169        let buffer = self.buffer.read(cx).snapshot(cx);
 7170
 7171        let mut edits = Vec::new();
 7172        let mut unfold_ranges = Vec::new();
 7173        let mut refold_creases = Vec::new();
 7174
 7175        let selections = self.selections.all::<Point>(cx);
 7176        let mut selections = selections.iter().peekable();
 7177        let mut contiguous_row_selections = Vec::new();
 7178        let mut new_selections = Vec::new();
 7179
 7180        while let Some(selection) = selections.next() {
 7181            // Find all the selections that span a contiguous row range
 7182            let (start_row, end_row) = consume_contiguous_rows(
 7183                &mut contiguous_row_selections,
 7184                selection,
 7185                &display_map,
 7186                &mut selections,
 7187            );
 7188
 7189            // Move the text spanned by the row range to be after the last line of the row range
 7190            if end_row.0 <= buffer.max_point().row {
 7191                let range_to_move =
 7192                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7193                let insertion_point = display_map
 7194                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7195                    .0;
 7196
 7197                // Don't move lines across excerpt boundaries
 7198                if buffer
 7199                    .excerpt_containing(range_to_move.start..insertion_point)
 7200                    .is_some()
 7201                {
 7202                    let mut text = String::from("\n");
 7203                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7204                    text.pop(); // Drop trailing newline
 7205                    edits.push((
 7206                        buffer.anchor_after(range_to_move.start)
 7207                            ..buffer.anchor_before(range_to_move.end),
 7208                        String::new(),
 7209                    ));
 7210                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7211                    edits.push((insertion_anchor..insertion_anchor, text));
 7212
 7213                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7214
 7215                    // Move selections down
 7216                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7217                        |mut selection| {
 7218                            selection.start.row += row_delta;
 7219                            selection.end.row += row_delta;
 7220                            selection
 7221                        },
 7222                    ));
 7223
 7224                    // Move folds down
 7225                    unfold_ranges.push(range_to_move.clone());
 7226                    for fold in display_map.folds_in_range(
 7227                        buffer.anchor_before(range_to_move.start)
 7228                            ..buffer.anchor_after(range_to_move.end),
 7229                    ) {
 7230                        let mut start = fold.range.start.to_point(&buffer);
 7231                        let mut end = fold.range.end.to_point(&buffer);
 7232                        start.row += row_delta;
 7233                        end.row += row_delta;
 7234                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7235                    }
 7236                }
 7237            }
 7238
 7239            // If we didn't move line(s), preserve the existing selections
 7240            new_selections.append(&mut contiguous_row_selections);
 7241        }
 7242
 7243        self.transact(window, cx, |this, window, cx| {
 7244            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7245            this.buffer.update(cx, |buffer, cx| {
 7246                for (range, text) in edits {
 7247                    buffer.edit([(range, text)], None, cx);
 7248                }
 7249            });
 7250            this.fold_creases(refold_creases, true, window, cx);
 7251            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7252                s.select(new_selections)
 7253            });
 7254        });
 7255    }
 7256
 7257    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7258        let text_layout_details = &self.text_layout_details(window);
 7259        self.transact(window, cx, |this, window, cx| {
 7260            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7261                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7262                let line_mode = s.line_mode;
 7263                s.move_with(|display_map, selection| {
 7264                    if !selection.is_empty() || line_mode {
 7265                        return;
 7266                    }
 7267
 7268                    let mut head = selection.head();
 7269                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7270                    if head.column() == display_map.line_len(head.row()) {
 7271                        transpose_offset = display_map
 7272                            .buffer_snapshot
 7273                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7274                    }
 7275
 7276                    if transpose_offset == 0 {
 7277                        return;
 7278                    }
 7279
 7280                    *head.column_mut() += 1;
 7281                    head = display_map.clip_point(head, Bias::Right);
 7282                    let goal = SelectionGoal::HorizontalPosition(
 7283                        display_map
 7284                            .x_for_display_point(head, text_layout_details)
 7285                            .into(),
 7286                    );
 7287                    selection.collapse_to(head, goal);
 7288
 7289                    let transpose_start = display_map
 7290                        .buffer_snapshot
 7291                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7292                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7293                        let transpose_end = display_map
 7294                            .buffer_snapshot
 7295                            .clip_offset(transpose_offset + 1, Bias::Right);
 7296                        if let Some(ch) =
 7297                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7298                        {
 7299                            edits.push((transpose_start..transpose_offset, String::new()));
 7300                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7301                        }
 7302                    }
 7303                });
 7304                edits
 7305            });
 7306            this.buffer
 7307                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7308            let selections = this.selections.all::<usize>(cx);
 7309            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7310                s.select(selections);
 7311            });
 7312        });
 7313    }
 7314
 7315    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7316        self.rewrap_impl(IsVimMode::No, cx)
 7317    }
 7318
 7319    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7320        let buffer = self.buffer.read(cx).snapshot(cx);
 7321        let selections = self.selections.all::<Point>(cx);
 7322        let mut selections = selections.iter().peekable();
 7323
 7324        let mut edits = Vec::new();
 7325        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7326
 7327        while let Some(selection) = selections.next() {
 7328            let mut start_row = selection.start.row;
 7329            let mut end_row = selection.end.row;
 7330
 7331            // Skip selections that overlap with a range that has already been rewrapped.
 7332            let selection_range = start_row..end_row;
 7333            if rewrapped_row_ranges
 7334                .iter()
 7335                .any(|range| range.overlaps(&selection_range))
 7336            {
 7337                continue;
 7338            }
 7339
 7340            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7341
 7342            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7343                match language_scope.language_name().as_ref() {
 7344                    "Markdown" | "Plain Text" => {
 7345                        should_rewrap = true;
 7346                    }
 7347                    _ => {}
 7348                }
 7349            }
 7350
 7351            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7352
 7353            // Since not all lines in the selection may be at the same indent
 7354            // level, choose the indent size that is the most common between all
 7355            // of the lines.
 7356            //
 7357            // If there is a tie, we use the deepest indent.
 7358            let (indent_size, indent_end) = {
 7359                let mut indent_size_occurrences = HashMap::default();
 7360                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7361
 7362                for row in start_row..=end_row {
 7363                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7364                    rows_by_indent_size.entry(indent).or_default().push(row);
 7365                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7366                }
 7367
 7368                let indent_size = indent_size_occurrences
 7369                    .into_iter()
 7370                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7371                    .map(|(indent, _)| indent)
 7372                    .unwrap_or_default();
 7373                let row = rows_by_indent_size[&indent_size][0];
 7374                let indent_end = Point::new(row, indent_size.len);
 7375
 7376                (indent_size, indent_end)
 7377            };
 7378
 7379            let mut line_prefix = indent_size.chars().collect::<String>();
 7380
 7381            if let Some(comment_prefix) =
 7382                buffer
 7383                    .language_scope_at(selection.head())
 7384                    .and_then(|language| {
 7385                        language
 7386                            .line_comment_prefixes()
 7387                            .iter()
 7388                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7389                            .cloned()
 7390                    })
 7391            {
 7392                line_prefix.push_str(&comment_prefix);
 7393                should_rewrap = true;
 7394            }
 7395
 7396            if !should_rewrap {
 7397                continue;
 7398            }
 7399
 7400            if selection.is_empty() {
 7401                'expand_upwards: while start_row > 0 {
 7402                    let prev_row = start_row - 1;
 7403                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7404                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7405                    {
 7406                        start_row = prev_row;
 7407                    } else {
 7408                        break 'expand_upwards;
 7409                    }
 7410                }
 7411
 7412                'expand_downwards: while end_row < buffer.max_point().row {
 7413                    let next_row = end_row + 1;
 7414                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7415                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7416                    {
 7417                        end_row = next_row;
 7418                    } else {
 7419                        break 'expand_downwards;
 7420                    }
 7421                }
 7422            }
 7423
 7424            let start = Point::new(start_row, 0);
 7425            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7426            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7427            let Some(lines_without_prefixes) = selection_text
 7428                .lines()
 7429                .map(|line| {
 7430                    line.strip_prefix(&line_prefix)
 7431                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7432                        .ok_or_else(|| {
 7433                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7434                        })
 7435                })
 7436                .collect::<Result<Vec<_>, _>>()
 7437                .log_err()
 7438            else {
 7439                continue;
 7440            };
 7441
 7442            let wrap_column = buffer
 7443                .settings_at(Point::new(start_row, 0), cx)
 7444                .preferred_line_length as usize;
 7445            let wrapped_text = wrap_with_prefix(
 7446                line_prefix,
 7447                lines_without_prefixes.join(" "),
 7448                wrap_column,
 7449                tab_size,
 7450            );
 7451
 7452            // TODO: should always use char-based diff while still supporting cursor behavior that
 7453            // matches vim.
 7454            let diff = match is_vim_mode {
 7455                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7456                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7457            };
 7458            let mut offset = start.to_offset(&buffer);
 7459            let mut moved_since_edit = true;
 7460
 7461            for change in diff.iter_all_changes() {
 7462                let value = change.value();
 7463                match change.tag() {
 7464                    ChangeTag::Equal => {
 7465                        offset += value.len();
 7466                        moved_since_edit = true;
 7467                    }
 7468                    ChangeTag::Delete => {
 7469                        let start = buffer.anchor_after(offset);
 7470                        let end = buffer.anchor_before(offset + value.len());
 7471
 7472                        if moved_since_edit {
 7473                            edits.push((start..end, String::new()));
 7474                        } else {
 7475                            edits.last_mut().unwrap().0.end = end;
 7476                        }
 7477
 7478                        offset += value.len();
 7479                        moved_since_edit = false;
 7480                    }
 7481                    ChangeTag::Insert => {
 7482                        if moved_since_edit {
 7483                            let anchor = buffer.anchor_after(offset);
 7484                            edits.push((anchor..anchor, value.to_string()));
 7485                        } else {
 7486                            edits.last_mut().unwrap().1.push_str(value);
 7487                        }
 7488
 7489                        moved_since_edit = false;
 7490                    }
 7491                }
 7492            }
 7493
 7494            rewrapped_row_ranges.push(start_row..=end_row);
 7495        }
 7496
 7497        self.buffer
 7498            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7499    }
 7500
 7501    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7502        let mut text = String::new();
 7503        let buffer = self.buffer.read(cx).snapshot(cx);
 7504        let mut selections = self.selections.all::<Point>(cx);
 7505        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7506        {
 7507            let max_point = buffer.max_point();
 7508            let mut is_first = true;
 7509            for selection in &mut selections {
 7510                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7511                if is_entire_line {
 7512                    selection.start = Point::new(selection.start.row, 0);
 7513                    if !selection.is_empty() && selection.end.column == 0 {
 7514                        selection.end = cmp::min(max_point, selection.end);
 7515                    } else {
 7516                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7517                    }
 7518                    selection.goal = SelectionGoal::None;
 7519                }
 7520                if is_first {
 7521                    is_first = false;
 7522                } else {
 7523                    text += "\n";
 7524                }
 7525                let mut len = 0;
 7526                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7527                    text.push_str(chunk);
 7528                    len += chunk.len();
 7529                }
 7530                clipboard_selections.push(ClipboardSelection {
 7531                    len,
 7532                    is_entire_line,
 7533                    first_line_indent: buffer
 7534                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7535                        .len,
 7536                });
 7537            }
 7538        }
 7539
 7540        self.transact(window, cx, |this, window, cx| {
 7541            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7542                s.select(selections);
 7543            });
 7544            this.insert("", window, cx);
 7545        });
 7546        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7547    }
 7548
 7549    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7550        let item = self.cut_common(window, cx);
 7551        cx.write_to_clipboard(item);
 7552    }
 7553
 7554    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7555        self.change_selections(None, window, cx, |s| {
 7556            s.move_with(|snapshot, sel| {
 7557                if sel.is_empty() {
 7558                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7559                }
 7560            });
 7561        });
 7562        let item = self.cut_common(window, cx);
 7563        cx.set_global(KillRing(item))
 7564    }
 7565
 7566    pub fn kill_ring_yank(
 7567        &mut self,
 7568        _: &KillRingYank,
 7569        window: &mut Window,
 7570        cx: &mut Context<Self>,
 7571    ) {
 7572        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7573            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7574                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7575            } else {
 7576                return;
 7577            }
 7578        } else {
 7579            return;
 7580        };
 7581        self.do_paste(&text, metadata, false, window, cx);
 7582    }
 7583
 7584    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7585        let selections = self.selections.all::<Point>(cx);
 7586        let buffer = self.buffer.read(cx).read(cx);
 7587        let mut text = String::new();
 7588
 7589        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7590        {
 7591            let max_point = buffer.max_point();
 7592            let mut is_first = true;
 7593            for selection in selections.iter() {
 7594                let mut start = selection.start;
 7595                let mut end = selection.end;
 7596                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7597                if is_entire_line {
 7598                    start = Point::new(start.row, 0);
 7599                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7600                }
 7601                if is_first {
 7602                    is_first = false;
 7603                } else {
 7604                    text += "\n";
 7605                }
 7606                let mut len = 0;
 7607                for chunk in buffer.text_for_range(start..end) {
 7608                    text.push_str(chunk);
 7609                    len += chunk.len();
 7610                }
 7611                clipboard_selections.push(ClipboardSelection {
 7612                    len,
 7613                    is_entire_line,
 7614                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7615                });
 7616            }
 7617        }
 7618
 7619        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7620            text,
 7621            clipboard_selections,
 7622        ));
 7623    }
 7624
 7625    pub fn do_paste(
 7626        &mut self,
 7627        text: &String,
 7628        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7629        handle_entire_lines: bool,
 7630        window: &mut Window,
 7631        cx: &mut Context<Self>,
 7632    ) {
 7633        if self.read_only(cx) {
 7634            return;
 7635        }
 7636
 7637        let clipboard_text = Cow::Borrowed(text);
 7638
 7639        self.transact(window, cx, |this, window, cx| {
 7640            if let Some(mut clipboard_selections) = clipboard_selections {
 7641                let old_selections = this.selections.all::<usize>(cx);
 7642                let all_selections_were_entire_line =
 7643                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7644                let first_selection_indent_column =
 7645                    clipboard_selections.first().map(|s| s.first_line_indent);
 7646                if clipboard_selections.len() != old_selections.len() {
 7647                    clipboard_selections.drain(..);
 7648                }
 7649                let cursor_offset = this.selections.last::<usize>(cx).head();
 7650                let mut auto_indent_on_paste = true;
 7651
 7652                this.buffer.update(cx, |buffer, cx| {
 7653                    let snapshot = buffer.read(cx);
 7654                    auto_indent_on_paste =
 7655                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7656
 7657                    let mut start_offset = 0;
 7658                    let mut edits = Vec::new();
 7659                    let mut original_indent_columns = Vec::new();
 7660                    for (ix, selection) in old_selections.iter().enumerate() {
 7661                        let to_insert;
 7662                        let entire_line;
 7663                        let original_indent_column;
 7664                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7665                            let end_offset = start_offset + clipboard_selection.len;
 7666                            to_insert = &clipboard_text[start_offset..end_offset];
 7667                            entire_line = clipboard_selection.is_entire_line;
 7668                            start_offset = end_offset + 1;
 7669                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7670                        } else {
 7671                            to_insert = clipboard_text.as_str();
 7672                            entire_line = all_selections_were_entire_line;
 7673                            original_indent_column = first_selection_indent_column
 7674                        }
 7675
 7676                        // If the corresponding selection was empty when this slice of the
 7677                        // clipboard text was written, then the entire line containing the
 7678                        // selection was copied. If this selection is also currently empty,
 7679                        // then paste the line before the current line of the buffer.
 7680                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7681                            let column = selection.start.to_point(&snapshot).column as usize;
 7682                            let line_start = selection.start - column;
 7683                            line_start..line_start
 7684                        } else {
 7685                            selection.range()
 7686                        };
 7687
 7688                        edits.push((range, to_insert));
 7689                        original_indent_columns.extend(original_indent_column);
 7690                    }
 7691                    drop(snapshot);
 7692
 7693                    buffer.edit(
 7694                        edits,
 7695                        if auto_indent_on_paste {
 7696                            Some(AutoindentMode::Block {
 7697                                original_indent_columns,
 7698                            })
 7699                        } else {
 7700                            None
 7701                        },
 7702                        cx,
 7703                    );
 7704                });
 7705
 7706                let selections = this.selections.all::<usize>(cx);
 7707                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7708                    s.select(selections)
 7709                });
 7710            } else {
 7711                this.insert(&clipboard_text, window, cx);
 7712            }
 7713        });
 7714    }
 7715
 7716    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7717        if let Some(item) = cx.read_from_clipboard() {
 7718            let entries = item.entries();
 7719
 7720            match entries.first() {
 7721                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7722                // of all the pasted entries.
 7723                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7724                    .do_paste(
 7725                        clipboard_string.text(),
 7726                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7727                        true,
 7728                        window,
 7729                        cx,
 7730                    ),
 7731                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7732            }
 7733        }
 7734    }
 7735
 7736    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7737        if self.read_only(cx) {
 7738            return;
 7739        }
 7740
 7741        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7742            if let Some((selections, _)) =
 7743                self.selection_history.transaction(transaction_id).cloned()
 7744            {
 7745                self.change_selections(None, window, cx, |s| {
 7746                    s.select_anchors(selections.to_vec());
 7747                });
 7748            }
 7749            self.request_autoscroll(Autoscroll::fit(), cx);
 7750            self.unmark_text(window, cx);
 7751            self.refresh_inline_completion(true, false, window, cx);
 7752            cx.emit(EditorEvent::Edited { transaction_id });
 7753            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7754        }
 7755    }
 7756
 7757    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7758        if self.read_only(cx) {
 7759            return;
 7760        }
 7761
 7762        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7763            if let Some((_, Some(selections))) =
 7764                self.selection_history.transaction(transaction_id).cloned()
 7765            {
 7766                self.change_selections(None, window, cx, |s| {
 7767                    s.select_anchors(selections.to_vec());
 7768                });
 7769            }
 7770            self.request_autoscroll(Autoscroll::fit(), cx);
 7771            self.unmark_text(window, cx);
 7772            self.refresh_inline_completion(true, false, window, cx);
 7773            cx.emit(EditorEvent::Edited { transaction_id });
 7774        }
 7775    }
 7776
 7777    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7778        self.buffer
 7779            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7780    }
 7781
 7782    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7783        self.buffer
 7784            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7785    }
 7786
 7787    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7788        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7789            let line_mode = s.line_mode;
 7790            s.move_with(|map, selection| {
 7791                let cursor = if selection.is_empty() && !line_mode {
 7792                    movement::left(map, selection.start)
 7793                } else {
 7794                    selection.start
 7795                };
 7796                selection.collapse_to(cursor, SelectionGoal::None);
 7797            });
 7798        })
 7799    }
 7800
 7801    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7802        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7803            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7804        })
 7805    }
 7806
 7807    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7809            let line_mode = s.line_mode;
 7810            s.move_with(|map, selection| {
 7811                let cursor = if selection.is_empty() && !line_mode {
 7812                    movement::right(map, selection.end)
 7813                } else {
 7814                    selection.end
 7815                };
 7816                selection.collapse_to(cursor, SelectionGoal::None)
 7817            });
 7818        })
 7819    }
 7820
 7821    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7822        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7823            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7824        })
 7825    }
 7826
 7827    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7828        if self.take_rename(true, window, cx).is_some() {
 7829            return;
 7830        }
 7831
 7832        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7833            cx.propagate();
 7834            return;
 7835        }
 7836
 7837        let text_layout_details = &self.text_layout_details(window);
 7838        let selection_count = self.selections.count();
 7839        let first_selection = self.selections.first_anchor();
 7840
 7841        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7842            let line_mode = s.line_mode;
 7843            s.move_with(|map, selection| {
 7844                if !selection.is_empty() && !line_mode {
 7845                    selection.goal = SelectionGoal::None;
 7846                }
 7847                let (cursor, goal) = movement::up(
 7848                    map,
 7849                    selection.start,
 7850                    selection.goal,
 7851                    false,
 7852                    text_layout_details,
 7853                );
 7854                selection.collapse_to(cursor, goal);
 7855            });
 7856        });
 7857
 7858        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7859        {
 7860            cx.propagate();
 7861        }
 7862    }
 7863
 7864    pub fn move_up_by_lines(
 7865        &mut self,
 7866        action: &MoveUpByLines,
 7867        window: &mut Window,
 7868        cx: &mut Context<Self>,
 7869    ) {
 7870        if self.take_rename(true, window, cx).is_some() {
 7871            return;
 7872        }
 7873
 7874        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7875            cx.propagate();
 7876            return;
 7877        }
 7878
 7879        let text_layout_details = &self.text_layout_details(window);
 7880
 7881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7882            let line_mode = s.line_mode;
 7883            s.move_with(|map, selection| {
 7884                if !selection.is_empty() && !line_mode {
 7885                    selection.goal = SelectionGoal::None;
 7886                }
 7887                let (cursor, goal) = movement::up_by_rows(
 7888                    map,
 7889                    selection.start,
 7890                    action.lines,
 7891                    selection.goal,
 7892                    false,
 7893                    text_layout_details,
 7894                );
 7895                selection.collapse_to(cursor, goal);
 7896            });
 7897        })
 7898    }
 7899
 7900    pub fn move_down_by_lines(
 7901        &mut self,
 7902        action: &MoveDownByLines,
 7903        window: &mut Window,
 7904        cx: &mut Context<Self>,
 7905    ) {
 7906        if self.take_rename(true, window, cx).is_some() {
 7907            return;
 7908        }
 7909
 7910        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7911            cx.propagate();
 7912            return;
 7913        }
 7914
 7915        let text_layout_details = &self.text_layout_details(window);
 7916
 7917        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7918            let line_mode = s.line_mode;
 7919            s.move_with(|map, selection| {
 7920                if !selection.is_empty() && !line_mode {
 7921                    selection.goal = SelectionGoal::None;
 7922                }
 7923                let (cursor, goal) = movement::down_by_rows(
 7924                    map,
 7925                    selection.start,
 7926                    action.lines,
 7927                    selection.goal,
 7928                    false,
 7929                    text_layout_details,
 7930                );
 7931                selection.collapse_to(cursor, goal);
 7932            });
 7933        })
 7934    }
 7935
 7936    pub fn select_down_by_lines(
 7937        &mut self,
 7938        action: &SelectDownByLines,
 7939        window: &mut Window,
 7940        cx: &mut Context<Self>,
 7941    ) {
 7942        let text_layout_details = &self.text_layout_details(window);
 7943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7944            s.move_heads_with(|map, head, goal| {
 7945                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7946            })
 7947        })
 7948    }
 7949
 7950    pub fn select_up_by_lines(
 7951        &mut self,
 7952        action: &SelectUpByLines,
 7953        window: &mut Window,
 7954        cx: &mut Context<Self>,
 7955    ) {
 7956        let text_layout_details = &self.text_layout_details(window);
 7957        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7958            s.move_heads_with(|map, head, goal| {
 7959                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7960            })
 7961        })
 7962    }
 7963
 7964    pub fn select_page_up(
 7965        &mut self,
 7966        _: &SelectPageUp,
 7967        window: &mut Window,
 7968        cx: &mut Context<Self>,
 7969    ) {
 7970        let Some(row_count) = self.visible_row_count() else {
 7971            return;
 7972        };
 7973
 7974        let text_layout_details = &self.text_layout_details(window);
 7975
 7976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7977            s.move_heads_with(|map, head, goal| {
 7978                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7979            })
 7980        })
 7981    }
 7982
 7983    pub fn move_page_up(
 7984        &mut self,
 7985        action: &MovePageUp,
 7986        window: &mut Window,
 7987        cx: &mut Context<Self>,
 7988    ) {
 7989        if self.take_rename(true, window, cx).is_some() {
 7990            return;
 7991        }
 7992
 7993        if self
 7994            .context_menu
 7995            .borrow_mut()
 7996            .as_mut()
 7997            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7998            .unwrap_or(false)
 7999        {
 8000            return;
 8001        }
 8002
 8003        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8004            cx.propagate();
 8005            return;
 8006        }
 8007
 8008        let Some(row_count) = self.visible_row_count() else {
 8009            return;
 8010        };
 8011
 8012        let autoscroll = if action.center_cursor {
 8013            Autoscroll::center()
 8014        } else {
 8015            Autoscroll::fit()
 8016        };
 8017
 8018        let text_layout_details = &self.text_layout_details(window);
 8019
 8020        self.change_selections(Some(autoscroll), window, cx, |s| {
 8021            let line_mode = s.line_mode;
 8022            s.move_with(|map, selection| {
 8023                if !selection.is_empty() && !line_mode {
 8024                    selection.goal = SelectionGoal::None;
 8025                }
 8026                let (cursor, goal) = movement::up_by_rows(
 8027                    map,
 8028                    selection.end,
 8029                    row_count,
 8030                    selection.goal,
 8031                    false,
 8032                    text_layout_details,
 8033                );
 8034                selection.collapse_to(cursor, goal);
 8035            });
 8036        });
 8037    }
 8038
 8039    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8040        let text_layout_details = &self.text_layout_details(window);
 8041        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8042            s.move_heads_with(|map, head, goal| {
 8043                movement::up(map, head, goal, false, text_layout_details)
 8044            })
 8045        })
 8046    }
 8047
 8048    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8049        self.take_rename(true, window, cx);
 8050
 8051        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8052            cx.propagate();
 8053            return;
 8054        }
 8055
 8056        let text_layout_details = &self.text_layout_details(window);
 8057        let selection_count = self.selections.count();
 8058        let first_selection = self.selections.first_anchor();
 8059
 8060        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8061            let line_mode = s.line_mode;
 8062            s.move_with(|map, selection| {
 8063                if !selection.is_empty() && !line_mode {
 8064                    selection.goal = SelectionGoal::None;
 8065                }
 8066                let (cursor, goal) = movement::down(
 8067                    map,
 8068                    selection.end,
 8069                    selection.goal,
 8070                    false,
 8071                    text_layout_details,
 8072                );
 8073                selection.collapse_to(cursor, goal);
 8074            });
 8075        });
 8076
 8077        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8078        {
 8079            cx.propagate();
 8080        }
 8081    }
 8082
 8083    pub fn select_page_down(
 8084        &mut self,
 8085        _: &SelectPageDown,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) {
 8089        let Some(row_count) = self.visible_row_count() else {
 8090            return;
 8091        };
 8092
 8093        let text_layout_details = &self.text_layout_details(window);
 8094
 8095        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8096            s.move_heads_with(|map, head, goal| {
 8097                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8098            })
 8099        })
 8100    }
 8101
 8102    pub fn move_page_down(
 8103        &mut self,
 8104        action: &MovePageDown,
 8105        window: &mut Window,
 8106        cx: &mut Context<Self>,
 8107    ) {
 8108        if self.take_rename(true, window, cx).is_some() {
 8109            return;
 8110        }
 8111
 8112        if self
 8113            .context_menu
 8114            .borrow_mut()
 8115            .as_mut()
 8116            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8117            .unwrap_or(false)
 8118        {
 8119            return;
 8120        }
 8121
 8122        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8123            cx.propagate();
 8124            return;
 8125        }
 8126
 8127        let Some(row_count) = self.visible_row_count() else {
 8128            return;
 8129        };
 8130
 8131        let autoscroll = if action.center_cursor {
 8132            Autoscroll::center()
 8133        } else {
 8134            Autoscroll::fit()
 8135        };
 8136
 8137        let text_layout_details = &self.text_layout_details(window);
 8138        self.change_selections(Some(autoscroll), window, cx, |s| {
 8139            let line_mode = s.line_mode;
 8140            s.move_with(|map, selection| {
 8141                if !selection.is_empty() && !line_mode {
 8142                    selection.goal = SelectionGoal::None;
 8143                }
 8144                let (cursor, goal) = movement::down_by_rows(
 8145                    map,
 8146                    selection.end,
 8147                    row_count,
 8148                    selection.goal,
 8149                    false,
 8150                    text_layout_details,
 8151                );
 8152                selection.collapse_to(cursor, goal);
 8153            });
 8154        });
 8155    }
 8156
 8157    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8158        let text_layout_details = &self.text_layout_details(window);
 8159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8160            s.move_heads_with(|map, head, goal| {
 8161                movement::down(map, head, goal, false, text_layout_details)
 8162            })
 8163        });
 8164    }
 8165
 8166    pub fn context_menu_first(
 8167        &mut self,
 8168        _: &ContextMenuFirst,
 8169        _window: &mut Window,
 8170        cx: &mut Context<Self>,
 8171    ) {
 8172        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8173            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8174        }
 8175    }
 8176
 8177    pub fn context_menu_prev(
 8178        &mut self,
 8179        _: &ContextMenuPrev,
 8180        _window: &mut Window,
 8181        cx: &mut Context<Self>,
 8182    ) {
 8183        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8184            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8185        }
 8186    }
 8187
 8188    pub fn context_menu_next(
 8189        &mut self,
 8190        _: &ContextMenuNext,
 8191        _window: &mut Window,
 8192        cx: &mut Context<Self>,
 8193    ) {
 8194        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8195            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8196        }
 8197    }
 8198
 8199    pub fn context_menu_last(
 8200        &mut self,
 8201        _: &ContextMenuLast,
 8202        _window: &mut Window,
 8203        cx: &mut Context<Self>,
 8204    ) {
 8205        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8206            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8207        }
 8208    }
 8209
 8210    pub fn move_to_previous_word_start(
 8211        &mut self,
 8212        _: &MoveToPreviousWordStart,
 8213        window: &mut Window,
 8214        cx: &mut Context<Self>,
 8215    ) {
 8216        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8217            s.move_cursors_with(|map, head, _| {
 8218                (
 8219                    movement::previous_word_start(map, head),
 8220                    SelectionGoal::None,
 8221                )
 8222            });
 8223        })
 8224    }
 8225
 8226    pub fn move_to_previous_subword_start(
 8227        &mut self,
 8228        _: &MoveToPreviousSubwordStart,
 8229        window: &mut Window,
 8230        cx: &mut Context<Self>,
 8231    ) {
 8232        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8233            s.move_cursors_with(|map, head, _| {
 8234                (
 8235                    movement::previous_subword_start(map, head),
 8236                    SelectionGoal::None,
 8237                )
 8238            });
 8239        })
 8240    }
 8241
 8242    pub fn select_to_previous_word_start(
 8243        &mut self,
 8244        _: &SelectToPreviousWordStart,
 8245        window: &mut Window,
 8246        cx: &mut Context<Self>,
 8247    ) {
 8248        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8249            s.move_heads_with(|map, head, _| {
 8250                (
 8251                    movement::previous_word_start(map, head),
 8252                    SelectionGoal::None,
 8253                )
 8254            });
 8255        })
 8256    }
 8257
 8258    pub fn select_to_previous_subword_start(
 8259        &mut self,
 8260        _: &SelectToPreviousSubwordStart,
 8261        window: &mut Window,
 8262        cx: &mut Context<Self>,
 8263    ) {
 8264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8265            s.move_heads_with(|map, head, _| {
 8266                (
 8267                    movement::previous_subword_start(map, head),
 8268                    SelectionGoal::None,
 8269                )
 8270            });
 8271        })
 8272    }
 8273
 8274    pub fn delete_to_previous_word_start(
 8275        &mut self,
 8276        action: &DeleteToPreviousWordStart,
 8277        window: &mut Window,
 8278        cx: &mut Context<Self>,
 8279    ) {
 8280        self.transact(window, cx, |this, window, cx| {
 8281            this.select_autoclose_pair(window, cx);
 8282            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8283                let line_mode = s.line_mode;
 8284                s.move_with(|map, selection| {
 8285                    if selection.is_empty() && !line_mode {
 8286                        let cursor = if action.ignore_newlines {
 8287                            movement::previous_word_start(map, selection.head())
 8288                        } else {
 8289                            movement::previous_word_start_or_newline(map, selection.head())
 8290                        };
 8291                        selection.set_head(cursor, SelectionGoal::None);
 8292                    }
 8293                });
 8294            });
 8295            this.insert("", window, cx);
 8296        });
 8297    }
 8298
 8299    pub fn delete_to_previous_subword_start(
 8300        &mut self,
 8301        _: &DeleteToPreviousSubwordStart,
 8302        window: &mut Window,
 8303        cx: &mut Context<Self>,
 8304    ) {
 8305        self.transact(window, cx, |this, window, cx| {
 8306            this.select_autoclose_pair(window, cx);
 8307            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8308                let line_mode = s.line_mode;
 8309                s.move_with(|map, selection| {
 8310                    if selection.is_empty() && !line_mode {
 8311                        let cursor = movement::previous_subword_start(map, selection.head());
 8312                        selection.set_head(cursor, SelectionGoal::None);
 8313                    }
 8314                });
 8315            });
 8316            this.insert("", window, cx);
 8317        });
 8318    }
 8319
 8320    pub fn move_to_next_word_end(
 8321        &mut self,
 8322        _: &MoveToNextWordEnd,
 8323        window: &mut Window,
 8324        cx: &mut Context<Self>,
 8325    ) {
 8326        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8327            s.move_cursors_with(|map, head, _| {
 8328                (movement::next_word_end(map, head), SelectionGoal::None)
 8329            });
 8330        })
 8331    }
 8332
 8333    pub fn move_to_next_subword_end(
 8334        &mut self,
 8335        _: &MoveToNextSubwordEnd,
 8336        window: &mut Window,
 8337        cx: &mut Context<Self>,
 8338    ) {
 8339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8340            s.move_cursors_with(|map, head, _| {
 8341                (movement::next_subword_end(map, head), SelectionGoal::None)
 8342            });
 8343        })
 8344    }
 8345
 8346    pub fn select_to_next_word_end(
 8347        &mut self,
 8348        _: &SelectToNextWordEnd,
 8349        window: &mut Window,
 8350        cx: &mut Context<Self>,
 8351    ) {
 8352        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8353            s.move_heads_with(|map, head, _| {
 8354                (movement::next_word_end(map, head), SelectionGoal::None)
 8355            });
 8356        })
 8357    }
 8358
 8359    pub fn select_to_next_subword_end(
 8360        &mut self,
 8361        _: &SelectToNextSubwordEnd,
 8362        window: &mut Window,
 8363        cx: &mut Context<Self>,
 8364    ) {
 8365        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8366            s.move_heads_with(|map, head, _| {
 8367                (movement::next_subword_end(map, head), SelectionGoal::None)
 8368            });
 8369        })
 8370    }
 8371
 8372    pub fn delete_to_next_word_end(
 8373        &mut self,
 8374        action: &DeleteToNextWordEnd,
 8375        window: &mut Window,
 8376        cx: &mut Context<Self>,
 8377    ) {
 8378        self.transact(window, cx, |this, window, cx| {
 8379            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8380                let line_mode = s.line_mode;
 8381                s.move_with(|map, selection| {
 8382                    if selection.is_empty() && !line_mode {
 8383                        let cursor = if action.ignore_newlines {
 8384                            movement::next_word_end(map, selection.head())
 8385                        } else {
 8386                            movement::next_word_end_or_newline(map, selection.head())
 8387                        };
 8388                        selection.set_head(cursor, SelectionGoal::None);
 8389                    }
 8390                });
 8391            });
 8392            this.insert("", window, cx);
 8393        });
 8394    }
 8395
 8396    pub fn delete_to_next_subword_end(
 8397        &mut self,
 8398        _: &DeleteToNextSubwordEnd,
 8399        window: &mut Window,
 8400        cx: &mut Context<Self>,
 8401    ) {
 8402        self.transact(window, cx, |this, window, cx| {
 8403            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8404                s.move_with(|map, selection| {
 8405                    if selection.is_empty() {
 8406                        let cursor = movement::next_subword_end(map, selection.head());
 8407                        selection.set_head(cursor, SelectionGoal::None);
 8408                    }
 8409                });
 8410            });
 8411            this.insert("", window, cx);
 8412        });
 8413    }
 8414
 8415    pub fn move_to_beginning_of_line(
 8416        &mut self,
 8417        action: &MoveToBeginningOfLine,
 8418        window: &mut Window,
 8419        cx: &mut Context<Self>,
 8420    ) {
 8421        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8422            s.move_cursors_with(|map, head, _| {
 8423                (
 8424                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8425                    SelectionGoal::None,
 8426                )
 8427            });
 8428        })
 8429    }
 8430
 8431    pub fn select_to_beginning_of_line(
 8432        &mut self,
 8433        action: &SelectToBeginningOfLine,
 8434        window: &mut Window,
 8435        cx: &mut Context<Self>,
 8436    ) {
 8437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8438            s.move_heads_with(|map, head, _| {
 8439                (
 8440                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8441                    SelectionGoal::None,
 8442                )
 8443            });
 8444        });
 8445    }
 8446
 8447    pub fn delete_to_beginning_of_line(
 8448        &mut self,
 8449        _: &DeleteToBeginningOfLine,
 8450        window: &mut Window,
 8451        cx: &mut Context<Self>,
 8452    ) {
 8453        self.transact(window, cx, |this, window, cx| {
 8454            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8455                s.move_with(|_, selection| {
 8456                    selection.reversed = true;
 8457                });
 8458            });
 8459
 8460            this.select_to_beginning_of_line(
 8461                &SelectToBeginningOfLine {
 8462                    stop_at_soft_wraps: false,
 8463                },
 8464                window,
 8465                cx,
 8466            );
 8467            this.backspace(&Backspace, window, cx);
 8468        });
 8469    }
 8470
 8471    pub fn move_to_end_of_line(
 8472        &mut self,
 8473        action: &MoveToEndOfLine,
 8474        window: &mut Window,
 8475        cx: &mut Context<Self>,
 8476    ) {
 8477        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8478            s.move_cursors_with(|map, head, _| {
 8479                (
 8480                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8481                    SelectionGoal::None,
 8482                )
 8483            });
 8484        })
 8485    }
 8486
 8487    pub fn select_to_end_of_line(
 8488        &mut self,
 8489        action: &SelectToEndOfLine,
 8490        window: &mut Window,
 8491        cx: &mut Context<Self>,
 8492    ) {
 8493        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8494            s.move_heads_with(|map, head, _| {
 8495                (
 8496                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8497                    SelectionGoal::None,
 8498                )
 8499            });
 8500        })
 8501    }
 8502
 8503    pub fn delete_to_end_of_line(
 8504        &mut self,
 8505        _: &DeleteToEndOfLine,
 8506        window: &mut Window,
 8507        cx: &mut Context<Self>,
 8508    ) {
 8509        self.transact(window, cx, |this, window, cx| {
 8510            this.select_to_end_of_line(
 8511                &SelectToEndOfLine {
 8512                    stop_at_soft_wraps: false,
 8513                },
 8514                window,
 8515                cx,
 8516            );
 8517            this.delete(&Delete, window, cx);
 8518        });
 8519    }
 8520
 8521    pub fn cut_to_end_of_line(
 8522        &mut self,
 8523        _: &CutToEndOfLine,
 8524        window: &mut Window,
 8525        cx: &mut Context<Self>,
 8526    ) {
 8527        self.transact(window, cx, |this, window, cx| {
 8528            this.select_to_end_of_line(
 8529                &SelectToEndOfLine {
 8530                    stop_at_soft_wraps: false,
 8531                },
 8532                window,
 8533                cx,
 8534            );
 8535            this.cut(&Cut, window, cx);
 8536        });
 8537    }
 8538
 8539    pub fn move_to_start_of_paragraph(
 8540        &mut self,
 8541        _: &MoveToStartOfParagraph,
 8542        window: &mut Window,
 8543        cx: &mut Context<Self>,
 8544    ) {
 8545        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8546            cx.propagate();
 8547            return;
 8548        }
 8549
 8550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8551            s.move_with(|map, selection| {
 8552                selection.collapse_to(
 8553                    movement::start_of_paragraph(map, selection.head(), 1),
 8554                    SelectionGoal::None,
 8555                )
 8556            });
 8557        })
 8558    }
 8559
 8560    pub fn move_to_end_of_paragraph(
 8561        &mut self,
 8562        _: &MoveToEndOfParagraph,
 8563        window: &mut Window,
 8564        cx: &mut Context<Self>,
 8565    ) {
 8566        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8567            cx.propagate();
 8568            return;
 8569        }
 8570
 8571        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8572            s.move_with(|map, selection| {
 8573                selection.collapse_to(
 8574                    movement::end_of_paragraph(map, selection.head(), 1),
 8575                    SelectionGoal::None,
 8576                )
 8577            });
 8578        })
 8579    }
 8580
 8581    pub fn select_to_start_of_paragraph(
 8582        &mut self,
 8583        _: &SelectToStartOfParagraph,
 8584        window: &mut Window,
 8585        cx: &mut Context<Self>,
 8586    ) {
 8587        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8588            cx.propagate();
 8589            return;
 8590        }
 8591
 8592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8593            s.move_heads_with(|map, head, _| {
 8594                (
 8595                    movement::start_of_paragraph(map, head, 1),
 8596                    SelectionGoal::None,
 8597                )
 8598            });
 8599        })
 8600    }
 8601
 8602    pub fn select_to_end_of_paragraph(
 8603        &mut self,
 8604        _: &SelectToEndOfParagraph,
 8605        window: &mut Window,
 8606        cx: &mut Context<Self>,
 8607    ) {
 8608        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8609            cx.propagate();
 8610            return;
 8611        }
 8612
 8613        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8614            s.move_heads_with(|map, head, _| {
 8615                (
 8616                    movement::end_of_paragraph(map, head, 1),
 8617                    SelectionGoal::None,
 8618                )
 8619            });
 8620        })
 8621    }
 8622
 8623    pub fn move_to_beginning(
 8624        &mut self,
 8625        _: &MoveToBeginning,
 8626        window: &mut Window,
 8627        cx: &mut Context<Self>,
 8628    ) {
 8629        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8630            cx.propagate();
 8631            return;
 8632        }
 8633
 8634        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8635            s.select_ranges(vec![0..0]);
 8636        });
 8637    }
 8638
 8639    pub fn select_to_beginning(
 8640        &mut self,
 8641        _: &SelectToBeginning,
 8642        window: &mut Window,
 8643        cx: &mut Context<Self>,
 8644    ) {
 8645        let mut selection = self.selections.last::<Point>(cx);
 8646        selection.set_head(Point::zero(), SelectionGoal::None);
 8647
 8648        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8649            s.select(vec![selection]);
 8650        });
 8651    }
 8652
 8653    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8654        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8655            cx.propagate();
 8656            return;
 8657        }
 8658
 8659        let cursor = self.buffer.read(cx).read(cx).len();
 8660        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8661            s.select_ranges(vec![cursor..cursor])
 8662        });
 8663    }
 8664
 8665    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8666        self.nav_history = nav_history;
 8667    }
 8668
 8669    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8670        self.nav_history.as_ref()
 8671    }
 8672
 8673    fn push_to_nav_history(
 8674        &mut self,
 8675        cursor_anchor: Anchor,
 8676        new_position: Option<Point>,
 8677        cx: &mut Context<Self>,
 8678    ) {
 8679        if let Some(nav_history) = self.nav_history.as_mut() {
 8680            let buffer = self.buffer.read(cx).read(cx);
 8681            let cursor_position = cursor_anchor.to_point(&buffer);
 8682            let scroll_state = self.scroll_manager.anchor();
 8683            let scroll_top_row = scroll_state.top_row(&buffer);
 8684            drop(buffer);
 8685
 8686            if let Some(new_position) = new_position {
 8687                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8688                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8689                    return;
 8690                }
 8691            }
 8692
 8693            nav_history.push(
 8694                Some(NavigationData {
 8695                    cursor_anchor,
 8696                    cursor_position,
 8697                    scroll_anchor: scroll_state,
 8698                    scroll_top_row,
 8699                }),
 8700                cx,
 8701            );
 8702        }
 8703    }
 8704
 8705    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8706        let buffer = self.buffer.read(cx).snapshot(cx);
 8707        let mut selection = self.selections.first::<usize>(cx);
 8708        selection.set_head(buffer.len(), SelectionGoal::None);
 8709        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8710            s.select(vec![selection]);
 8711        });
 8712    }
 8713
 8714    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8715        let end = self.buffer.read(cx).read(cx).len();
 8716        self.change_selections(None, window, cx, |s| {
 8717            s.select_ranges(vec![0..end]);
 8718        });
 8719    }
 8720
 8721    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8722        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8723        let mut selections = self.selections.all::<Point>(cx);
 8724        let max_point = display_map.buffer_snapshot.max_point();
 8725        for selection in &mut selections {
 8726            let rows = selection.spanned_rows(true, &display_map);
 8727            selection.start = Point::new(rows.start.0, 0);
 8728            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8729            selection.reversed = false;
 8730        }
 8731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8732            s.select(selections);
 8733        });
 8734    }
 8735
 8736    pub fn split_selection_into_lines(
 8737        &mut self,
 8738        _: &SplitSelectionIntoLines,
 8739        window: &mut Window,
 8740        cx: &mut Context<Self>,
 8741    ) {
 8742        let mut to_unfold = Vec::new();
 8743        let mut new_selection_ranges = Vec::new();
 8744        {
 8745            let selections = self.selections.all::<Point>(cx);
 8746            let buffer = self.buffer.read(cx).read(cx);
 8747            for selection in selections {
 8748                for row in selection.start.row..selection.end.row {
 8749                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8750                    new_selection_ranges.push(cursor..cursor);
 8751                }
 8752                new_selection_ranges.push(selection.end..selection.end);
 8753                to_unfold.push(selection.start..selection.end);
 8754            }
 8755        }
 8756        self.unfold_ranges(&to_unfold, true, true, cx);
 8757        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8758            s.select_ranges(new_selection_ranges);
 8759        });
 8760    }
 8761
 8762    pub fn add_selection_above(
 8763        &mut self,
 8764        _: &AddSelectionAbove,
 8765        window: &mut Window,
 8766        cx: &mut Context<Self>,
 8767    ) {
 8768        self.add_selection(true, window, cx);
 8769    }
 8770
 8771    pub fn add_selection_below(
 8772        &mut self,
 8773        _: &AddSelectionBelow,
 8774        window: &mut Window,
 8775        cx: &mut Context<Self>,
 8776    ) {
 8777        self.add_selection(false, window, cx);
 8778    }
 8779
 8780    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8781        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8782        let mut selections = self.selections.all::<Point>(cx);
 8783        let text_layout_details = self.text_layout_details(window);
 8784        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8785            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8786            let range = oldest_selection.display_range(&display_map).sorted();
 8787
 8788            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8789            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8790            let positions = start_x.min(end_x)..start_x.max(end_x);
 8791
 8792            selections.clear();
 8793            let mut stack = Vec::new();
 8794            for row in range.start.row().0..=range.end.row().0 {
 8795                if let Some(selection) = self.selections.build_columnar_selection(
 8796                    &display_map,
 8797                    DisplayRow(row),
 8798                    &positions,
 8799                    oldest_selection.reversed,
 8800                    &text_layout_details,
 8801                ) {
 8802                    stack.push(selection.id);
 8803                    selections.push(selection);
 8804                }
 8805            }
 8806
 8807            if above {
 8808                stack.reverse();
 8809            }
 8810
 8811            AddSelectionsState { above, stack }
 8812        });
 8813
 8814        let last_added_selection = *state.stack.last().unwrap();
 8815        let mut new_selections = Vec::new();
 8816        if above == state.above {
 8817            let end_row = if above {
 8818                DisplayRow(0)
 8819            } else {
 8820                display_map.max_point().row()
 8821            };
 8822
 8823            'outer: for selection in selections {
 8824                if selection.id == last_added_selection {
 8825                    let range = selection.display_range(&display_map).sorted();
 8826                    debug_assert_eq!(range.start.row(), range.end.row());
 8827                    let mut row = range.start.row();
 8828                    let positions =
 8829                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8830                            px(start)..px(end)
 8831                        } else {
 8832                            let start_x =
 8833                                display_map.x_for_display_point(range.start, &text_layout_details);
 8834                            let end_x =
 8835                                display_map.x_for_display_point(range.end, &text_layout_details);
 8836                            start_x.min(end_x)..start_x.max(end_x)
 8837                        };
 8838
 8839                    while row != end_row {
 8840                        if above {
 8841                            row.0 -= 1;
 8842                        } else {
 8843                            row.0 += 1;
 8844                        }
 8845
 8846                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8847                            &display_map,
 8848                            row,
 8849                            &positions,
 8850                            selection.reversed,
 8851                            &text_layout_details,
 8852                        ) {
 8853                            state.stack.push(new_selection.id);
 8854                            if above {
 8855                                new_selections.push(new_selection);
 8856                                new_selections.push(selection);
 8857                            } else {
 8858                                new_selections.push(selection);
 8859                                new_selections.push(new_selection);
 8860                            }
 8861
 8862                            continue 'outer;
 8863                        }
 8864                    }
 8865                }
 8866
 8867                new_selections.push(selection);
 8868            }
 8869        } else {
 8870            new_selections = selections;
 8871            new_selections.retain(|s| s.id != last_added_selection);
 8872            state.stack.pop();
 8873        }
 8874
 8875        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8876            s.select(new_selections);
 8877        });
 8878        if state.stack.len() > 1 {
 8879            self.add_selections_state = Some(state);
 8880        }
 8881    }
 8882
 8883    pub fn select_next_match_internal(
 8884        &mut self,
 8885        display_map: &DisplaySnapshot,
 8886        replace_newest: bool,
 8887        autoscroll: Option<Autoscroll>,
 8888        window: &mut Window,
 8889        cx: &mut Context<Self>,
 8890    ) -> Result<()> {
 8891        fn select_next_match_ranges(
 8892            this: &mut Editor,
 8893            range: Range<usize>,
 8894            replace_newest: bool,
 8895            auto_scroll: Option<Autoscroll>,
 8896            window: &mut Window,
 8897            cx: &mut Context<Editor>,
 8898        ) {
 8899            this.unfold_ranges(&[range.clone()], false, true, cx);
 8900            this.change_selections(auto_scroll, window, cx, |s| {
 8901                if replace_newest {
 8902                    s.delete(s.newest_anchor().id);
 8903                }
 8904                s.insert_range(range.clone());
 8905            });
 8906        }
 8907
 8908        let buffer = &display_map.buffer_snapshot;
 8909        let mut selections = self.selections.all::<usize>(cx);
 8910        if let Some(mut select_next_state) = self.select_next_state.take() {
 8911            let query = &select_next_state.query;
 8912            if !select_next_state.done {
 8913                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8914                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8915                let mut next_selected_range = None;
 8916
 8917                let bytes_after_last_selection =
 8918                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8919                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8920                let query_matches = query
 8921                    .stream_find_iter(bytes_after_last_selection)
 8922                    .map(|result| (last_selection.end, result))
 8923                    .chain(
 8924                        query
 8925                            .stream_find_iter(bytes_before_first_selection)
 8926                            .map(|result| (0, result)),
 8927                    );
 8928
 8929                for (start_offset, query_match) in query_matches {
 8930                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8931                    let offset_range =
 8932                        start_offset + query_match.start()..start_offset + query_match.end();
 8933                    let display_range = offset_range.start.to_display_point(display_map)
 8934                        ..offset_range.end.to_display_point(display_map);
 8935
 8936                    if !select_next_state.wordwise
 8937                        || (!movement::is_inside_word(display_map, display_range.start)
 8938                            && !movement::is_inside_word(display_map, display_range.end))
 8939                    {
 8940                        // TODO: This is n^2, because we might check all the selections
 8941                        if !selections
 8942                            .iter()
 8943                            .any(|selection| selection.range().overlaps(&offset_range))
 8944                        {
 8945                            next_selected_range = Some(offset_range);
 8946                            break;
 8947                        }
 8948                    }
 8949                }
 8950
 8951                if let Some(next_selected_range) = next_selected_range {
 8952                    select_next_match_ranges(
 8953                        self,
 8954                        next_selected_range,
 8955                        replace_newest,
 8956                        autoscroll,
 8957                        window,
 8958                        cx,
 8959                    );
 8960                } else {
 8961                    select_next_state.done = true;
 8962                }
 8963            }
 8964
 8965            self.select_next_state = Some(select_next_state);
 8966        } else {
 8967            let mut only_carets = true;
 8968            let mut same_text_selected = true;
 8969            let mut selected_text = None;
 8970
 8971            let mut selections_iter = selections.iter().peekable();
 8972            while let Some(selection) = selections_iter.next() {
 8973                if selection.start != selection.end {
 8974                    only_carets = false;
 8975                }
 8976
 8977                if same_text_selected {
 8978                    if selected_text.is_none() {
 8979                        selected_text =
 8980                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8981                    }
 8982
 8983                    if let Some(next_selection) = selections_iter.peek() {
 8984                        if next_selection.range().len() == selection.range().len() {
 8985                            let next_selected_text = buffer
 8986                                .text_for_range(next_selection.range())
 8987                                .collect::<String>();
 8988                            if Some(next_selected_text) != selected_text {
 8989                                same_text_selected = false;
 8990                                selected_text = None;
 8991                            }
 8992                        } else {
 8993                            same_text_selected = false;
 8994                            selected_text = None;
 8995                        }
 8996                    }
 8997                }
 8998            }
 8999
 9000            if only_carets {
 9001                for selection in &mut selections {
 9002                    let word_range = movement::surrounding_word(
 9003                        display_map,
 9004                        selection.start.to_display_point(display_map),
 9005                    );
 9006                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9007                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9008                    selection.goal = SelectionGoal::None;
 9009                    selection.reversed = false;
 9010                    select_next_match_ranges(
 9011                        self,
 9012                        selection.start..selection.end,
 9013                        replace_newest,
 9014                        autoscroll,
 9015                        window,
 9016                        cx,
 9017                    );
 9018                }
 9019
 9020                if selections.len() == 1 {
 9021                    let selection = selections
 9022                        .last()
 9023                        .expect("ensured that there's only one selection");
 9024                    let query = buffer
 9025                        .text_for_range(selection.start..selection.end)
 9026                        .collect::<String>();
 9027                    let is_empty = query.is_empty();
 9028                    let select_state = SelectNextState {
 9029                        query: AhoCorasick::new(&[query])?,
 9030                        wordwise: true,
 9031                        done: is_empty,
 9032                    };
 9033                    self.select_next_state = Some(select_state);
 9034                } else {
 9035                    self.select_next_state = None;
 9036                }
 9037            } else if let Some(selected_text) = selected_text {
 9038                self.select_next_state = Some(SelectNextState {
 9039                    query: AhoCorasick::new(&[selected_text])?,
 9040                    wordwise: false,
 9041                    done: false,
 9042                });
 9043                self.select_next_match_internal(
 9044                    display_map,
 9045                    replace_newest,
 9046                    autoscroll,
 9047                    window,
 9048                    cx,
 9049                )?;
 9050            }
 9051        }
 9052        Ok(())
 9053    }
 9054
 9055    pub fn select_all_matches(
 9056        &mut self,
 9057        _action: &SelectAllMatches,
 9058        window: &mut Window,
 9059        cx: &mut Context<Self>,
 9060    ) -> Result<()> {
 9061        self.push_to_selection_history();
 9062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9063
 9064        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9065        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9066            return Ok(());
 9067        };
 9068        if select_next_state.done {
 9069            return Ok(());
 9070        }
 9071
 9072        let mut new_selections = self.selections.all::<usize>(cx);
 9073
 9074        let buffer = &display_map.buffer_snapshot;
 9075        let query_matches = select_next_state
 9076            .query
 9077            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9078
 9079        for query_match in query_matches {
 9080            let query_match = query_match.unwrap(); // can only fail due to I/O
 9081            let offset_range = query_match.start()..query_match.end();
 9082            let display_range = offset_range.start.to_display_point(&display_map)
 9083                ..offset_range.end.to_display_point(&display_map);
 9084
 9085            if !select_next_state.wordwise
 9086                || (!movement::is_inside_word(&display_map, display_range.start)
 9087                    && !movement::is_inside_word(&display_map, display_range.end))
 9088            {
 9089                self.selections.change_with(cx, |selections| {
 9090                    new_selections.push(Selection {
 9091                        id: selections.new_selection_id(),
 9092                        start: offset_range.start,
 9093                        end: offset_range.end,
 9094                        reversed: false,
 9095                        goal: SelectionGoal::None,
 9096                    });
 9097                });
 9098            }
 9099        }
 9100
 9101        new_selections.sort_by_key(|selection| selection.start);
 9102        let mut ix = 0;
 9103        while ix + 1 < new_selections.len() {
 9104            let current_selection = &new_selections[ix];
 9105            let next_selection = &new_selections[ix + 1];
 9106            if current_selection.range().overlaps(&next_selection.range()) {
 9107                if current_selection.id < next_selection.id {
 9108                    new_selections.remove(ix + 1);
 9109                } else {
 9110                    new_selections.remove(ix);
 9111                }
 9112            } else {
 9113                ix += 1;
 9114            }
 9115        }
 9116
 9117        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9118
 9119        for selection in new_selections.iter_mut() {
 9120            selection.reversed = reversed;
 9121        }
 9122
 9123        select_next_state.done = true;
 9124        self.unfold_ranges(
 9125            &new_selections
 9126                .iter()
 9127                .map(|selection| selection.range())
 9128                .collect::<Vec<_>>(),
 9129            false,
 9130            false,
 9131            cx,
 9132        );
 9133        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9134            selections.select(new_selections)
 9135        });
 9136
 9137        Ok(())
 9138    }
 9139
 9140    pub fn select_next(
 9141        &mut self,
 9142        action: &SelectNext,
 9143        window: &mut Window,
 9144        cx: &mut Context<Self>,
 9145    ) -> Result<()> {
 9146        self.push_to_selection_history();
 9147        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9148        self.select_next_match_internal(
 9149            &display_map,
 9150            action.replace_newest,
 9151            Some(Autoscroll::newest()),
 9152            window,
 9153            cx,
 9154        )?;
 9155        Ok(())
 9156    }
 9157
 9158    pub fn select_previous(
 9159        &mut self,
 9160        action: &SelectPrevious,
 9161        window: &mut Window,
 9162        cx: &mut Context<Self>,
 9163    ) -> Result<()> {
 9164        self.push_to_selection_history();
 9165        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9166        let buffer = &display_map.buffer_snapshot;
 9167        let mut selections = self.selections.all::<usize>(cx);
 9168        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9169            let query = &select_prev_state.query;
 9170            if !select_prev_state.done {
 9171                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9172                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9173                let mut next_selected_range = None;
 9174                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9175                let bytes_before_last_selection =
 9176                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9177                let bytes_after_first_selection =
 9178                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9179                let query_matches = query
 9180                    .stream_find_iter(bytes_before_last_selection)
 9181                    .map(|result| (last_selection.start, result))
 9182                    .chain(
 9183                        query
 9184                            .stream_find_iter(bytes_after_first_selection)
 9185                            .map(|result| (buffer.len(), result)),
 9186                    );
 9187                for (end_offset, query_match) in query_matches {
 9188                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9189                    let offset_range =
 9190                        end_offset - query_match.end()..end_offset - query_match.start();
 9191                    let display_range = offset_range.start.to_display_point(&display_map)
 9192                        ..offset_range.end.to_display_point(&display_map);
 9193
 9194                    if !select_prev_state.wordwise
 9195                        || (!movement::is_inside_word(&display_map, display_range.start)
 9196                            && !movement::is_inside_word(&display_map, display_range.end))
 9197                    {
 9198                        next_selected_range = Some(offset_range);
 9199                        break;
 9200                    }
 9201                }
 9202
 9203                if let Some(next_selected_range) = next_selected_range {
 9204                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9205                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9206                        if action.replace_newest {
 9207                            s.delete(s.newest_anchor().id);
 9208                        }
 9209                        s.insert_range(next_selected_range);
 9210                    });
 9211                } else {
 9212                    select_prev_state.done = true;
 9213                }
 9214            }
 9215
 9216            self.select_prev_state = Some(select_prev_state);
 9217        } else {
 9218            let mut only_carets = true;
 9219            let mut same_text_selected = true;
 9220            let mut selected_text = None;
 9221
 9222            let mut selections_iter = selections.iter().peekable();
 9223            while let Some(selection) = selections_iter.next() {
 9224                if selection.start != selection.end {
 9225                    only_carets = false;
 9226                }
 9227
 9228                if same_text_selected {
 9229                    if selected_text.is_none() {
 9230                        selected_text =
 9231                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9232                    }
 9233
 9234                    if let Some(next_selection) = selections_iter.peek() {
 9235                        if next_selection.range().len() == selection.range().len() {
 9236                            let next_selected_text = buffer
 9237                                .text_for_range(next_selection.range())
 9238                                .collect::<String>();
 9239                            if Some(next_selected_text) != selected_text {
 9240                                same_text_selected = false;
 9241                                selected_text = None;
 9242                            }
 9243                        } else {
 9244                            same_text_selected = false;
 9245                            selected_text = None;
 9246                        }
 9247                    }
 9248                }
 9249            }
 9250
 9251            if only_carets {
 9252                for selection in &mut selections {
 9253                    let word_range = movement::surrounding_word(
 9254                        &display_map,
 9255                        selection.start.to_display_point(&display_map),
 9256                    );
 9257                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9258                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9259                    selection.goal = SelectionGoal::None;
 9260                    selection.reversed = false;
 9261                }
 9262                if selections.len() == 1 {
 9263                    let selection = selections
 9264                        .last()
 9265                        .expect("ensured that there's only one selection");
 9266                    let query = buffer
 9267                        .text_for_range(selection.start..selection.end)
 9268                        .collect::<String>();
 9269                    let is_empty = query.is_empty();
 9270                    let select_state = SelectNextState {
 9271                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9272                        wordwise: true,
 9273                        done: is_empty,
 9274                    };
 9275                    self.select_prev_state = Some(select_state);
 9276                } else {
 9277                    self.select_prev_state = None;
 9278                }
 9279
 9280                self.unfold_ranges(
 9281                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9282                    false,
 9283                    true,
 9284                    cx,
 9285                );
 9286                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9287                    s.select(selections);
 9288                });
 9289            } else if let Some(selected_text) = selected_text {
 9290                self.select_prev_state = Some(SelectNextState {
 9291                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9292                    wordwise: false,
 9293                    done: false,
 9294                });
 9295                self.select_previous(action, window, cx)?;
 9296            }
 9297        }
 9298        Ok(())
 9299    }
 9300
 9301    pub fn toggle_comments(
 9302        &mut self,
 9303        action: &ToggleComments,
 9304        window: &mut Window,
 9305        cx: &mut Context<Self>,
 9306    ) {
 9307        if self.read_only(cx) {
 9308            return;
 9309        }
 9310        let text_layout_details = &self.text_layout_details(window);
 9311        self.transact(window, cx, |this, window, cx| {
 9312            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9313            let mut edits = Vec::new();
 9314            let mut selection_edit_ranges = Vec::new();
 9315            let mut last_toggled_row = None;
 9316            let snapshot = this.buffer.read(cx).read(cx);
 9317            let empty_str: Arc<str> = Arc::default();
 9318            let mut suffixes_inserted = Vec::new();
 9319            let ignore_indent = action.ignore_indent;
 9320
 9321            fn comment_prefix_range(
 9322                snapshot: &MultiBufferSnapshot,
 9323                row: MultiBufferRow,
 9324                comment_prefix: &str,
 9325                comment_prefix_whitespace: &str,
 9326                ignore_indent: bool,
 9327            ) -> Range<Point> {
 9328                let indent_size = if ignore_indent {
 9329                    0
 9330                } else {
 9331                    snapshot.indent_size_for_line(row).len
 9332                };
 9333
 9334                let start = Point::new(row.0, indent_size);
 9335
 9336                let mut line_bytes = snapshot
 9337                    .bytes_in_range(start..snapshot.max_point())
 9338                    .flatten()
 9339                    .copied();
 9340
 9341                // If this line currently begins with the line comment prefix, then record
 9342                // the range containing the prefix.
 9343                if line_bytes
 9344                    .by_ref()
 9345                    .take(comment_prefix.len())
 9346                    .eq(comment_prefix.bytes())
 9347                {
 9348                    // Include any whitespace that matches the comment prefix.
 9349                    let matching_whitespace_len = line_bytes
 9350                        .zip(comment_prefix_whitespace.bytes())
 9351                        .take_while(|(a, b)| a == b)
 9352                        .count() as u32;
 9353                    let end = Point::new(
 9354                        start.row,
 9355                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9356                    );
 9357                    start..end
 9358                } else {
 9359                    start..start
 9360                }
 9361            }
 9362
 9363            fn comment_suffix_range(
 9364                snapshot: &MultiBufferSnapshot,
 9365                row: MultiBufferRow,
 9366                comment_suffix: &str,
 9367                comment_suffix_has_leading_space: bool,
 9368            ) -> Range<Point> {
 9369                let end = Point::new(row.0, snapshot.line_len(row));
 9370                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9371
 9372                let mut line_end_bytes = snapshot
 9373                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9374                    .flatten()
 9375                    .copied();
 9376
 9377                let leading_space_len = if suffix_start_column > 0
 9378                    && line_end_bytes.next() == Some(b' ')
 9379                    && comment_suffix_has_leading_space
 9380                {
 9381                    1
 9382                } else {
 9383                    0
 9384                };
 9385
 9386                // If this line currently begins with the line comment prefix, then record
 9387                // the range containing the prefix.
 9388                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9389                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9390                    start..end
 9391                } else {
 9392                    end..end
 9393                }
 9394            }
 9395
 9396            // TODO: Handle selections that cross excerpts
 9397            for selection in &mut selections {
 9398                let start_column = snapshot
 9399                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9400                    .len;
 9401                let language = if let Some(language) =
 9402                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9403                {
 9404                    language
 9405                } else {
 9406                    continue;
 9407                };
 9408
 9409                selection_edit_ranges.clear();
 9410
 9411                // If multiple selections contain a given row, avoid processing that
 9412                // row more than once.
 9413                let mut start_row = MultiBufferRow(selection.start.row);
 9414                if last_toggled_row == Some(start_row) {
 9415                    start_row = start_row.next_row();
 9416                }
 9417                let end_row =
 9418                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9419                        MultiBufferRow(selection.end.row - 1)
 9420                    } else {
 9421                        MultiBufferRow(selection.end.row)
 9422                    };
 9423                last_toggled_row = Some(end_row);
 9424
 9425                if start_row > end_row {
 9426                    continue;
 9427                }
 9428
 9429                // If the language has line comments, toggle those.
 9430                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9431
 9432                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9433                if ignore_indent {
 9434                    full_comment_prefixes = full_comment_prefixes
 9435                        .into_iter()
 9436                        .map(|s| Arc::from(s.trim_end()))
 9437                        .collect();
 9438                }
 9439
 9440                if !full_comment_prefixes.is_empty() {
 9441                    let first_prefix = full_comment_prefixes
 9442                        .first()
 9443                        .expect("prefixes is non-empty");
 9444                    let prefix_trimmed_lengths = full_comment_prefixes
 9445                        .iter()
 9446                        .map(|p| p.trim_end_matches(' ').len())
 9447                        .collect::<SmallVec<[usize; 4]>>();
 9448
 9449                    let mut all_selection_lines_are_comments = true;
 9450
 9451                    for row in start_row.0..=end_row.0 {
 9452                        let row = MultiBufferRow(row);
 9453                        if start_row < end_row && snapshot.is_line_blank(row) {
 9454                            continue;
 9455                        }
 9456
 9457                        let prefix_range = full_comment_prefixes
 9458                            .iter()
 9459                            .zip(prefix_trimmed_lengths.iter().copied())
 9460                            .map(|(prefix, trimmed_prefix_len)| {
 9461                                comment_prefix_range(
 9462                                    snapshot.deref(),
 9463                                    row,
 9464                                    &prefix[..trimmed_prefix_len],
 9465                                    &prefix[trimmed_prefix_len..],
 9466                                    ignore_indent,
 9467                                )
 9468                            })
 9469                            .max_by_key(|range| range.end.column - range.start.column)
 9470                            .expect("prefixes is non-empty");
 9471
 9472                        if prefix_range.is_empty() {
 9473                            all_selection_lines_are_comments = false;
 9474                        }
 9475
 9476                        selection_edit_ranges.push(prefix_range);
 9477                    }
 9478
 9479                    if all_selection_lines_are_comments {
 9480                        edits.extend(
 9481                            selection_edit_ranges
 9482                                .iter()
 9483                                .cloned()
 9484                                .map(|range| (range, empty_str.clone())),
 9485                        );
 9486                    } else {
 9487                        let min_column = selection_edit_ranges
 9488                            .iter()
 9489                            .map(|range| range.start.column)
 9490                            .min()
 9491                            .unwrap_or(0);
 9492                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9493                            let position = Point::new(range.start.row, min_column);
 9494                            (position..position, first_prefix.clone())
 9495                        }));
 9496                    }
 9497                } else if let Some((full_comment_prefix, comment_suffix)) =
 9498                    language.block_comment_delimiters()
 9499                {
 9500                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9501                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9502                    let prefix_range = comment_prefix_range(
 9503                        snapshot.deref(),
 9504                        start_row,
 9505                        comment_prefix,
 9506                        comment_prefix_whitespace,
 9507                        ignore_indent,
 9508                    );
 9509                    let suffix_range = comment_suffix_range(
 9510                        snapshot.deref(),
 9511                        end_row,
 9512                        comment_suffix.trim_start_matches(' '),
 9513                        comment_suffix.starts_with(' '),
 9514                    );
 9515
 9516                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9517                        edits.push((
 9518                            prefix_range.start..prefix_range.start,
 9519                            full_comment_prefix.clone(),
 9520                        ));
 9521                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9522                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9523                    } else {
 9524                        edits.push((prefix_range, empty_str.clone()));
 9525                        edits.push((suffix_range, empty_str.clone()));
 9526                    }
 9527                } else {
 9528                    continue;
 9529                }
 9530            }
 9531
 9532            drop(snapshot);
 9533            this.buffer.update(cx, |buffer, cx| {
 9534                buffer.edit(edits, None, cx);
 9535            });
 9536
 9537            // Adjust selections so that they end before any comment suffixes that
 9538            // were inserted.
 9539            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9540            let mut selections = this.selections.all::<Point>(cx);
 9541            let snapshot = this.buffer.read(cx).read(cx);
 9542            for selection in &mut selections {
 9543                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9544                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9545                        Ordering::Less => {
 9546                            suffixes_inserted.next();
 9547                            continue;
 9548                        }
 9549                        Ordering::Greater => break,
 9550                        Ordering::Equal => {
 9551                            if selection.end.column == snapshot.line_len(row) {
 9552                                if selection.is_empty() {
 9553                                    selection.start.column -= suffix_len as u32;
 9554                                }
 9555                                selection.end.column -= suffix_len as u32;
 9556                            }
 9557                            break;
 9558                        }
 9559                    }
 9560                }
 9561            }
 9562
 9563            drop(snapshot);
 9564            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9565                s.select(selections)
 9566            });
 9567
 9568            let selections = this.selections.all::<Point>(cx);
 9569            let selections_on_single_row = selections.windows(2).all(|selections| {
 9570                selections[0].start.row == selections[1].start.row
 9571                    && selections[0].end.row == selections[1].end.row
 9572                    && selections[0].start.row == selections[0].end.row
 9573            });
 9574            let selections_selecting = selections
 9575                .iter()
 9576                .any(|selection| selection.start != selection.end);
 9577            let advance_downwards = action.advance_downwards
 9578                && selections_on_single_row
 9579                && !selections_selecting
 9580                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9581
 9582            if advance_downwards {
 9583                let snapshot = this.buffer.read(cx).snapshot(cx);
 9584
 9585                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9586                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9587                        let mut point = display_point.to_point(display_snapshot);
 9588                        point.row += 1;
 9589                        point = snapshot.clip_point(point, Bias::Left);
 9590                        let display_point = point.to_display_point(display_snapshot);
 9591                        let goal = SelectionGoal::HorizontalPosition(
 9592                            display_snapshot
 9593                                .x_for_display_point(display_point, text_layout_details)
 9594                                .into(),
 9595                        );
 9596                        (display_point, goal)
 9597                    })
 9598                });
 9599            }
 9600        });
 9601    }
 9602
 9603    pub fn select_enclosing_symbol(
 9604        &mut self,
 9605        _: &SelectEnclosingSymbol,
 9606        window: &mut Window,
 9607        cx: &mut Context<Self>,
 9608    ) {
 9609        let buffer = self.buffer.read(cx).snapshot(cx);
 9610        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9611
 9612        fn update_selection(
 9613            selection: &Selection<usize>,
 9614            buffer_snap: &MultiBufferSnapshot,
 9615        ) -> Option<Selection<usize>> {
 9616            let cursor = selection.head();
 9617            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9618            for symbol in symbols.iter().rev() {
 9619                let start = symbol.range.start.to_offset(buffer_snap);
 9620                let end = symbol.range.end.to_offset(buffer_snap);
 9621                let new_range = start..end;
 9622                if start < selection.start || end > selection.end {
 9623                    return Some(Selection {
 9624                        id: selection.id,
 9625                        start: new_range.start,
 9626                        end: new_range.end,
 9627                        goal: SelectionGoal::None,
 9628                        reversed: selection.reversed,
 9629                    });
 9630                }
 9631            }
 9632            None
 9633        }
 9634
 9635        let mut selected_larger_symbol = false;
 9636        let new_selections = old_selections
 9637            .iter()
 9638            .map(|selection| match update_selection(selection, &buffer) {
 9639                Some(new_selection) => {
 9640                    if new_selection.range() != selection.range() {
 9641                        selected_larger_symbol = true;
 9642                    }
 9643                    new_selection
 9644                }
 9645                None => selection.clone(),
 9646            })
 9647            .collect::<Vec<_>>();
 9648
 9649        if selected_larger_symbol {
 9650            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9651                s.select(new_selections);
 9652            });
 9653        }
 9654    }
 9655
 9656    pub fn select_larger_syntax_node(
 9657        &mut self,
 9658        _: &SelectLargerSyntaxNode,
 9659        window: &mut Window,
 9660        cx: &mut Context<Self>,
 9661    ) {
 9662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9663        let buffer = self.buffer.read(cx).snapshot(cx);
 9664        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9665
 9666        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9667        let mut selected_larger_node = false;
 9668        let new_selections = old_selections
 9669            .iter()
 9670            .map(|selection| {
 9671                let old_range = selection.start..selection.end;
 9672                let mut new_range = old_range.clone();
 9673                let mut new_node = None;
 9674                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9675                {
 9676                    new_node = Some(node);
 9677                    new_range = containing_range;
 9678                    if !display_map.intersects_fold(new_range.start)
 9679                        && !display_map.intersects_fold(new_range.end)
 9680                    {
 9681                        break;
 9682                    }
 9683                }
 9684
 9685                if let Some(node) = new_node {
 9686                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9687                    // nodes. Parent and grandparent are also logged because this operation will not
 9688                    // visit nodes that have the same range as their parent.
 9689                    log::info!("Node: {node:?}");
 9690                    let parent = node.parent();
 9691                    log::info!("Parent: {parent:?}");
 9692                    let grandparent = parent.and_then(|x| x.parent());
 9693                    log::info!("Grandparent: {grandparent:?}");
 9694                }
 9695
 9696                selected_larger_node |= new_range != old_range;
 9697                Selection {
 9698                    id: selection.id,
 9699                    start: new_range.start,
 9700                    end: new_range.end,
 9701                    goal: SelectionGoal::None,
 9702                    reversed: selection.reversed,
 9703                }
 9704            })
 9705            .collect::<Vec<_>>();
 9706
 9707        if selected_larger_node {
 9708            stack.push(old_selections);
 9709            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9710                s.select(new_selections);
 9711            });
 9712        }
 9713        self.select_larger_syntax_node_stack = stack;
 9714    }
 9715
 9716    pub fn select_smaller_syntax_node(
 9717        &mut self,
 9718        _: &SelectSmallerSyntaxNode,
 9719        window: &mut Window,
 9720        cx: &mut Context<Self>,
 9721    ) {
 9722        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9723        if let Some(selections) = stack.pop() {
 9724            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9725                s.select(selections.to_vec());
 9726            });
 9727        }
 9728        self.select_larger_syntax_node_stack = stack;
 9729    }
 9730
 9731    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9732        if !EditorSettings::get_global(cx).gutter.runnables {
 9733            self.clear_tasks();
 9734            return Task::ready(());
 9735        }
 9736        let project = self.project.as_ref().map(Entity::downgrade);
 9737        cx.spawn_in(window, |this, mut cx| async move {
 9738            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9739            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9740                return;
 9741            };
 9742            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9743                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9744            }) else {
 9745                return;
 9746            };
 9747
 9748            let hide_runnables = project
 9749                .update(&mut cx, |project, cx| {
 9750                    // Do not display any test indicators in non-dev server remote projects.
 9751                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9752                })
 9753                .unwrap_or(true);
 9754            if hide_runnables {
 9755                return;
 9756            }
 9757            let new_rows =
 9758                cx.background_executor()
 9759                    .spawn({
 9760                        let snapshot = display_snapshot.clone();
 9761                        async move {
 9762                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9763                        }
 9764                    })
 9765                    .await;
 9766
 9767            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9768            this.update(&mut cx, |this, _| {
 9769                this.clear_tasks();
 9770                for (key, value) in rows {
 9771                    this.insert_tasks(key, value);
 9772                }
 9773            })
 9774            .ok();
 9775        })
 9776    }
 9777    fn fetch_runnable_ranges(
 9778        snapshot: &DisplaySnapshot,
 9779        range: Range<Anchor>,
 9780    ) -> Vec<language::RunnableRange> {
 9781        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9782    }
 9783
 9784    fn runnable_rows(
 9785        project: Entity<Project>,
 9786        snapshot: DisplaySnapshot,
 9787        runnable_ranges: Vec<RunnableRange>,
 9788        mut cx: AsyncWindowContext,
 9789    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9790        runnable_ranges
 9791            .into_iter()
 9792            .filter_map(|mut runnable| {
 9793                let tasks = cx
 9794                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9795                    .ok()?;
 9796                if tasks.is_empty() {
 9797                    return None;
 9798                }
 9799
 9800                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9801
 9802                let row = snapshot
 9803                    .buffer_snapshot
 9804                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9805                    .1
 9806                    .start
 9807                    .row;
 9808
 9809                let context_range =
 9810                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9811                Some((
 9812                    (runnable.buffer_id, row),
 9813                    RunnableTasks {
 9814                        templates: tasks,
 9815                        offset: MultiBufferOffset(runnable.run_range.start),
 9816                        context_range,
 9817                        column: point.column,
 9818                        extra_variables: runnable.extra_captures,
 9819                    },
 9820                ))
 9821            })
 9822            .collect()
 9823    }
 9824
 9825    fn templates_with_tags(
 9826        project: &Entity<Project>,
 9827        runnable: &mut Runnable,
 9828        cx: &mut App,
 9829    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9830        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9831            let (worktree_id, file) = project
 9832                .buffer_for_id(runnable.buffer, cx)
 9833                .and_then(|buffer| buffer.read(cx).file())
 9834                .map(|file| (file.worktree_id(cx), file.clone()))
 9835                .unzip();
 9836
 9837            (
 9838                project.task_store().read(cx).task_inventory().cloned(),
 9839                worktree_id,
 9840                file,
 9841            )
 9842        });
 9843
 9844        let tags = mem::take(&mut runnable.tags);
 9845        let mut tags: Vec<_> = tags
 9846            .into_iter()
 9847            .flat_map(|tag| {
 9848                let tag = tag.0.clone();
 9849                inventory
 9850                    .as_ref()
 9851                    .into_iter()
 9852                    .flat_map(|inventory| {
 9853                        inventory.read(cx).list_tasks(
 9854                            file.clone(),
 9855                            Some(runnable.language.clone()),
 9856                            worktree_id,
 9857                            cx,
 9858                        )
 9859                    })
 9860                    .filter(move |(_, template)| {
 9861                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9862                    })
 9863            })
 9864            .sorted_by_key(|(kind, _)| kind.to_owned())
 9865            .collect();
 9866        if let Some((leading_tag_source, _)) = tags.first() {
 9867            // Strongest source wins; if we have worktree tag binding, prefer that to
 9868            // global and language bindings;
 9869            // if we have a global binding, prefer that to language binding.
 9870            let first_mismatch = tags
 9871                .iter()
 9872                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9873            if let Some(index) = first_mismatch {
 9874                tags.truncate(index);
 9875            }
 9876        }
 9877
 9878        tags
 9879    }
 9880
 9881    pub fn move_to_enclosing_bracket(
 9882        &mut self,
 9883        _: &MoveToEnclosingBracket,
 9884        window: &mut Window,
 9885        cx: &mut Context<Self>,
 9886    ) {
 9887        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9888            s.move_offsets_with(|snapshot, selection| {
 9889                let Some(enclosing_bracket_ranges) =
 9890                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9891                else {
 9892                    return;
 9893                };
 9894
 9895                let mut best_length = usize::MAX;
 9896                let mut best_inside = false;
 9897                let mut best_in_bracket_range = false;
 9898                let mut best_destination = None;
 9899                for (open, close) in enclosing_bracket_ranges {
 9900                    let close = close.to_inclusive();
 9901                    let length = close.end() - open.start;
 9902                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9903                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9904                        || close.contains(&selection.head());
 9905
 9906                    // If best is next to a bracket and current isn't, skip
 9907                    if !in_bracket_range && best_in_bracket_range {
 9908                        continue;
 9909                    }
 9910
 9911                    // Prefer smaller lengths unless best is inside and current isn't
 9912                    if length > best_length && (best_inside || !inside) {
 9913                        continue;
 9914                    }
 9915
 9916                    best_length = length;
 9917                    best_inside = inside;
 9918                    best_in_bracket_range = in_bracket_range;
 9919                    best_destination = Some(
 9920                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9921                            if inside {
 9922                                open.end
 9923                            } else {
 9924                                open.start
 9925                            }
 9926                        } else if inside {
 9927                            *close.start()
 9928                        } else {
 9929                            *close.end()
 9930                        },
 9931                    );
 9932                }
 9933
 9934                if let Some(destination) = best_destination {
 9935                    selection.collapse_to(destination, SelectionGoal::None);
 9936                }
 9937            })
 9938        });
 9939    }
 9940
 9941    pub fn undo_selection(
 9942        &mut self,
 9943        _: &UndoSelection,
 9944        window: &mut Window,
 9945        cx: &mut Context<Self>,
 9946    ) {
 9947        self.end_selection(window, cx);
 9948        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9949        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9950            self.change_selections(None, window, cx, |s| {
 9951                s.select_anchors(entry.selections.to_vec())
 9952            });
 9953            self.select_next_state = entry.select_next_state;
 9954            self.select_prev_state = entry.select_prev_state;
 9955            self.add_selections_state = entry.add_selections_state;
 9956            self.request_autoscroll(Autoscroll::newest(), cx);
 9957        }
 9958        self.selection_history.mode = SelectionHistoryMode::Normal;
 9959    }
 9960
 9961    pub fn redo_selection(
 9962        &mut self,
 9963        _: &RedoSelection,
 9964        window: &mut Window,
 9965        cx: &mut Context<Self>,
 9966    ) {
 9967        self.end_selection(window, cx);
 9968        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9969        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9970            self.change_selections(None, window, cx, |s| {
 9971                s.select_anchors(entry.selections.to_vec())
 9972            });
 9973            self.select_next_state = entry.select_next_state;
 9974            self.select_prev_state = entry.select_prev_state;
 9975            self.add_selections_state = entry.add_selections_state;
 9976            self.request_autoscroll(Autoscroll::newest(), cx);
 9977        }
 9978        self.selection_history.mode = SelectionHistoryMode::Normal;
 9979    }
 9980
 9981    pub fn expand_excerpts(
 9982        &mut self,
 9983        action: &ExpandExcerpts,
 9984        _: &mut Window,
 9985        cx: &mut Context<Self>,
 9986    ) {
 9987        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9988    }
 9989
 9990    pub fn expand_excerpts_down(
 9991        &mut self,
 9992        action: &ExpandExcerptsDown,
 9993        _: &mut Window,
 9994        cx: &mut Context<Self>,
 9995    ) {
 9996        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9997    }
 9998
 9999    pub fn expand_excerpts_up(
10000        &mut self,
10001        action: &ExpandExcerptsUp,
10002        _: &mut Window,
10003        cx: &mut Context<Self>,
10004    ) {
10005        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10006    }
10007
10008    pub fn expand_excerpts_for_direction(
10009        &mut self,
10010        lines: u32,
10011        direction: ExpandExcerptDirection,
10012
10013        cx: &mut Context<Self>,
10014    ) {
10015        let selections = self.selections.disjoint_anchors();
10016
10017        let lines = if lines == 0 {
10018            EditorSettings::get_global(cx).expand_excerpt_lines
10019        } else {
10020            lines
10021        };
10022
10023        self.buffer.update(cx, |buffer, cx| {
10024            let snapshot = buffer.snapshot(cx);
10025            let mut excerpt_ids = selections
10026                .iter()
10027                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10028                .collect::<Vec<_>>();
10029            excerpt_ids.sort();
10030            excerpt_ids.dedup();
10031            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10032        })
10033    }
10034
10035    pub fn expand_excerpt(
10036        &mut self,
10037        excerpt: ExcerptId,
10038        direction: ExpandExcerptDirection,
10039        cx: &mut Context<Self>,
10040    ) {
10041        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10042        self.buffer.update(cx, |buffer, cx| {
10043            buffer.expand_excerpts([excerpt], lines, direction, cx)
10044        })
10045    }
10046
10047    pub fn go_to_singleton_buffer_point(
10048        &mut self,
10049        point: Point,
10050        window: &mut Window,
10051        cx: &mut Context<Self>,
10052    ) {
10053        self.go_to_singleton_buffer_range(point..point, window, cx);
10054    }
10055
10056    pub fn go_to_singleton_buffer_range(
10057        &mut self,
10058        range: Range<Point>,
10059        window: &mut Window,
10060        cx: &mut Context<Self>,
10061    ) {
10062        let multibuffer = self.buffer().read(cx);
10063        let Some(buffer) = multibuffer.as_singleton() else {
10064            return;
10065        };
10066        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10067            return;
10068        };
10069        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10070            return;
10071        };
10072        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10073            s.select_anchor_ranges([start..end])
10074        });
10075    }
10076
10077    fn go_to_diagnostic(
10078        &mut self,
10079        _: &GoToDiagnostic,
10080        window: &mut Window,
10081        cx: &mut Context<Self>,
10082    ) {
10083        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10084    }
10085
10086    fn go_to_prev_diagnostic(
10087        &mut self,
10088        _: &GoToPrevDiagnostic,
10089        window: &mut Window,
10090        cx: &mut Context<Self>,
10091    ) {
10092        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10093    }
10094
10095    pub fn go_to_diagnostic_impl(
10096        &mut self,
10097        direction: Direction,
10098        window: &mut Window,
10099        cx: &mut Context<Self>,
10100    ) {
10101        let buffer = self.buffer.read(cx).snapshot(cx);
10102        let selection = self.selections.newest::<usize>(cx);
10103
10104        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10105        if direction == Direction::Next {
10106            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10107                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10108                    return;
10109                };
10110                self.activate_diagnostics(
10111                    buffer_id,
10112                    popover.local_diagnostic.diagnostic.group_id,
10113                    window,
10114                    cx,
10115                );
10116                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10117                    let primary_range_start = active_diagnostics.primary_range.start;
10118                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10119                        let mut new_selection = s.newest_anchor().clone();
10120                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10121                        s.select_anchors(vec![new_selection.clone()]);
10122                    });
10123                    self.refresh_inline_completion(false, true, window, cx);
10124                }
10125                return;
10126            }
10127        }
10128
10129        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10130            active_diagnostics
10131                .primary_range
10132                .to_offset(&buffer)
10133                .to_inclusive()
10134        });
10135        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10136            if active_primary_range.contains(&selection.head()) {
10137                *active_primary_range.start()
10138            } else {
10139                selection.head()
10140            }
10141        } else {
10142            selection.head()
10143        };
10144        let snapshot = self.snapshot(window, cx);
10145        loop {
10146            let mut diagnostics;
10147            if direction == Direction::Prev {
10148                diagnostics = buffer
10149                    .diagnostics_in_range::<usize>(0..search_start)
10150                    .collect::<Vec<_>>();
10151                diagnostics.reverse();
10152            } else {
10153                diagnostics = buffer
10154                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10155                    .collect::<Vec<_>>();
10156            };
10157            let group = diagnostics
10158                .into_iter()
10159                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10160                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10161                // be sorted in a stable way
10162                // skip until we are at current active diagnostic, if it exists
10163                .skip_while(|entry| {
10164                    let is_in_range = match direction {
10165                        Direction::Prev => entry.range.end > search_start,
10166                        Direction::Next => entry.range.start < search_start,
10167                    };
10168                    is_in_range
10169                        && self
10170                            .active_diagnostics
10171                            .as_ref()
10172                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10173                })
10174                .find_map(|entry| {
10175                    if entry.diagnostic.is_primary
10176                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10177                        && entry.range.start != entry.range.end
10178                        // if we match with the active diagnostic, skip it
10179                        && Some(entry.diagnostic.group_id)
10180                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10181                    {
10182                        Some((entry.range, entry.diagnostic.group_id))
10183                    } else {
10184                        None
10185                    }
10186                });
10187
10188            if let Some((primary_range, group_id)) = group {
10189                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10190                    return;
10191                };
10192                self.activate_diagnostics(buffer_id, group_id, window, cx);
10193                if self.active_diagnostics.is_some() {
10194                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10195                        s.select(vec![Selection {
10196                            id: selection.id,
10197                            start: primary_range.start,
10198                            end: primary_range.start,
10199                            reversed: false,
10200                            goal: SelectionGoal::None,
10201                        }]);
10202                    });
10203                    self.refresh_inline_completion(false, true, window, cx);
10204                }
10205                break;
10206            } else {
10207                // Cycle around to the start of the buffer, potentially moving back to the start of
10208                // the currently active diagnostic.
10209                active_primary_range.take();
10210                if direction == Direction::Prev {
10211                    if search_start == buffer.len() {
10212                        break;
10213                    } else {
10214                        search_start = buffer.len();
10215                    }
10216                } else if search_start == 0 {
10217                    break;
10218                } else {
10219                    search_start = 0;
10220                }
10221            }
10222        }
10223    }
10224
10225    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10226        let snapshot = self.snapshot(window, cx);
10227        let selection = self.selections.newest::<Point>(cx);
10228        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10229    }
10230
10231    fn go_to_hunk_after_position(
10232        &mut self,
10233        snapshot: &EditorSnapshot,
10234        position: Point,
10235        window: &mut Window,
10236        cx: &mut Context<Editor>,
10237    ) -> Option<MultiBufferDiffHunk> {
10238        let mut hunk = snapshot
10239            .buffer_snapshot
10240            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10241            .find(|hunk| hunk.row_range.start.0 > position.row);
10242        if hunk.is_none() {
10243            hunk = snapshot
10244                .buffer_snapshot
10245                .diff_hunks_in_range(Point::zero()..position)
10246                .find(|hunk| hunk.row_range.end.0 < position.row)
10247        }
10248        if let Some(hunk) = &hunk {
10249            let destination = Point::new(hunk.row_range.start.0, 0);
10250            self.unfold_ranges(&[destination..destination], false, false, cx);
10251            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252                s.select_ranges(vec![destination..destination]);
10253            });
10254        }
10255
10256        hunk
10257    }
10258
10259    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10260        let snapshot = self.snapshot(window, cx);
10261        let selection = self.selections.newest::<Point>(cx);
10262        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10263    }
10264
10265    fn go_to_hunk_before_position(
10266        &mut self,
10267        snapshot: &EditorSnapshot,
10268        position: Point,
10269        window: &mut Window,
10270        cx: &mut Context<Editor>,
10271    ) -> Option<MultiBufferDiffHunk> {
10272        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10273        if hunk.is_none() {
10274            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10275        }
10276        if let Some(hunk) = &hunk {
10277            let destination = Point::new(hunk.row_range.start.0, 0);
10278            self.unfold_ranges(&[destination..destination], false, false, cx);
10279            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10280                s.select_ranges(vec![destination..destination]);
10281            });
10282        }
10283
10284        hunk
10285    }
10286
10287    pub fn go_to_definition(
10288        &mut self,
10289        _: &GoToDefinition,
10290        window: &mut Window,
10291        cx: &mut Context<Self>,
10292    ) -> Task<Result<Navigated>> {
10293        let definition =
10294            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10295        cx.spawn_in(window, |editor, mut cx| async move {
10296            if definition.await? == Navigated::Yes {
10297                return Ok(Navigated::Yes);
10298            }
10299            match editor.update_in(&mut cx, |editor, window, cx| {
10300                editor.find_all_references(&FindAllReferences, window, cx)
10301            })? {
10302                Some(references) => references.await,
10303                None => Ok(Navigated::No),
10304            }
10305        })
10306    }
10307
10308    pub fn go_to_declaration(
10309        &mut self,
10310        _: &GoToDeclaration,
10311        window: &mut Window,
10312        cx: &mut Context<Self>,
10313    ) -> Task<Result<Navigated>> {
10314        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10315    }
10316
10317    pub fn go_to_declaration_split(
10318        &mut self,
10319        _: &GoToDeclaration,
10320        window: &mut Window,
10321        cx: &mut Context<Self>,
10322    ) -> Task<Result<Navigated>> {
10323        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10324    }
10325
10326    pub fn go_to_implementation(
10327        &mut self,
10328        _: &GoToImplementation,
10329        window: &mut Window,
10330        cx: &mut Context<Self>,
10331    ) -> Task<Result<Navigated>> {
10332        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10333    }
10334
10335    pub fn go_to_implementation_split(
10336        &mut self,
10337        _: &GoToImplementationSplit,
10338        window: &mut Window,
10339        cx: &mut Context<Self>,
10340    ) -> Task<Result<Navigated>> {
10341        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10342    }
10343
10344    pub fn go_to_type_definition(
10345        &mut self,
10346        _: &GoToTypeDefinition,
10347        window: &mut Window,
10348        cx: &mut Context<Self>,
10349    ) -> Task<Result<Navigated>> {
10350        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10351    }
10352
10353    pub fn go_to_definition_split(
10354        &mut self,
10355        _: &GoToDefinitionSplit,
10356        window: &mut Window,
10357        cx: &mut Context<Self>,
10358    ) -> Task<Result<Navigated>> {
10359        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10360    }
10361
10362    pub fn go_to_type_definition_split(
10363        &mut self,
10364        _: &GoToTypeDefinitionSplit,
10365        window: &mut Window,
10366        cx: &mut Context<Self>,
10367    ) -> Task<Result<Navigated>> {
10368        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10369    }
10370
10371    fn go_to_definition_of_kind(
10372        &mut self,
10373        kind: GotoDefinitionKind,
10374        split: bool,
10375        window: &mut Window,
10376        cx: &mut Context<Self>,
10377    ) -> Task<Result<Navigated>> {
10378        let Some(provider) = self.semantics_provider.clone() else {
10379            return Task::ready(Ok(Navigated::No));
10380        };
10381        let head = self.selections.newest::<usize>(cx).head();
10382        let buffer = self.buffer.read(cx);
10383        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10384            text_anchor
10385        } else {
10386            return Task::ready(Ok(Navigated::No));
10387        };
10388
10389        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10390            return Task::ready(Ok(Navigated::No));
10391        };
10392
10393        cx.spawn_in(window, |editor, mut cx| async move {
10394            let definitions = definitions.await?;
10395            let navigated = editor
10396                .update_in(&mut cx, |editor, window, cx| {
10397                    editor.navigate_to_hover_links(
10398                        Some(kind),
10399                        definitions
10400                            .into_iter()
10401                            .filter(|location| {
10402                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10403                            })
10404                            .map(HoverLink::Text)
10405                            .collect::<Vec<_>>(),
10406                        split,
10407                        window,
10408                        cx,
10409                    )
10410                })?
10411                .await?;
10412            anyhow::Ok(navigated)
10413        })
10414    }
10415
10416    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10417        let selection = self.selections.newest_anchor();
10418        let head = selection.head();
10419        let tail = selection.tail();
10420
10421        let Some((buffer, start_position)) =
10422            self.buffer.read(cx).text_anchor_for_position(head, cx)
10423        else {
10424            return;
10425        };
10426
10427        let end_position = if head != tail {
10428            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10429                return;
10430            };
10431            Some(pos)
10432        } else {
10433            None
10434        };
10435
10436        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10437            let url = if let Some(end_pos) = end_position {
10438                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10439            } else {
10440                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10441            };
10442
10443            if let Some(url) = url {
10444                editor.update(&mut cx, |_, cx| {
10445                    cx.open_url(&url);
10446                })
10447            } else {
10448                Ok(())
10449            }
10450        });
10451
10452        url_finder.detach();
10453    }
10454
10455    pub fn open_selected_filename(
10456        &mut self,
10457        _: &OpenSelectedFilename,
10458        window: &mut Window,
10459        cx: &mut Context<Self>,
10460    ) {
10461        let Some(workspace) = self.workspace() else {
10462            return;
10463        };
10464
10465        let position = self.selections.newest_anchor().head();
10466
10467        let Some((buffer, buffer_position)) =
10468            self.buffer.read(cx).text_anchor_for_position(position, cx)
10469        else {
10470            return;
10471        };
10472
10473        let project = self.project.clone();
10474
10475        cx.spawn_in(window, |_, mut cx| async move {
10476            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10477
10478            if let Some((_, path)) = result {
10479                workspace
10480                    .update_in(&mut cx, |workspace, window, cx| {
10481                        workspace.open_resolved_path(path, window, cx)
10482                    })?
10483                    .await?;
10484            }
10485            anyhow::Ok(())
10486        })
10487        .detach();
10488    }
10489
10490    pub(crate) fn navigate_to_hover_links(
10491        &mut self,
10492        kind: Option<GotoDefinitionKind>,
10493        mut definitions: Vec<HoverLink>,
10494        split: bool,
10495        window: &mut Window,
10496        cx: &mut Context<Editor>,
10497    ) -> Task<Result<Navigated>> {
10498        // If there is one definition, just open it directly
10499        if definitions.len() == 1 {
10500            let definition = definitions.pop().unwrap();
10501
10502            enum TargetTaskResult {
10503                Location(Option<Location>),
10504                AlreadyNavigated,
10505            }
10506
10507            let target_task = match definition {
10508                HoverLink::Text(link) => {
10509                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10510                }
10511                HoverLink::InlayHint(lsp_location, server_id) => {
10512                    let computation =
10513                        self.compute_target_location(lsp_location, server_id, window, cx);
10514                    cx.background_executor().spawn(async move {
10515                        let location = computation.await?;
10516                        Ok(TargetTaskResult::Location(location))
10517                    })
10518                }
10519                HoverLink::Url(url) => {
10520                    cx.open_url(&url);
10521                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10522                }
10523                HoverLink::File(path) => {
10524                    if let Some(workspace) = self.workspace() {
10525                        cx.spawn_in(window, |_, mut cx| async move {
10526                            workspace
10527                                .update_in(&mut cx, |workspace, window, cx| {
10528                                    workspace.open_resolved_path(path, window, cx)
10529                                })?
10530                                .await
10531                                .map(|_| TargetTaskResult::AlreadyNavigated)
10532                        })
10533                    } else {
10534                        Task::ready(Ok(TargetTaskResult::Location(None)))
10535                    }
10536                }
10537            };
10538            cx.spawn_in(window, |editor, mut cx| async move {
10539                let target = match target_task.await.context("target resolution task")? {
10540                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10541                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10542                    TargetTaskResult::Location(Some(target)) => target,
10543                };
10544
10545                editor.update_in(&mut cx, |editor, window, cx| {
10546                    let Some(workspace) = editor.workspace() else {
10547                        return Navigated::No;
10548                    };
10549                    let pane = workspace.read(cx).active_pane().clone();
10550
10551                    let range = target.range.to_point(target.buffer.read(cx));
10552                    let range = editor.range_for_match(&range);
10553                    let range = collapse_multiline_range(range);
10554
10555                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10556                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10557                    } else {
10558                        window.defer(cx, move |window, cx| {
10559                            let target_editor: Entity<Self> =
10560                                workspace.update(cx, |workspace, cx| {
10561                                    let pane = if split {
10562                                        workspace.adjacent_pane(window, cx)
10563                                    } else {
10564                                        workspace.active_pane().clone()
10565                                    };
10566
10567                                    workspace.open_project_item(
10568                                        pane,
10569                                        target.buffer.clone(),
10570                                        true,
10571                                        true,
10572                                        window,
10573                                        cx,
10574                                    )
10575                                });
10576                            target_editor.update(cx, |target_editor, cx| {
10577                                // When selecting a definition in a different buffer, disable the nav history
10578                                // to avoid creating a history entry at the previous cursor location.
10579                                pane.update(cx, |pane, _| pane.disable_history());
10580                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10581                                pane.update(cx, |pane, _| pane.enable_history());
10582                            });
10583                        });
10584                    }
10585                    Navigated::Yes
10586                })
10587            })
10588        } else if !definitions.is_empty() {
10589            cx.spawn_in(window, |editor, mut cx| async move {
10590                let (title, location_tasks, workspace) = editor
10591                    .update_in(&mut cx, |editor, window, cx| {
10592                        let tab_kind = match kind {
10593                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10594                            _ => "Definitions",
10595                        };
10596                        let title = definitions
10597                            .iter()
10598                            .find_map(|definition| match definition {
10599                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10600                                    let buffer = origin.buffer.read(cx);
10601                                    format!(
10602                                        "{} for {}",
10603                                        tab_kind,
10604                                        buffer
10605                                            .text_for_range(origin.range.clone())
10606                                            .collect::<String>()
10607                                    )
10608                                }),
10609                                HoverLink::InlayHint(_, _) => None,
10610                                HoverLink::Url(_) => None,
10611                                HoverLink::File(_) => None,
10612                            })
10613                            .unwrap_or(tab_kind.to_string());
10614                        let location_tasks = definitions
10615                            .into_iter()
10616                            .map(|definition| match definition {
10617                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10618                                HoverLink::InlayHint(lsp_location, server_id) => editor
10619                                    .compute_target_location(lsp_location, server_id, window, cx),
10620                                HoverLink::Url(_) => Task::ready(Ok(None)),
10621                                HoverLink::File(_) => Task::ready(Ok(None)),
10622                            })
10623                            .collect::<Vec<_>>();
10624                        (title, location_tasks, editor.workspace().clone())
10625                    })
10626                    .context("location tasks preparation")?;
10627
10628                let locations = future::join_all(location_tasks)
10629                    .await
10630                    .into_iter()
10631                    .filter_map(|location| location.transpose())
10632                    .collect::<Result<_>>()
10633                    .context("location tasks")?;
10634
10635                let Some(workspace) = workspace else {
10636                    return Ok(Navigated::No);
10637                };
10638                let opened = workspace
10639                    .update_in(&mut cx, |workspace, window, cx| {
10640                        Self::open_locations_in_multibuffer(
10641                            workspace,
10642                            locations,
10643                            title,
10644                            split,
10645                            MultibufferSelectionMode::First,
10646                            window,
10647                            cx,
10648                        )
10649                    })
10650                    .ok();
10651
10652                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10653            })
10654        } else {
10655            Task::ready(Ok(Navigated::No))
10656        }
10657    }
10658
10659    fn compute_target_location(
10660        &self,
10661        lsp_location: lsp::Location,
10662        server_id: LanguageServerId,
10663        window: &mut Window,
10664        cx: &mut Context<Self>,
10665    ) -> Task<anyhow::Result<Option<Location>>> {
10666        let Some(project) = self.project.clone() else {
10667            return Task::ready(Ok(None));
10668        };
10669
10670        cx.spawn_in(window, move |editor, mut cx| async move {
10671            let location_task = editor.update(&mut cx, |_, cx| {
10672                project.update(cx, |project, cx| {
10673                    let language_server_name = project
10674                        .language_server_statuses(cx)
10675                        .find(|(id, _)| server_id == *id)
10676                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10677                    language_server_name.map(|language_server_name| {
10678                        project.open_local_buffer_via_lsp(
10679                            lsp_location.uri.clone(),
10680                            server_id,
10681                            language_server_name,
10682                            cx,
10683                        )
10684                    })
10685                })
10686            })?;
10687            let location = match location_task {
10688                Some(task) => Some({
10689                    let target_buffer_handle = task.await.context("open local buffer")?;
10690                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10691                        let target_start = target_buffer
10692                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10693                        let target_end = target_buffer
10694                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10695                        target_buffer.anchor_after(target_start)
10696                            ..target_buffer.anchor_before(target_end)
10697                    })?;
10698                    Location {
10699                        buffer: target_buffer_handle,
10700                        range,
10701                    }
10702                }),
10703                None => None,
10704            };
10705            Ok(location)
10706        })
10707    }
10708
10709    pub fn find_all_references(
10710        &mut self,
10711        _: &FindAllReferences,
10712        window: &mut Window,
10713        cx: &mut Context<Self>,
10714    ) -> Option<Task<Result<Navigated>>> {
10715        let selection = self.selections.newest::<usize>(cx);
10716        let multi_buffer = self.buffer.read(cx);
10717        let head = selection.head();
10718
10719        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10720        let head_anchor = multi_buffer_snapshot.anchor_at(
10721            head,
10722            if head < selection.tail() {
10723                Bias::Right
10724            } else {
10725                Bias::Left
10726            },
10727        );
10728
10729        match self
10730            .find_all_references_task_sources
10731            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10732        {
10733            Ok(_) => {
10734                log::info!(
10735                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10736                );
10737                return None;
10738            }
10739            Err(i) => {
10740                self.find_all_references_task_sources.insert(i, head_anchor);
10741            }
10742        }
10743
10744        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10745        let workspace = self.workspace()?;
10746        let project = workspace.read(cx).project().clone();
10747        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10748        Some(cx.spawn_in(window, |editor, mut cx| async move {
10749            let _cleanup = defer({
10750                let mut cx = cx.clone();
10751                move || {
10752                    let _ = editor.update(&mut cx, |editor, _| {
10753                        if let Ok(i) =
10754                            editor
10755                                .find_all_references_task_sources
10756                                .binary_search_by(|anchor| {
10757                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10758                                })
10759                        {
10760                            editor.find_all_references_task_sources.remove(i);
10761                        }
10762                    });
10763                }
10764            });
10765
10766            let locations = references.await?;
10767            if locations.is_empty() {
10768                return anyhow::Ok(Navigated::No);
10769            }
10770
10771            workspace.update_in(&mut cx, |workspace, window, cx| {
10772                let title = locations
10773                    .first()
10774                    .as_ref()
10775                    .map(|location| {
10776                        let buffer = location.buffer.read(cx);
10777                        format!(
10778                            "References to `{}`",
10779                            buffer
10780                                .text_for_range(location.range.clone())
10781                                .collect::<String>()
10782                        )
10783                    })
10784                    .unwrap();
10785                Self::open_locations_in_multibuffer(
10786                    workspace,
10787                    locations,
10788                    title,
10789                    false,
10790                    MultibufferSelectionMode::First,
10791                    window,
10792                    cx,
10793                );
10794                Navigated::Yes
10795            })
10796        }))
10797    }
10798
10799    /// Opens a multibuffer with the given project locations in it
10800    pub fn open_locations_in_multibuffer(
10801        workspace: &mut Workspace,
10802        mut locations: Vec<Location>,
10803        title: String,
10804        split: bool,
10805        multibuffer_selection_mode: MultibufferSelectionMode,
10806        window: &mut Window,
10807        cx: &mut Context<Workspace>,
10808    ) {
10809        // If there are multiple definitions, open them in a multibuffer
10810        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10811        let mut locations = locations.into_iter().peekable();
10812        let mut ranges = Vec::new();
10813        let capability = workspace.project().read(cx).capability();
10814
10815        let excerpt_buffer = cx.new(|cx| {
10816            let mut multibuffer = MultiBuffer::new(capability);
10817            while let Some(location) = locations.next() {
10818                let buffer = location.buffer.read(cx);
10819                let mut ranges_for_buffer = Vec::new();
10820                let range = location.range.to_offset(buffer);
10821                ranges_for_buffer.push(range.clone());
10822
10823                while let Some(next_location) = locations.peek() {
10824                    if next_location.buffer == location.buffer {
10825                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10826                        locations.next();
10827                    } else {
10828                        break;
10829                    }
10830                }
10831
10832                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10833                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10834                    location.buffer.clone(),
10835                    ranges_for_buffer,
10836                    DEFAULT_MULTIBUFFER_CONTEXT,
10837                    cx,
10838                ))
10839            }
10840
10841            multibuffer.with_title(title)
10842        });
10843
10844        let editor = cx.new(|cx| {
10845            Editor::for_multibuffer(
10846                excerpt_buffer,
10847                Some(workspace.project().clone()),
10848                true,
10849                window,
10850                cx,
10851            )
10852        });
10853        editor.update(cx, |editor, cx| {
10854            match multibuffer_selection_mode {
10855                MultibufferSelectionMode::First => {
10856                    if let Some(first_range) = ranges.first() {
10857                        editor.change_selections(None, window, cx, |selections| {
10858                            selections.clear_disjoint();
10859                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10860                        });
10861                    }
10862                    editor.highlight_background::<Self>(
10863                        &ranges,
10864                        |theme| theme.editor_highlighted_line_background,
10865                        cx,
10866                    );
10867                }
10868                MultibufferSelectionMode::All => {
10869                    editor.change_selections(None, window, cx, |selections| {
10870                        selections.clear_disjoint();
10871                        selections.select_anchor_ranges(ranges);
10872                    });
10873                }
10874            }
10875            editor.register_buffers_with_language_servers(cx);
10876        });
10877
10878        let item = Box::new(editor);
10879        let item_id = item.item_id();
10880
10881        if split {
10882            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10883        } else {
10884            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10885                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10886                    pane.close_current_preview_item(window, cx)
10887                } else {
10888                    None
10889                }
10890            });
10891            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10892        }
10893        workspace.active_pane().update(cx, |pane, cx| {
10894            pane.set_preview_item_id(Some(item_id), cx);
10895        });
10896    }
10897
10898    pub fn rename(
10899        &mut self,
10900        _: &Rename,
10901        window: &mut Window,
10902        cx: &mut Context<Self>,
10903    ) -> Option<Task<Result<()>>> {
10904        use language::ToOffset as _;
10905
10906        let provider = self.semantics_provider.clone()?;
10907        let selection = self.selections.newest_anchor().clone();
10908        let (cursor_buffer, cursor_buffer_position) = self
10909            .buffer
10910            .read(cx)
10911            .text_anchor_for_position(selection.head(), cx)?;
10912        let (tail_buffer, cursor_buffer_position_end) = self
10913            .buffer
10914            .read(cx)
10915            .text_anchor_for_position(selection.tail(), cx)?;
10916        if tail_buffer != cursor_buffer {
10917            return None;
10918        }
10919
10920        let snapshot = cursor_buffer.read(cx).snapshot();
10921        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10922        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10923        let prepare_rename = provider
10924            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10925            .unwrap_or_else(|| Task::ready(Ok(None)));
10926        drop(snapshot);
10927
10928        Some(cx.spawn_in(window, |this, mut cx| async move {
10929            let rename_range = if let Some(range) = prepare_rename.await? {
10930                Some(range)
10931            } else {
10932                this.update(&mut cx, |this, cx| {
10933                    let buffer = this.buffer.read(cx).snapshot(cx);
10934                    let mut buffer_highlights = this
10935                        .document_highlights_for_position(selection.head(), &buffer)
10936                        .filter(|highlight| {
10937                            highlight.start.excerpt_id == selection.head().excerpt_id
10938                                && highlight.end.excerpt_id == selection.head().excerpt_id
10939                        });
10940                    buffer_highlights
10941                        .next()
10942                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10943                })?
10944            };
10945            if let Some(rename_range) = rename_range {
10946                this.update_in(&mut cx, |this, window, cx| {
10947                    let snapshot = cursor_buffer.read(cx).snapshot();
10948                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10949                    let cursor_offset_in_rename_range =
10950                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10951                    let cursor_offset_in_rename_range_end =
10952                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10953
10954                    this.take_rename(false, window, cx);
10955                    let buffer = this.buffer.read(cx).read(cx);
10956                    let cursor_offset = selection.head().to_offset(&buffer);
10957                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10958                    let rename_end = rename_start + rename_buffer_range.len();
10959                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10960                    let mut old_highlight_id = None;
10961                    let old_name: Arc<str> = buffer
10962                        .chunks(rename_start..rename_end, true)
10963                        .map(|chunk| {
10964                            if old_highlight_id.is_none() {
10965                                old_highlight_id = chunk.syntax_highlight_id;
10966                            }
10967                            chunk.text
10968                        })
10969                        .collect::<String>()
10970                        .into();
10971
10972                    drop(buffer);
10973
10974                    // Position the selection in the rename editor so that it matches the current selection.
10975                    this.show_local_selections = false;
10976                    let rename_editor = cx.new(|cx| {
10977                        let mut editor = Editor::single_line(window, cx);
10978                        editor.buffer.update(cx, |buffer, cx| {
10979                            buffer.edit([(0..0, old_name.clone())], None, cx)
10980                        });
10981                        let rename_selection_range = match cursor_offset_in_rename_range
10982                            .cmp(&cursor_offset_in_rename_range_end)
10983                        {
10984                            Ordering::Equal => {
10985                                editor.select_all(&SelectAll, window, cx);
10986                                return editor;
10987                            }
10988                            Ordering::Less => {
10989                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10990                            }
10991                            Ordering::Greater => {
10992                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10993                            }
10994                        };
10995                        if rename_selection_range.end > old_name.len() {
10996                            editor.select_all(&SelectAll, window, cx);
10997                        } else {
10998                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10999                                s.select_ranges([rename_selection_range]);
11000                            });
11001                        }
11002                        editor
11003                    });
11004                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11005                        if e == &EditorEvent::Focused {
11006                            cx.emit(EditorEvent::FocusedIn)
11007                        }
11008                    })
11009                    .detach();
11010
11011                    let write_highlights =
11012                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11013                    let read_highlights =
11014                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11015                    let ranges = write_highlights
11016                        .iter()
11017                        .flat_map(|(_, ranges)| ranges.iter())
11018                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11019                        .cloned()
11020                        .collect();
11021
11022                    this.highlight_text::<Rename>(
11023                        ranges,
11024                        HighlightStyle {
11025                            fade_out: Some(0.6),
11026                            ..Default::default()
11027                        },
11028                        cx,
11029                    );
11030                    let rename_focus_handle = rename_editor.focus_handle(cx);
11031                    window.focus(&rename_focus_handle);
11032                    let block_id = this.insert_blocks(
11033                        [BlockProperties {
11034                            style: BlockStyle::Flex,
11035                            placement: BlockPlacement::Below(range.start),
11036                            height: 1,
11037                            render: Arc::new({
11038                                let rename_editor = rename_editor.clone();
11039                                move |cx: &mut BlockContext| {
11040                                    let mut text_style = cx.editor_style.text.clone();
11041                                    if let Some(highlight_style) = old_highlight_id
11042                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11043                                    {
11044                                        text_style = text_style.highlight(highlight_style);
11045                                    }
11046                                    div()
11047                                        .block_mouse_down()
11048                                        .pl(cx.anchor_x)
11049                                        .child(EditorElement::new(
11050                                            &rename_editor,
11051                                            EditorStyle {
11052                                                background: cx.theme().system().transparent,
11053                                                local_player: cx.editor_style.local_player,
11054                                                text: text_style,
11055                                                scrollbar_width: cx.editor_style.scrollbar_width,
11056                                                syntax: cx.editor_style.syntax.clone(),
11057                                                status: cx.editor_style.status.clone(),
11058                                                inlay_hints_style: HighlightStyle {
11059                                                    font_weight: Some(FontWeight::BOLD),
11060                                                    ..make_inlay_hints_style(cx.app)
11061                                                },
11062                                                inline_completion_styles: make_suggestion_styles(
11063                                                    cx.app,
11064                                                ),
11065                                                ..EditorStyle::default()
11066                                            },
11067                                        ))
11068                                        .into_any_element()
11069                                }
11070                            }),
11071                            priority: 0,
11072                        }],
11073                        Some(Autoscroll::fit()),
11074                        cx,
11075                    )[0];
11076                    this.pending_rename = Some(RenameState {
11077                        range,
11078                        old_name,
11079                        editor: rename_editor,
11080                        block_id,
11081                    });
11082                })?;
11083            }
11084
11085            Ok(())
11086        }))
11087    }
11088
11089    pub fn confirm_rename(
11090        &mut self,
11091        _: &ConfirmRename,
11092        window: &mut Window,
11093        cx: &mut Context<Self>,
11094    ) -> Option<Task<Result<()>>> {
11095        let rename = self.take_rename(false, window, cx)?;
11096        let workspace = self.workspace()?.downgrade();
11097        let (buffer, start) = self
11098            .buffer
11099            .read(cx)
11100            .text_anchor_for_position(rename.range.start, cx)?;
11101        let (end_buffer, _) = self
11102            .buffer
11103            .read(cx)
11104            .text_anchor_for_position(rename.range.end, cx)?;
11105        if buffer != end_buffer {
11106            return None;
11107        }
11108
11109        let old_name = rename.old_name;
11110        let new_name = rename.editor.read(cx).text(cx);
11111
11112        let rename = self.semantics_provider.as_ref()?.perform_rename(
11113            &buffer,
11114            start,
11115            new_name.clone(),
11116            cx,
11117        )?;
11118
11119        Some(cx.spawn_in(window, |editor, mut cx| async move {
11120            let project_transaction = rename.await?;
11121            Self::open_project_transaction(
11122                &editor,
11123                workspace,
11124                project_transaction,
11125                format!("Rename: {}{}", old_name, new_name),
11126                cx.clone(),
11127            )
11128            .await?;
11129
11130            editor.update(&mut cx, |editor, cx| {
11131                editor.refresh_document_highlights(cx);
11132            })?;
11133            Ok(())
11134        }))
11135    }
11136
11137    fn take_rename(
11138        &mut self,
11139        moving_cursor: bool,
11140        window: &mut Window,
11141        cx: &mut Context<Self>,
11142    ) -> Option<RenameState> {
11143        let rename = self.pending_rename.take()?;
11144        if rename.editor.focus_handle(cx).is_focused(window) {
11145            window.focus(&self.focus_handle);
11146        }
11147
11148        self.remove_blocks(
11149            [rename.block_id].into_iter().collect(),
11150            Some(Autoscroll::fit()),
11151            cx,
11152        );
11153        self.clear_highlights::<Rename>(cx);
11154        self.show_local_selections = true;
11155
11156        if moving_cursor {
11157            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11158                editor.selections.newest::<usize>(cx).head()
11159            });
11160
11161            // Update the selection to match the position of the selection inside
11162            // the rename editor.
11163            let snapshot = self.buffer.read(cx).read(cx);
11164            let rename_range = rename.range.to_offset(&snapshot);
11165            let cursor_in_editor = snapshot
11166                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11167                .min(rename_range.end);
11168            drop(snapshot);
11169
11170            self.change_selections(None, window, cx, |s| {
11171                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11172            });
11173        } else {
11174            self.refresh_document_highlights(cx);
11175        }
11176
11177        Some(rename)
11178    }
11179
11180    pub fn pending_rename(&self) -> Option<&RenameState> {
11181        self.pending_rename.as_ref()
11182    }
11183
11184    fn format(
11185        &mut self,
11186        _: &Format,
11187        window: &mut Window,
11188        cx: &mut Context<Self>,
11189    ) -> Option<Task<Result<()>>> {
11190        let project = match &self.project {
11191            Some(project) => project.clone(),
11192            None => return None,
11193        };
11194
11195        Some(self.perform_format(
11196            project,
11197            FormatTrigger::Manual,
11198            FormatTarget::Buffers,
11199            window,
11200            cx,
11201        ))
11202    }
11203
11204    fn format_selections(
11205        &mut self,
11206        _: &FormatSelections,
11207        window: &mut Window,
11208        cx: &mut Context<Self>,
11209    ) -> Option<Task<Result<()>>> {
11210        let project = match &self.project {
11211            Some(project) => project.clone(),
11212            None => return None,
11213        };
11214
11215        let ranges = self
11216            .selections
11217            .all_adjusted(cx)
11218            .into_iter()
11219            .map(|selection| selection.range())
11220            .collect_vec();
11221
11222        Some(self.perform_format(
11223            project,
11224            FormatTrigger::Manual,
11225            FormatTarget::Ranges(ranges),
11226            window,
11227            cx,
11228        ))
11229    }
11230
11231    fn perform_format(
11232        &mut self,
11233        project: Entity<Project>,
11234        trigger: FormatTrigger,
11235        target: FormatTarget,
11236        window: &mut Window,
11237        cx: &mut Context<Self>,
11238    ) -> Task<Result<()>> {
11239        let buffer = self.buffer.clone();
11240        let (buffers, target) = match target {
11241            FormatTarget::Buffers => {
11242                let mut buffers = buffer.read(cx).all_buffers();
11243                if trigger == FormatTrigger::Save {
11244                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11245                }
11246                (buffers, LspFormatTarget::Buffers)
11247            }
11248            FormatTarget::Ranges(selection_ranges) => {
11249                let multi_buffer = buffer.read(cx);
11250                let snapshot = multi_buffer.read(cx);
11251                let mut buffers = HashSet::default();
11252                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11253                    BTreeMap::new();
11254                for selection_range in selection_ranges {
11255                    for (buffer, buffer_range, _) in
11256                        snapshot.range_to_buffer_ranges(selection_range)
11257                    {
11258                        let buffer_id = buffer.remote_id();
11259                        let start = buffer.anchor_before(buffer_range.start);
11260                        let end = buffer.anchor_after(buffer_range.end);
11261                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11262                        buffer_id_to_ranges
11263                            .entry(buffer_id)
11264                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11265                            .or_insert_with(|| vec![start..end]);
11266                    }
11267                }
11268                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11269            }
11270        };
11271
11272        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11273        let format = project.update(cx, |project, cx| {
11274            project.format(buffers, target, true, trigger, cx)
11275        });
11276
11277        cx.spawn_in(window, |_, mut cx| async move {
11278            let transaction = futures::select_biased! {
11279                () = timeout => {
11280                    log::warn!("timed out waiting for formatting");
11281                    None
11282                }
11283                transaction = format.log_err().fuse() => transaction,
11284            };
11285
11286            buffer
11287                .update(&mut cx, |buffer, cx| {
11288                    if let Some(transaction) = transaction {
11289                        if !buffer.is_singleton() {
11290                            buffer.push_transaction(&transaction.0, cx);
11291                        }
11292                    }
11293
11294                    cx.notify();
11295                })
11296                .ok();
11297
11298            Ok(())
11299        })
11300    }
11301
11302    fn restart_language_server(
11303        &mut self,
11304        _: &RestartLanguageServer,
11305        _: &mut Window,
11306        cx: &mut Context<Self>,
11307    ) {
11308        if let Some(project) = self.project.clone() {
11309            self.buffer.update(cx, |multi_buffer, cx| {
11310                project.update(cx, |project, cx| {
11311                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11312                });
11313            })
11314        }
11315    }
11316
11317    fn cancel_language_server_work(
11318        workspace: &mut Workspace,
11319        _: &actions::CancelLanguageServerWork,
11320        _: &mut Window,
11321        cx: &mut Context<Workspace>,
11322    ) {
11323        let project = workspace.project();
11324        let buffers = workspace
11325            .active_item(cx)
11326            .and_then(|item| item.act_as::<Editor>(cx))
11327            .map_or(HashSet::default(), |editor| {
11328                editor.read(cx).buffer.read(cx).all_buffers()
11329            });
11330        project.update(cx, |project, cx| {
11331            project.cancel_language_server_work_for_buffers(buffers, cx);
11332        });
11333    }
11334
11335    fn show_character_palette(
11336        &mut self,
11337        _: &ShowCharacterPalette,
11338        window: &mut Window,
11339        _: &mut Context<Self>,
11340    ) {
11341        window.show_character_palette();
11342    }
11343
11344    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11345        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11346            let buffer = self.buffer.read(cx).snapshot(cx);
11347            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11348            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11349            let is_valid = buffer
11350                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11351                .any(|entry| {
11352                    entry.diagnostic.is_primary
11353                        && !entry.range.is_empty()
11354                        && entry.range.start == primary_range_start
11355                        && entry.diagnostic.message == active_diagnostics.primary_message
11356                });
11357
11358            if is_valid != active_diagnostics.is_valid {
11359                active_diagnostics.is_valid = is_valid;
11360                let mut new_styles = HashMap::default();
11361                for (block_id, diagnostic) in &active_diagnostics.blocks {
11362                    new_styles.insert(
11363                        *block_id,
11364                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11365                    );
11366                }
11367                self.display_map.update(cx, |display_map, _cx| {
11368                    display_map.replace_blocks(new_styles)
11369                });
11370            }
11371        }
11372    }
11373
11374    fn activate_diagnostics(
11375        &mut self,
11376        buffer_id: BufferId,
11377        group_id: usize,
11378        window: &mut Window,
11379        cx: &mut Context<Self>,
11380    ) {
11381        self.dismiss_diagnostics(cx);
11382        let snapshot = self.snapshot(window, cx);
11383        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11384            let buffer = self.buffer.read(cx).snapshot(cx);
11385
11386            let mut primary_range = None;
11387            let mut primary_message = None;
11388            let diagnostic_group = buffer
11389                .diagnostic_group(buffer_id, group_id)
11390                .filter_map(|entry| {
11391                    let start = entry.range.start;
11392                    let end = entry.range.end;
11393                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11394                        && (start.row == end.row
11395                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11396                    {
11397                        return None;
11398                    }
11399                    if entry.diagnostic.is_primary {
11400                        primary_range = Some(entry.range.clone());
11401                        primary_message = Some(entry.diagnostic.message.clone());
11402                    }
11403                    Some(entry)
11404                })
11405                .collect::<Vec<_>>();
11406            let primary_range = primary_range?;
11407            let primary_message = primary_message?;
11408
11409            let blocks = display_map
11410                .insert_blocks(
11411                    diagnostic_group.iter().map(|entry| {
11412                        let diagnostic = entry.diagnostic.clone();
11413                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11414                        BlockProperties {
11415                            style: BlockStyle::Fixed,
11416                            placement: BlockPlacement::Below(
11417                                buffer.anchor_after(entry.range.start),
11418                            ),
11419                            height: message_height,
11420                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11421                            priority: 0,
11422                        }
11423                    }),
11424                    cx,
11425                )
11426                .into_iter()
11427                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11428                .collect();
11429
11430            Some(ActiveDiagnosticGroup {
11431                primary_range: buffer.anchor_before(primary_range.start)
11432                    ..buffer.anchor_after(primary_range.end),
11433                primary_message,
11434                group_id,
11435                blocks,
11436                is_valid: true,
11437            })
11438        });
11439    }
11440
11441    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11442        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11443            self.display_map.update(cx, |display_map, cx| {
11444                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11445            });
11446            cx.notify();
11447        }
11448    }
11449
11450    pub fn set_selections_from_remote(
11451        &mut self,
11452        selections: Vec<Selection<Anchor>>,
11453        pending_selection: Option<Selection<Anchor>>,
11454        window: &mut Window,
11455        cx: &mut Context<Self>,
11456    ) {
11457        let old_cursor_position = self.selections.newest_anchor().head();
11458        self.selections.change_with(cx, |s| {
11459            s.select_anchors(selections);
11460            if let Some(pending_selection) = pending_selection {
11461                s.set_pending(pending_selection, SelectMode::Character);
11462            } else {
11463                s.clear_pending();
11464            }
11465        });
11466        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11467    }
11468
11469    fn push_to_selection_history(&mut self) {
11470        self.selection_history.push(SelectionHistoryEntry {
11471            selections: self.selections.disjoint_anchors(),
11472            select_next_state: self.select_next_state.clone(),
11473            select_prev_state: self.select_prev_state.clone(),
11474            add_selections_state: self.add_selections_state.clone(),
11475        });
11476    }
11477
11478    pub fn transact(
11479        &mut self,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11483    ) -> Option<TransactionId> {
11484        self.start_transaction_at(Instant::now(), window, cx);
11485        update(self, window, cx);
11486        self.end_transaction_at(Instant::now(), cx)
11487    }
11488
11489    pub fn start_transaction_at(
11490        &mut self,
11491        now: Instant,
11492        window: &mut Window,
11493        cx: &mut Context<Self>,
11494    ) {
11495        self.end_selection(window, cx);
11496        if let Some(tx_id) = self
11497            .buffer
11498            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11499        {
11500            self.selection_history
11501                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11502            cx.emit(EditorEvent::TransactionBegun {
11503                transaction_id: tx_id,
11504            })
11505        }
11506    }
11507
11508    pub fn end_transaction_at(
11509        &mut self,
11510        now: Instant,
11511        cx: &mut Context<Self>,
11512    ) -> Option<TransactionId> {
11513        if let Some(transaction_id) = self
11514            .buffer
11515            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11516        {
11517            if let Some((_, end_selections)) =
11518                self.selection_history.transaction_mut(transaction_id)
11519            {
11520                *end_selections = Some(self.selections.disjoint_anchors());
11521            } else {
11522                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11523            }
11524
11525            cx.emit(EditorEvent::Edited { transaction_id });
11526            Some(transaction_id)
11527        } else {
11528            None
11529        }
11530    }
11531
11532    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11533        if self.selection_mark_mode {
11534            self.change_selections(None, window, cx, |s| {
11535                s.move_with(|_, sel| {
11536                    sel.collapse_to(sel.head(), SelectionGoal::None);
11537                });
11538            })
11539        }
11540        self.selection_mark_mode = true;
11541        cx.notify();
11542    }
11543
11544    pub fn swap_selection_ends(
11545        &mut self,
11546        _: &actions::SwapSelectionEnds,
11547        window: &mut Window,
11548        cx: &mut Context<Self>,
11549    ) {
11550        self.change_selections(None, window, cx, |s| {
11551            s.move_with(|_, sel| {
11552                if sel.start != sel.end {
11553                    sel.reversed = !sel.reversed
11554                }
11555            });
11556        });
11557        self.request_autoscroll(Autoscroll::newest(), cx);
11558        cx.notify();
11559    }
11560
11561    pub fn toggle_fold(
11562        &mut self,
11563        _: &actions::ToggleFold,
11564        window: &mut Window,
11565        cx: &mut Context<Self>,
11566    ) {
11567        if self.is_singleton(cx) {
11568            let selection = self.selections.newest::<Point>(cx);
11569
11570            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11571            let range = if selection.is_empty() {
11572                let point = selection.head().to_display_point(&display_map);
11573                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11574                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11575                    .to_point(&display_map);
11576                start..end
11577            } else {
11578                selection.range()
11579            };
11580            if display_map.folds_in_range(range).next().is_some() {
11581                self.unfold_lines(&Default::default(), window, cx)
11582            } else {
11583                self.fold(&Default::default(), window, cx)
11584            }
11585        } else {
11586            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11587            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11588                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11589                .map(|(snapshot, _, _)| snapshot.remote_id())
11590                .collect();
11591
11592            for buffer_id in buffer_ids {
11593                if self.is_buffer_folded(buffer_id, cx) {
11594                    self.unfold_buffer(buffer_id, cx);
11595                } else {
11596                    self.fold_buffer(buffer_id, cx);
11597                }
11598            }
11599        }
11600    }
11601
11602    pub fn toggle_fold_recursive(
11603        &mut self,
11604        _: &actions::ToggleFoldRecursive,
11605        window: &mut Window,
11606        cx: &mut Context<Self>,
11607    ) {
11608        let selection = self.selections.newest::<Point>(cx);
11609
11610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11611        let range = if selection.is_empty() {
11612            let point = selection.head().to_display_point(&display_map);
11613            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11614            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11615                .to_point(&display_map);
11616            start..end
11617        } else {
11618            selection.range()
11619        };
11620        if display_map.folds_in_range(range).next().is_some() {
11621            self.unfold_recursive(&Default::default(), window, cx)
11622        } else {
11623            self.fold_recursive(&Default::default(), window, cx)
11624        }
11625    }
11626
11627    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11628        if self.is_singleton(cx) {
11629            let mut to_fold = Vec::new();
11630            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11631            let selections = self.selections.all_adjusted(cx);
11632
11633            for selection in selections {
11634                let range = selection.range().sorted();
11635                let buffer_start_row = range.start.row;
11636
11637                if range.start.row != range.end.row {
11638                    let mut found = false;
11639                    let mut row = range.start.row;
11640                    while row <= range.end.row {
11641                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11642                        {
11643                            found = true;
11644                            row = crease.range().end.row + 1;
11645                            to_fold.push(crease);
11646                        } else {
11647                            row += 1
11648                        }
11649                    }
11650                    if found {
11651                        continue;
11652                    }
11653                }
11654
11655                for row in (0..=range.start.row).rev() {
11656                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11657                        if crease.range().end.row >= buffer_start_row {
11658                            to_fold.push(crease);
11659                            if row <= range.start.row {
11660                                break;
11661                            }
11662                        }
11663                    }
11664                }
11665            }
11666
11667            self.fold_creases(to_fold, true, window, cx);
11668        } else {
11669            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11670
11671            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11672                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11673                .map(|(snapshot, _, _)| snapshot.remote_id())
11674                .collect();
11675            for buffer_id in buffer_ids {
11676                self.fold_buffer(buffer_id, cx);
11677            }
11678        }
11679    }
11680
11681    fn fold_at_level(
11682        &mut self,
11683        fold_at: &FoldAtLevel,
11684        window: &mut Window,
11685        cx: &mut Context<Self>,
11686    ) {
11687        if !self.buffer.read(cx).is_singleton() {
11688            return;
11689        }
11690
11691        let fold_at_level = fold_at.level;
11692        let snapshot = self.buffer.read(cx).snapshot(cx);
11693        let mut to_fold = Vec::new();
11694        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11695
11696        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11697            while start_row < end_row {
11698                match self
11699                    .snapshot(window, cx)
11700                    .crease_for_buffer_row(MultiBufferRow(start_row))
11701                {
11702                    Some(crease) => {
11703                        let nested_start_row = crease.range().start.row + 1;
11704                        let nested_end_row = crease.range().end.row;
11705
11706                        if current_level < fold_at_level {
11707                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11708                        } else if current_level == fold_at_level {
11709                            to_fold.push(crease);
11710                        }
11711
11712                        start_row = nested_end_row + 1;
11713                    }
11714                    None => start_row += 1,
11715                }
11716            }
11717        }
11718
11719        self.fold_creases(to_fold, true, window, cx);
11720    }
11721
11722    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11723        if self.buffer.read(cx).is_singleton() {
11724            let mut fold_ranges = Vec::new();
11725            let snapshot = self.buffer.read(cx).snapshot(cx);
11726
11727            for row in 0..snapshot.max_row().0 {
11728                if let Some(foldable_range) = self
11729                    .snapshot(window, cx)
11730                    .crease_for_buffer_row(MultiBufferRow(row))
11731                {
11732                    fold_ranges.push(foldable_range);
11733                }
11734            }
11735
11736            self.fold_creases(fold_ranges, true, window, cx);
11737        } else {
11738            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11739                editor
11740                    .update_in(&mut cx, |editor, _, cx| {
11741                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11742                            editor.fold_buffer(buffer_id, cx);
11743                        }
11744                    })
11745                    .ok();
11746            });
11747        }
11748    }
11749
11750    pub fn fold_function_bodies(
11751        &mut self,
11752        _: &actions::FoldFunctionBodies,
11753        window: &mut Window,
11754        cx: &mut Context<Self>,
11755    ) {
11756        let snapshot = self.buffer.read(cx).snapshot(cx);
11757
11758        let ranges = snapshot
11759            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11760            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11761            .collect::<Vec<_>>();
11762
11763        let creases = ranges
11764            .into_iter()
11765            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11766            .collect();
11767
11768        self.fold_creases(creases, true, window, cx);
11769    }
11770
11771    pub fn fold_recursive(
11772        &mut self,
11773        _: &actions::FoldRecursive,
11774        window: &mut Window,
11775        cx: &mut Context<Self>,
11776    ) {
11777        let mut to_fold = Vec::new();
11778        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11779        let selections = self.selections.all_adjusted(cx);
11780
11781        for selection in selections {
11782            let range = selection.range().sorted();
11783            let buffer_start_row = range.start.row;
11784
11785            if range.start.row != range.end.row {
11786                let mut found = false;
11787                for row in range.start.row..=range.end.row {
11788                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11789                        found = true;
11790                        to_fold.push(crease);
11791                    }
11792                }
11793                if found {
11794                    continue;
11795                }
11796            }
11797
11798            for row in (0..=range.start.row).rev() {
11799                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11800                    if crease.range().end.row >= buffer_start_row {
11801                        to_fold.push(crease);
11802                    } else {
11803                        break;
11804                    }
11805                }
11806            }
11807        }
11808
11809        self.fold_creases(to_fold, true, window, cx);
11810    }
11811
11812    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11813        let buffer_row = fold_at.buffer_row;
11814        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11815
11816        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11817            let autoscroll = self
11818                .selections
11819                .all::<Point>(cx)
11820                .iter()
11821                .any(|selection| crease.range().overlaps(&selection.range()));
11822
11823            self.fold_creases(vec![crease], autoscroll, window, cx);
11824        }
11825    }
11826
11827    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11828        if self.is_singleton(cx) {
11829            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11830            let buffer = &display_map.buffer_snapshot;
11831            let selections = self.selections.all::<Point>(cx);
11832            let ranges = selections
11833                .iter()
11834                .map(|s| {
11835                    let range = s.display_range(&display_map).sorted();
11836                    let mut start = range.start.to_point(&display_map);
11837                    let mut end = range.end.to_point(&display_map);
11838                    start.column = 0;
11839                    end.column = buffer.line_len(MultiBufferRow(end.row));
11840                    start..end
11841                })
11842                .collect::<Vec<_>>();
11843
11844            self.unfold_ranges(&ranges, true, true, cx);
11845        } else {
11846            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11847            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11848                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11849                .map(|(snapshot, _, _)| snapshot.remote_id())
11850                .collect();
11851            for buffer_id in buffer_ids {
11852                self.unfold_buffer(buffer_id, cx);
11853            }
11854        }
11855    }
11856
11857    pub fn unfold_recursive(
11858        &mut self,
11859        _: &UnfoldRecursive,
11860        _window: &mut Window,
11861        cx: &mut Context<Self>,
11862    ) {
11863        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11864        let selections = self.selections.all::<Point>(cx);
11865        let ranges = selections
11866            .iter()
11867            .map(|s| {
11868                let mut range = s.display_range(&display_map).sorted();
11869                *range.start.column_mut() = 0;
11870                *range.end.column_mut() = display_map.line_len(range.end.row());
11871                let start = range.start.to_point(&display_map);
11872                let end = range.end.to_point(&display_map);
11873                start..end
11874            })
11875            .collect::<Vec<_>>();
11876
11877        self.unfold_ranges(&ranges, true, true, cx);
11878    }
11879
11880    pub fn unfold_at(
11881        &mut self,
11882        unfold_at: &UnfoldAt,
11883        _window: &mut Window,
11884        cx: &mut Context<Self>,
11885    ) {
11886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11887
11888        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11889            ..Point::new(
11890                unfold_at.buffer_row.0,
11891                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11892            );
11893
11894        let autoscroll = self
11895            .selections
11896            .all::<Point>(cx)
11897            .iter()
11898            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11899
11900        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11901    }
11902
11903    pub fn unfold_all(
11904        &mut self,
11905        _: &actions::UnfoldAll,
11906        _window: &mut Window,
11907        cx: &mut Context<Self>,
11908    ) {
11909        if self.buffer.read(cx).is_singleton() {
11910            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11911            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11912        } else {
11913            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11914                editor
11915                    .update(&mut cx, |editor, cx| {
11916                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11917                            editor.unfold_buffer(buffer_id, cx);
11918                        }
11919                    })
11920                    .ok();
11921            });
11922        }
11923    }
11924
11925    pub fn fold_selected_ranges(
11926        &mut self,
11927        _: &FoldSelectedRanges,
11928        window: &mut Window,
11929        cx: &mut Context<Self>,
11930    ) {
11931        let selections = self.selections.all::<Point>(cx);
11932        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11933        let line_mode = self.selections.line_mode;
11934        let ranges = selections
11935            .into_iter()
11936            .map(|s| {
11937                if line_mode {
11938                    let start = Point::new(s.start.row, 0);
11939                    let end = Point::new(
11940                        s.end.row,
11941                        display_map
11942                            .buffer_snapshot
11943                            .line_len(MultiBufferRow(s.end.row)),
11944                    );
11945                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11946                } else {
11947                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11948                }
11949            })
11950            .collect::<Vec<_>>();
11951        self.fold_creases(ranges, true, window, cx);
11952    }
11953
11954    pub fn fold_ranges<T: ToOffset + Clone>(
11955        &mut self,
11956        ranges: Vec<Range<T>>,
11957        auto_scroll: bool,
11958        window: &mut Window,
11959        cx: &mut Context<Self>,
11960    ) {
11961        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11962        let ranges = ranges
11963            .into_iter()
11964            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11965            .collect::<Vec<_>>();
11966        self.fold_creases(ranges, auto_scroll, window, cx);
11967    }
11968
11969    pub fn fold_creases<T: ToOffset + Clone>(
11970        &mut self,
11971        creases: Vec<Crease<T>>,
11972        auto_scroll: bool,
11973        window: &mut Window,
11974        cx: &mut Context<Self>,
11975    ) {
11976        if creases.is_empty() {
11977            return;
11978        }
11979
11980        let mut buffers_affected = HashSet::default();
11981        let multi_buffer = self.buffer().read(cx);
11982        for crease in &creases {
11983            if let Some((_, buffer, _)) =
11984                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11985            {
11986                buffers_affected.insert(buffer.read(cx).remote_id());
11987            };
11988        }
11989
11990        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11991
11992        if auto_scroll {
11993            self.request_autoscroll(Autoscroll::fit(), cx);
11994        }
11995
11996        cx.notify();
11997
11998        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11999            // Clear diagnostics block when folding a range that contains it.
12000            let snapshot = self.snapshot(window, cx);
12001            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12002                drop(snapshot);
12003                self.active_diagnostics = Some(active_diagnostics);
12004                self.dismiss_diagnostics(cx);
12005            } else {
12006                self.active_diagnostics = Some(active_diagnostics);
12007            }
12008        }
12009
12010        self.scrollbar_marker_state.dirty = true;
12011    }
12012
12013    /// Removes any folds whose ranges intersect any of the given ranges.
12014    pub fn unfold_ranges<T: ToOffset + Clone>(
12015        &mut self,
12016        ranges: &[Range<T>],
12017        inclusive: bool,
12018        auto_scroll: bool,
12019        cx: &mut Context<Self>,
12020    ) {
12021        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12022            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12023        });
12024    }
12025
12026    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12027        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12028            return;
12029        }
12030        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12031        self.display_map
12032            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12033        cx.emit(EditorEvent::BufferFoldToggled {
12034            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12035            folded: true,
12036        });
12037        cx.notify();
12038    }
12039
12040    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12041        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12042            return;
12043        }
12044        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12045        self.display_map.update(cx, |display_map, cx| {
12046            display_map.unfold_buffer(buffer_id, cx);
12047        });
12048        cx.emit(EditorEvent::BufferFoldToggled {
12049            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12050            folded: false,
12051        });
12052        cx.notify();
12053    }
12054
12055    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12056        self.display_map.read(cx).is_buffer_folded(buffer)
12057    }
12058
12059    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12060        self.display_map.read(cx).folded_buffers()
12061    }
12062
12063    /// Removes any folds with the given ranges.
12064    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12065        &mut self,
12066        ranges: &[Range<T>],
12067        type_id: TypeId,
12068        auto_scroll: bool,
12069        cx: &mut Context<Self>,
12070    ) {
12071        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12072            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12073        });
12074    }
12075
12076    fn remove_folds_with<T: ToOffset + Clone>(
12077        &mut self,
12078        ranges: &[Range<T>],
12079        auto_scroll: bool,
12080        cx: &mut Context<Self>,
12081        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12082    ) {
12083        if ranges.is_empty() {
12084            return;
12085        }
12086
12087        let mut buffers_affected = HashSet::default();
12088        let multi_buffer = self.buffer().read(cx);
12089        for range in ranges {
12090            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12091                buffers_affected.insert(buffer.read(cx).remote_id());
12092            };
12093        }
12094
12095        self.display_map.update(cx, update);
12096
12097        if auto_scroll {
12098            self.request_autoscroll(Autoscroll::fit(), cx);
12099        }
12100
12101        cx.notify();
12102        self.scrollbar_marker_state.dirty = true;
12103        self.active_indent_guides_state.dirty = true;
12104    }
12105
12106    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12107        self.display_map.read(cx).fold_placeholder.clone()
12108    }
12109
12110    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12111        self.buffer.update(cx, |buffer, cx| {
12112            buffer.set_all_diff_hunks_expanded(cx);
12113        });
12114    }
12115
12116    pub fn expand_all_diff_hunks(
12117        &mut self,
12118        _: &ExpandAllHunkDiffs,
12119        _window: &mut Window,
12120        cx: &mut Context<Self>,
12121    ) {
12122        self.buffer.update(cx, |buffer, cx| {
12123            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12124        });
12125    }
12126
12127    pub fn toggle_selected_diff_hunks(
12128        &mut self,
12129        _: &ToggleSelectedDiffHunks,
12130        _window: &mut Window,
12131        cx: &mut Context<Self>,
12132    ) {
12133        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12134        self.toggle_diff_hunks_in_ranges(ranges, cx);
12135    }
12136
12137    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12138        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12139        self.buffer
12140            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12141    }
12142
12143    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12144        self.buffer.update(cx, |buffer, cx| {
12145            let ranges = vec![Anchor::min()..Anchor::max()];
12146            if !buffer.all_diff_hunks_expanded()
12147                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12148            {
12149                buffer.collapse_diff_hunks(ranges, cx);
12150                true
12151            } else {
12152                false
12153            }
12154        })
12155    }
12156
12157    fn toggle_diff_hunks_in_ranges(
12158        &mut self,
12159        ranges: Vec<Range<Anchor>>,
12160        cx: &mut Context<'_, Editor>,
12161    ) {
12162        self.buffer.update(cx, |buffer, cx| {
12163            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12164                buffer.collapse_diff_hunks(ranges, cx)
12165            } else {
12166                buffer.expand_diff_hunks(ranges, cx)
12167            }
12168        })
12169    }
12170
12171    pub(crate) fn apply_all_diff_hunks(
12172        &mut self,
12173        _: &ApplyAllDiffHunks,
12174        window: &mut Window,
12175        cx: &mut Context<Self>,
12176    ) {
12177        let buffers = self.buffer.read(cx).all_buffers();
12178        for branch_buffer in buffers {
12179            branch_buffer.update(cx, |branch_buffer, cx| {
12180                branch_buffer.merge_into_base(Vec::new(), cx);
12181            });
12182        }
12183
12184        if let Some(project) = self.project.clone() {
12185            self.save(true, project, window, cx).detach_and_log_err(cx);
12186        }
12187    }
12188
12189    pub(crate) fn apply_selected_diff_hunks(
12190        &mut self,
12191        _: &ApplyDiffHunk,
12192        window: &mut Window,
12193        cx: &mut Context<Self>,
12194    ) {
12195        let snapshot = self.snapshot(window, cx);
12196        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12197        let mut ranges_by_buffer = HashMap::default();
12198        self.transact(window, cx, |editor, _window, cx| {
12199            for hunk in hunks {
12200                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12201                    ranges_by_buffer
12202                        .entry(buffer.clone())
12203                        .or_insert_with(Vec::new)
12204                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12205                }
12206            }
12207
12208            for (buffer, ranges) in ranges_by_buffer {
12209                buffer.update(cx, |buffer, cx| {
12210                    buffer.merge_into_base(ranges, cx);
12211                });
12212            }
12213        });
12214
12215        if let Some(project) = self.project.clone() {
12216            self.save(true, project, window, cx).detach_and_log_err(cx);
12217        }
12218    }
12219
12220    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12221        if hovered != self.gutter_hovered {
12222            self.gutter_hovered = hovered;
12223            cx.notify();
12224        }
12225    }
12226
12227    pub fn insert_blocks(
12228        &mut self,
12229        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12230        autoscroll: Option<Autoscroll>,
12231        cx: &mut Context<Self>,
12232    ) -> Vec<CustomBlockId> {
12233        let blocks = self
12234            .display_map
12235            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12236        if let Some(autoscroll) = autoscroll {
12237            self.request_autoscroll(autoscroll, cx);
12238        }
12239        cx.notify();
12240        blocks
12241    }
12242
12243    pub fn resize_blocks(
12244        &mut self,
12245        heights: HashMap<CustomBlockId, u32>,
12246        autoscroll: Option<Autoscroll>,
12247        cx: &mut Context<Self>,
12248    ) {
12249        self.display_map
12250            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12251        if let Some(autoscroll) = autoscroll {
12252            self.request_autoscroll(autoscroll, cx);
12253        }
12254        cx.notify();
12255    }
12256
12257    pub fn replace_blocks(
12258        &mut self,
12259        renderers: HashMap<CustomBlockId, RenderBlock>,
12260        autoscroll: Option<Autoscroll>,
12261        cx: &mut Context<Self>,
12262    ) {
12263        self.display_map
12264            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12265        if let Some(autoscroll) = autoscroll {
12266            self.request_autoscroll(autoscroll, cx);
12267        }
12268        cx.notify();
12269    }
12270
12271    pub fn remove_blocks(
12272        &mut self,
12273        block_ids: HashSet<CustomBlockId>,
12274        autoscroll: Option<Autoscroll>,
12275        cx: &mut Context<Self>,
12276    ) {
12277        self.display_map.update(cx, |display_map, cx| {
12278            display_map.remove_blocks(block_ids, cx)
12279        });
12280        if let Some(autoscroll) = autoscroll {
12281            self.request_autoscroll(autoscroll, cx);
12282        }
12283        cx.notify();
12284    }
12285
12286    pub fn row_for_block(
12287        &self,
12288        block_id: CustomBlockId,
12289        cx: &mut Context<Self>,
12290    ) -> Option<DisplayRow> {
12291        self.display_map
12292            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12293    }
12294
12295    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12296        self.focused_block = Some(focused_block);
12297    }
12298
12299    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12300        self.focused_block.take()
12301    }
12302
12303    pub fn insert_creases(
12304        &mut self,
12305        creases: impl IntoIterator<Item = Crease<Anchor>>,
12306        cx: &mut Context<Self>,
12307    ) -> Vec<CreaseId> {
12308        self.display_map
12309            .update(cx, |map, cx| map.insert_creases(creases, cx))
12310    }
12311
12312    pub fn remove_creases(
12313        &mut self,
12314        ids: impl IntoIterator<Item = CreaseId>,
12315        cx: &mut Context<Self>,
12316    ) {
12317        self.display_map
12318            .update(cx, |map, cx| map.remove_creases(ids, cx));
12319    }
12320
12321    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12322        self.display_map
12323            .update(cx, |map, cx| map.snapshot(cx))
12324            .longest_row()
12325    }
12326
12327    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12328        self.display_map
12329            .update(cx, |map, cx| map.snapshot(cx))
12330            .max_point()
12331    }
12332
12333    pub fn text(&self, cx: &App) -> String {
12334        self.buffer.read(cx).read(cx).text()
12335    }
12336
12337    pub fn is_empty(&self, cx: &App) -> bool {
12338        self.buffer.read(cx).read(cx).is_empty()
12339    }
12340
12341    pub fn text_option(&self, cx: &App) -> Option<String> {
12342        let text = self.text(cx);
12343        let text = text.trim();
12344
12345        if text.is_empty() {
12346            return None;
12347        }
12348
12349        Some(text.to_string())
12350    }
12351
12352    pub fn set_text(
12353        &mut self,
12354        text: impl Into<Arc<str>>,
12355        window: &mut Window,
12356        cx: &mut Context<Self>,
12357    ) {
12358        self.transact(window, cx, |this, _, cx| {
12359            this.buffer
12360                .read(cx)
12361                .as_singleton()
12362                .expect("you can only call set_text on editors for singleton buffers")
12363                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12364        });
12365    }
12366
12367    pub fn display_text(&self, cx: &mut App) -> String {
12368        self.display_map
12369            .update(cx, |map, cx| map.snapshot(cx))
12370            .text()
12371    }
12372
12373    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12374        let mut wrap_guides = smallvec::smallvec![];
12375
12376        if self.show_wrap_guides == Some(false) {
12377            return wrap_guides;
12378        }
12379
12380        let settings = self.buffer.read(cx).settings_at(0, cx);
12381        if settings.show_wrap_guides {
12382            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12383                wrap_guides.push((soft_wrap as usize, true));
12384            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12385                wrap_guides.push((soft_wrap as usize, true));
12386            }
12387            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12388        }
12389
12390        wrap_guides
12391    }
12392
12393    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12394        let settings = self.buffer.read(cx).settings_at(0, cx);
12395        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12396        match mode {
12397            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12398                SoftWrap::None
12399            }
12400            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12401            language_settings::SoftWrap::PreferredLineLength => {
12402                SoftWrap::Column(settings.preferred_line_length)
12403            }
12404            language_settings::SoftWrap::Bounded => {
12405                SoftWrap::Bounded(settings.preferred_line_length)
12406            }
12407        }
12408    }
12409
12410    pub fn set_soft_wrap_mode(
12411        &mut self,
12412        mode: language_settings::SoftWrap,
12413
12414        cx: &mut Context<Self>,
12415    ) {
12416        self.soft_wrap_mode_override = Some(mode);
12417        cx.notify();
12418    }
12419
12420    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12421        self.text_style_refinement = Some(style);
12422    }
12423
12424    /// called by the Element so we know what style we were most recently rendered with.
12425    pub(crate) fn set_style(
12426        &mut self,
12427        style: EditorStyle,
12428        window: &mut Window,
12429        cx: &mut Context<Self>,
12430    ) {
12431        let rem_size = window.rem_size();
12432        self.display_map.update(cx, |map, cx| {
12433            map.set_font(
12434                style.text.font(),
12435                style.text.font_size.to_pixels(rem_size),
12436                cx,
12437            )
12438        });
12439        self.style = Some(style);
12440    }
12441
12442    pub fn style(&self) -> Option<&EditorStyle> {
12443        self.style.as_ref()
12444    }
12445
12446    // Called by the element. This method is not designed to be called outside of the editor
12447    // element's layout code because it does not notify when rewrapping is computed synchronously.
12448    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12449        self.display_map
12450            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12451    }
12452
12453    pub fn set_soft_wrap(&mut self) {
12454        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12455    }
12456
12457    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12458        if self.soft_wrap_mode_override.is_some() {
12459            self.soft_wrap_mode_override.take();
12460        } else {
12461            let soft_wrap = match self.soft_wrap_mode(cx) {
12462                SoftWrap::GitDiff => return,
12463                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12464                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12465                    language_settings::SoftWrap::None
12466                }
12467            };
12468            self.soft_wrap_mode_override = Some(soft_wrap);
12469        }
12470        cx.notify();
12471    }
12472
12473    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12474        let Some(workspace) = self.workspace() else {
12475            return;
12476        };
12477        let fs = workspace.read(cx).app_state().fs.clone();
12478        let current_show = TabBarSettings::get_global(cx).show;
12479        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12480            setting.show = Some(!current_show);
12481        });
12482    }
12483
12484    pub fn toggle_indent_guides(
12485        &mut self,
12486        _: &ToggleIndentGuides,
12487        _: &mut Window,
12488        cx: &mut Context<Self>,
12489    ) {
12490        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12491            self.buffer
12492                .read(cx)
12493                .settings_at(0, cx)
12494                .indent_guides
12495                .enabled
12496        });
12497        self.show_indent_guides = Some(!currently_enabled);
12498        cx.notify();
12499    }
12500
12501    fn should_show_indent_guides(&self) -> Option<bool> {
12502        self.show_indent_guides
12503    }
12504
12505    pub fn toggle_line_numbers(
12506        &mut self,
12507        _: &ToggleLineNumbers,
12508        _: &mut Window,
12509        cx: &mut Context<Self>,
12510    ) {
12511        let mut editor_settings = EditorSettings::get_global(cx).clone();
12512        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12513        EditorSettings::override_global(editor_settings, cx);
12514    }
12515
12516    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12517        self.use_relative_line_numbers
12518            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12519    }
12520
12521    pub fn toggle_relative_line_numbers(
12522        &mut self,
12523        _: &ToggleRelativeLineNumbers,
12524        _: &mut Window,
12525        cx: &mut Context<Self>,
12526    ) {
12527        let is_relative = self.should_use_relative_line_numbers(cx);
12528        self.set_relative_line_number(Some(!is_relative), cx)
12529    }
12530
12531    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12532        self.use_relative_line_numbers = is_relative;
12533        cx.notify();
12534    }
12535
12536    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12537        self.show_gutter = show_gutter;
12538        cx.notify();
12539    }
12540
12541    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12542        self.show_scrollbars = show_scrollbars;
12543        cx.notify();
12544    }
12545
12546    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12547        self.show_line_numbers = Some(show_line_numbers);
12548        cx.notify();
12549    }
12550
12551    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12552        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12553        cx.notify();
12554    }
12555
12556    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12557        self.show_code_actions = Some(show_code_actions);
12558        cx.notify();
12559    }
12560
12561    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12562        self.show_runnables = Some(show_runnables);
12563        cx.notify();
12564    }
12565
12566    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12567        if self.display_map.read(cx).masked != masked {
12568            self.display_map.update(cx, |map, _| map.masked = masked);
12569        }
12570        cx.notify()
12571    }
12572
12573    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12574        self.show_wrap_guides = Some(show_wrap_guides);
12575        cx.notify();
12576    }
12577
12578    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12579        self.show_indent_guides = Some(show_indent_guides);
12580        cx.notify();
12581    }
12582
12583    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12584        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12585            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12586                if let Some(dir) = file.abs_path(cx).parent() {
12587                    return Some(dir.to_owned());
12588                }
12589            }
12590
12591            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12592                return Some(project_path.path.to_path_buf());
12593            }
12594        }
12595
12596        None
12597    }
12598
12599    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12600        self.active_excerpt(cx)?
12601            .1
12602            .read(cx)
12603            .file()
12604            .and_then(|f| f.as_local())
12605    }
12606
12607    fn target_file_abs_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            project.absolute_path(&project_path, cx)
12612        })
12613    }
12614
12615    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12616        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12617            let project_path = buffer.read(cx).project_path(cx)?;
12618            let project = self.project.as_ref()?.read(cx);
12619            let entry = project.entry_for_path(&project_path, cx)?;
12620            let path = entry.path.to_path_buf();
12621            Some(path)
12622        })
12623    }
12624
12625    pub fn reveal_in_finder(
12626        &mut self,
12627        _: &RevealInFileManager,
12628        _window: &mut Window,
12629        cx: &mut Context<Self>,
12630    ) {
12631        if let Some(target) = self.target_file(cx) {
12632            cx.reveal_path(&target.abs_path(cx));
12633        }
12634    }
12635
12636    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12637        if let Some(path) = self.target_file_abs_path(cx) {
12638            if let Some(path) = path.to_str() {
12639                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12640            }
12641        }
12642    }
12643
12644    pub fn copy_relative_path(
12645        &mut self,
12646        _: &CopyRelativePath,
12647        _window: &mut Window,
12648        cx: &mut Context<Self>,
12649    ) {
12650        if let Some(path) = self.target_file_path(cx) {
12651            if let Some(path) = path.to_str() {
12652                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12653            }
12654        }
12655    }
12656
12657    pub fn toggle_git_blame(
12658        &mut self,
12659        _: &ToggleGitBlame,
12660        window: &mut Window,
12661        cx: &mut Context<Self>,
12662    ) {
12663        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12664
12665        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12666            self.start_git_blame(true, window, cx);
12667        }
12668
12669        cx.notify();
12670    }
12671
12672    pub fn toggle_git_blame_inline(
12673        &mut self,
12674        _: &ToggleGitBlameInline,
12675        window: &mut Window,
12676        cx: &mut Context<Self>,
12677    ) {
12678        self.toggle_git_blame_inline_internal(true, window, cx);
12679        cx.notify();
12680    }
12681
12682    pub fn git_blame_inline_enabled(&self) -> bool {
12683        self.git_blame_inline_enabled
12684    }
12685
12686    pub fn toggle_selection_menu(
12687        &mut self,
12688        _: &ToggleSelectionMenu,
12689        _: &mut Window,
12690        cx: &mut Context<Self>,
12691    ) {
12692        self.show_selection_menu = self
12693            .show_selection_menu
12694            .map(|show_selections_menu| !show_selections_menu)
12695            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12696
12697        cx.notify();
12698    }
12699
12700    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12701        self.show_selection_menu
12702            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12703    }
12704
12705    fn start_git_blame(
12706        &mut self,
12707        user_triggered: bool,
12708        window: &mut Window,
12709        cx: &mut Context<Self>,
12710    ) {
12711        if let Some(project) = self.project.as_ref() {
12712            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12713                return;
12714            };
12715
12716            if buffer.read(cx).file().is_none() {
12717                return;
12718            }
12719
12720            let focused = self.focus_handle(cx).contains_focused(window, cx);
12721
12722            let project = project.clone();
12723            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12724            self.blame_subscription =
12725                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12726            self.blame = Some(blame);
12727        }
12728    }
12729
12730    fn toggle_git_blame_inline_internal(
12731        &mut self,
12732        user_triggered: bool,
12733        window: &mut Window,
12734        cx: &mut Context<Self>,
12735    ) {
12736        if self.git_blame_inline_enabled {
12737            self.git_blame_inline_enabled = false;
12738            self.show_git_blame_inline = false;
12739            self.show_git_blame_inline_delay_task.take();
12740        } else {
12741            self.git_blame_inline_enabled = true;
12742            self.start_git_blame_inline(user_triggered, window, cx);
12743        }
12744
12745        cx.notify();
12746    }
12747
12748    fn start_git_blame_inline(
12749        &mut self,
12750        user_triggered: bool,
12751        window: &mut Window,
12752        cx: &mut Context<Self>,
12753    ) {
12754        self.start_git_blame(user_triggered, window, cx);
12755
12756        if ProjectSettings::get_global(cx)
12757            .git
12758            .inline_blame_delay()
12759            .is_some()
12760        {
12761            self.start_inline_blame_timer(window, cx);
12762        } else {
12763            self.show_git_blame_inline = true
12764        }
12765    }
12766
12767    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12768        self.blame.as_ref()
12769    }
12770
12771    pub fn show_git_blame_gutter(&self) -> bool {
12772        self.show_git_blame_gutter
12773    }
12774
12775    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12776        self.show_git_blame_gutter && self.has_blame_entries(cx)
12777    }
12778
12779    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12780        self.show_git_blame_inline
12781            && self.focus_handle.is_focused(window)
12782            && !self.newest_selection_head_on_empty_line(cx)
12783            && self.has_blame_entries(cx)
12784    }
12785
12786    fn has_blame_entries(&self, cx: &App) -> bool {
12787        self.blame()
12788            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12789    }
12790
12791    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12792        let cursor_anchor = self.selections.newest_anchor().head();
12793
12794        let snapshot = self.buffer.read(cx).snapshot(cx);
12795        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12796
12797        snapshot.line_len(buffer_row) == 0
12798    }
12799
12800    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12801        let buffer_and_selection = maybe!({
12802            let selection = self.selections.newest::<Point>(cx);
12803            let selection_range = selection.range();
12804
12805            let multi_buffer = self.buffer().read(cx);
12806            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12807            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12808
12809            let (buffer, range, _) = if selection.reversed {
12810                buffer_ranges.first()
12811            } else {
12812                buffer_ranges.last()
12813            }?;
12814
12815            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12816                ..text::ToPoint::to_point(&range.end, &buffer).row;
12817            Some((
12818                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12819                selection,
12820            ))
12821        });
12822
12823        let Some((buffer, selection)) = buffer_and_selection else {
12824            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12825        };
12826
12827        let Some(project) = self.project.as_ref() else {
12828            return Task::ready(Err(anyhow!("editor does not have project")));
12829        };
12830
12831        project.update(cx, |project, cx| {
12832            project.get_permalink_to_line(&buffer, selection, cx)
12833        })
12834    }
12835
12836    pub fn copy_permalink_to_line(
12837        &mut self,
12838        _: &CopyPermalinkToLine,
12839        window: &mut Window,
12840        cx: &mut Context<Self>,
12841    ) {
12842        let permalink_task = self.get_permalink_to_line(cx);
12843        let workspace = self.workspace();
12844
12845        cx.spawn_in(window, |_, mut cx| async move {
12846            match permalink_task.await {
12847                Ok(permalink) => {
12848                    cx.update(|_, cx| {
12849                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12850                    })
12851                    .ok();
12852                }
12853                Err(err) => {
12854                    let message = format!("Failed to copy permalink: {err}");
12855
12856                    Err::<(), anyhow::Error>(err).log_err();
12857
12858                    if let Some(workspace) = workspace {
12859                        workspace
12860                            .update_in(&mut cx, |workspace, _, cx| {
12861                                struct CopyPermalinkToLine;
12862
12863                                workspace.show_toast(
12864                                    Toast::new(
12865                                        NotificationId::unique::<CopyPermalinkToLine>(),
12866                                        message,
12867                                    ),
12868                                    cx,
12869                                )
12870                            })
12871                            .ok();
12872                    }
12873                }
12874            }
12875        })
12876        .detach();
12877    }
12878
12879    pub fn copy_file_location(
12880        &mut self,
12881        _: &CopyFileLocation,
12882        _: &mut Window,
12883        cx: &mut Context<Self>,
12884    ) {
12885        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12886        if let Some(file) = self.target_file(cx) {
12887            if let Some(path) = file.path().to_str() {
12888                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12889            }
12890        }
12891    }
12892
12893    pub fn open_permalink_to_line(
12894        &mut self,
12895        _: &OpenPermalinkToLine,
12896        window: &mut Window,
12897        cx: &mut Context<Self>,
12898    ) {
12899        let permalink_task = self.get_permalink_to_line(cx);
12900        let workspace = self.workspace();
12901
12902        cx.spawn_in(window, |_, mut cx| async move {
12903            match permalink_task.await {
12904                Ok(permalink) => {
12905                    cx.update(|_, cx| {
12906                        cx.open_url(permalink.as_ref());
12907                    })
12908                    .ok();
12909                }
12910                Err(err) => {
12911                    let message = format!("Failed to open permalink: {err}");
12912
12913                    Err::<(), anyhow::Error>(err).log_err();
12914
12915                    if let Some(workspace) = workspace {
12916                        workspace
12917                            .update(&mut cx, |workspace, cx| {
12918                                struct OpenPermalinkToLine;
12919
12920                                workspace.show_toast(
12921                                    Toast::new(
12922                                        NotificationId::unique::<OpenPermalinkToLine>(),
12923                                        message,
12924                                    ),
12925                                    cx,
12926                                )
12927                            })
12928                            .ok();
12929                    }
12930                }
12931            }
12932        })
12933        .detach();
12934    }
12935
12936    pub fn insert_uuid_v4(
12937        &mut self,
12938        _: &InsertUuidV4,
12939        window: &mut Window,
12940        cx: &mut Context<Self>,
12941    ) {
12942        self.insert_uuid(UuidVersion::V4, window, cx);
12943    }
12944
12945    pub fn insert_uuid_v7(
12946        &mut self,
12947        _: &InsertUuidV7,
12948        window: &mut Window,
12949        cx: &mut Context<Self>,
12950    ) {
12951        self.insert_uuid(UuidVersion::V7, window, cx);
12952    }
12953
12954    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12955        self.transact(window, cx, |this, window, cx| {
12956            let edits = this
12957                .selections
12958                .all::<Point>(cx)
12959                .into_iter()
12960                .map(|selection| {
12961                    let uuid = match version {
12962                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12963                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12964                    };
12965
12966                    (selection.range(), uuid.to_string())
12967                });
12968            this.edit(edits, cx);
12969            this.refresh_inline_completion(true, false, window, cx);
12970        });
12971    }
12972
12973    pub fn open_selections_in_multibuffer(
12974        &mut self,
12975        _: &OpenSelectionsInMultibuffer,
12976        window: &mut Window,
12977        cx: &mut Context<Self>,
12978    ) {
12979        let multibuffer = self.buffer.read(cx);
12980
12981        let Some(buffer) = multibuffer.as_singleton() else {
12982            return;
12983        };
12984
12985        let Some(workspace) = self.workspace() else {
12986            return;
12987        };
12988
12989        let locations = self
12990            .selections
12991            .disjoint_anchors()
12992            .iter()
12993            .map(|range| Location {
12994                buffer: buffer.clone(),
12995                range: range.start.text_anchor..range.end.text_anchor,
12996            })
12997            .collect::<Vec<_>>();
12998
12999        let title = multibuffer.title(cx).to_string();
13000
13001        cx.spawn_in(window, |_, mut cx| async move {
13002            workspace.update_in(&mut cx, |workspace, window, cx| {
13003                Self::open_locations_in_multibuffer(
13004                    workspace,
13005                    locations,
13006                    format!("Selections for '{title}'"),
13007                    false,
13008                    MultibufferSelectionMode::All,
13009                    window,
13010                    cx,
13011                );
13012            })
13013        })
13014        .detach();
13015    }
13016
13017    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13018    /// last highlight added will be used.
13019    ///
13020    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13021    pub fn highlight_rows<T: 'static>(
13022        &mut self,
13023        range: Range<Anchor>,
13024        color: Hsla,
13025        should_autoscroll: bool,
13026        cx: &mut Context<Self>,
13027    ) {
13028        let snapshot = self.buffer().read(cx).snapshot(cx);
13029        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13030        let ix = row_highlights.binary_search_by(|highlight| {
13031            Ordering::Equal
13032                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13033                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13034        });
13035
13036        if let Err(mut ix) = ix {
13037            let index = post_inc(&mut self.highlight_order);
13038
13039            // If this range intersects with the preceding highlight, then merge it with
13040            // the preceding highlight. Otherwise insert a new highlight.
13041            let mut merged = false;
13042            if ix > 0 {
13043                let prev_highlight = &mut row_highlights[ix - 1];
13044                if prev_highlight
13045                    .range
13046                    .end
13047                    .cmp(&range.start, &snapshot)
13048                    .is_ge()
13049                {
13050                    ix -= 1;
13051                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13052                        prev_highlight.range.end = range.end;
13053                    }
13054                    merged = true;
13055                    prev_highlight.index = index;
13056                    prev_highlight.color = color;
13057                    prev_highlight.should_autoscroll = should_autoscroll;
13058                }
13059            }
13060
13061            if !merged {
13062                row_highlights.insert(
13063                    ix,
13064                    RowHighlight {
13065                        range: range.clone(),
13066                        index,
13067                        color,
13068                        should_autoscroll,
13069                    },
13070                );
13071            }
13072
13073            // If any of the following highlights intersect with this one, merge them.
13074            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13075                let highlight = &row_highlights[ix];
13076                if next_highlight
13077                    .range
13078                    .start
13079                    .cmp(&highlight.range.end, &snapshot)
13080                    .is_le()
13081                {
13082                    if next_highlight
13083                        .range
13084                        .end
13085                        .cmp(&highlight.range.end, &snapshot)
13086                        .is_gt()
13087                    {
13088                        row_highlights[ix].range.end = next_highlight.range.end;
13089                    }
13090                    row_highlights.remove(ix + 1);
13091                } else {
13092                    break;
13093                }
13094            }
13095        }
13096    }
13097
13098    /// Remove any highlighted row ranges of the given type that intersect the
13099    /// given ranges.
13100    pub fn remove_highlighted_rows<T: 'static>(
13101        &mut self,
13102        ranges_to_remove: Vec<Range<Anchor>>,
13103        cx: &mut Context<Self>,
13104    ) {
13105        let snapshot = self.buffer().read(cx).snapshot(cx);
13106        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13107        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13108        row_highlights.retain(|highlight| {
13109            while let Some(range_to_remove) = ranges_to_remove.peek() {
13110                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13111                    Ordering::Less | Ordering::Equal => {
13112                        ranges_to_remove.next();
13113                    }
13114                    Ordering::Greater => {
13115                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13116                            Ordering::Less | Ordering::Equal => {
13117                                return false;
13118                            }
13119                            Ordering::Greater => break,
13120                        }
13121                    }
13122                }
13123            }
13124
13125            true
13126        })
13127    }
13128
13129    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13130    pub fn clear_row_highlights<T: 'static>(&mut self) {
13131        self.highlighted_rows.remove(&TypeId::of::<T>());
13132    }
13133
13134    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13135    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13136        self.highlighted_rows
13137            .get(&TypeId::of::<T>())
13138            .map_or(&[] as &[_], |vec| vec.as_slice())
13139            .iter()
13140            .map(|highlight| (highlight.range.clone(), highlight.color))
13141    }
13142
13143    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13144    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13145    /// Allows to ignore certain kinds of highlights.
13146    pub fn highlighted_display_rows(
13147        &self,
13148        window: &mut Window,
13149        cx: &mut App,
13150    ) -> BTreeMap<DisplayRow, Hsla> {
13151        let snapshot = self.snapshot(window, cx);
13152        let mut used_highlight_orders = HashMap::default();
13153        self.highlighted_rows
13154            .iter()
13155            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13156            .fold(
13157                BTreeMap::<DisplayRow, Hsla>::new(),
13158                |mut unique_rows, highlight| {
13159                    let start = highlight.range.start.to_display_point(&snapshot);
13160                    let end = highlight.range.end.to_display_point(&snapshot);
13161                    let start_row = start.row().0;
13162                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13163                        && end.column() == 0
13164                    {
13165                        end.row().0.saturating_sub(1)
13166                    } else {
13167                        end.row().0
13168                    };
13169                    for row in start_row..=end_row {
13170                        let used_index =
13171                            used_highlight_orders.entry(row).or_insert(highlight.index);
13172                        if highlight.index >= *used_index {
13173                            *used_index = highlight.index;
13174                            unique_rows.insert(DisplayRow(row), highlight.color);
13175                        }
13176                    }
13177                    unique_rows
13178                },
13179            )
13180    }
13181
13182    pub fn highlighted_display_row_for_autoscroll(
13183        &self,
13184        snapshot: &DisplaySnapshot,
13185    ) -> Option<DisplayRow> {
13186        self.highlighted_rows
13187            .values()
13188            .flat_map(|highlighted_rows| highlighted_rows.iter())
13189            .filter_map(|highlight| {
13190                if highlight.should_autoscroll {
13191                    Some(highlight.range.start.to_display_point(snapshot).row())
13192                } else {
13193                    None
13194                }
13195            })
13196            .min()
13197    }
13198
13199    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13200        self.highlight_background::<SearchWithinRange>(
13201            ranges,
13202            |colors| colors.editor_document_highlight_read_background,
13203            cx,
13204        )
13205    }
13206
13207    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13208        self.breadcrumb_header = Some(new_header);
13209    }
13210
13211    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13212        self.clear_background_highlights::<SearchWithinRange>(cx);
13213    }
13214
13215    pub fn highlight_background<T: 'static>(
13216        &mut self,
13217        ranges: &[Range<Anchor>],
13218        color_fetcher: fn(&ThemeColors) -> Hsla,
13219        cx: &mut Context<Self>,
13220    ) {
13221        self.background_highlights
13222            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13223        self.scrollbar_marker_state.dirty = true;
13224        cx.notify();
13225    }
13226
13227    pub fn clear_background_highlights<T: 'static>(
13228        &mut self,
13229        cx: &mut Context<Self>,
13230    ) -> Option<BackgroundHighlight> {
13231        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13232        if !text_highlights.1.is_empty() {
13233            self.scrollbar_marker_state.dirty = true;
13234            cx.notify();
13235        }
13236        Some(text_highlights)
13237    }
13238
13239    pub fn highlight_gutter<T: 'static>(
13240        &mut self,
13241        ranges: &[Range<Anchor>],
13242        color_fetcher: fn(&App) -> Hsla,
13243        cx: &mut Context<Self>,
13244    ) {
13245        self.gutter_highlights
13246            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13247        cx.notify();
13248    }
13249
13250    pub fn clear_gutter_highlights<T: 'static>(
13251        &mut self,
13252        cx: &mut Context<Self>,
13253    ) -> Option<GutterHighlight> {
13254        cx.notify();
13255        self.gutter_highlights.remove(&TypeId::of::<T>())
13256    }
13257
13258    #[cfg(feature = "test-support")]
13259    pub fn all_text_background_highlights(
13260        &self,
13261        window: &mut Window,
13262        cx: &mut Context<Self>,
13263    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13264        let snapshot = self.snapshot(window, cx);
13265        let buffer = &snapshot.buffer_snapshot;
13266        let start = buffer.anchor_before(0);
13267        let end = buffer.anchor_after(buffer.len());
13268        let theme = cx.theme().colors();
13269        self.background_highlights_in_range(start..end, &snapshot, theme)
13270    }
13271
13272    #[cfg(feature = "test-support")]
13273    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13274        let snapshot = self.buffer().read(cx).snapshot(cx);
13275
13276        let highlights = self
13277            .background_highlights
13278            .get(&TypeId::of::<items::BufferSearchHighlights>());
13279
13280        if let Some((_color, ranges)) = highlights {
13281            ranges
13282                .iter()
13283                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13284                .collect_vec()
13285        } else {
13286            vec![]
13287        }
13288    }
13289
13290    fn document_highlights_for_position<'a>(
13291        &'a self,
13292        position: Anchor,
13293        buffer: &'a MultiBufferSnapshot,
13294    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13295        let read_highlights = self
13296            .background_highlights
13297            .get(&TypeId::of::<DocumentHighlightRead>())
13298            .map(|h| &h.1);
13299        let write_highlights = self
13300            .background_highlights
13301            .get(&TypeId::of::<DocumentHighlightWrite>())
13302            .map(|h| &h.1);
13303        let left_position = position.bias_left(buffer);
13304        let right_position = position.bias_right(buffer);
13305        read_highlights
13306            .into_iter()
13307            .chain(write_highlights)
13308            .flat_map(move |ranges| {
13309                let start_ix = match ranges.binary_search_by(|probe| {
13310                    let cmp = probe.end.cmp(&left_position, buffer);
13311                    if cmp.is_ge() {
13312                        Ordering::Greater
13313                    } else {
13314                        Ordering::Less
13315                    }
13316                }) {
13317                    Ok(i) | Err(i) => i,
13318                };
13319
13320                ranges[start_ix..]
13321                    .iter()
13322                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13323            })
13324    }
13325
13326    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13327        self.background_highlights
13328            .get(&TypeId::of::<T>())
13329            .map_or(false, |(_, highlights)| !highlights.is_empty())
13330    }
13331
13332    pub fn background_highlights_in_range(
13333        &self,
13334        search_range: Range<Anchor>,
13335        display_snapshot: &DisplaySnapshot,
13336        theme: &ThemeColors,
13337    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13338        let mut results = Vec::new();
13339        for (color_fetcher, ranges) in self.background_highlights.values() {
13340            let color = color_fetcher(theme);
13341            let start_ix = match ranges.binary_search_by(|probe| {
13342                let cmp = probe
13343                    .end
13344                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13345                if cmp.is_gt() {
13346                    Ordering::Greater
13347                } else {
13348                    Ordering::Less
13349                }
13350            }) {
13351                Ok(i) | Err(i) => i,
13352            };
13353            for range in &ranges[start_ix..] {
13354                if range
13355                    .start
13356                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13357                    .is_ge()
13358                {
13359                    break;
13360                }
13361
13362                let start = range.start.to_display_point(display_snapshot);
13363                let end = range.end.to_display_point(display_snapshot);
13364                results.push((start..end, color))
13365            }
13366        }
13367        results
13368    }
13369
13370    pub fn background_highlight_row_ranges<T: 'static>(
13371        &self,
13372        search_range: Range<Anchor>,
13373        display_snapshot: &DisplaySnapshot,
13374        count: usize,
13375    ) -> Vec<RangeInclusive<DisplayPoint>> {
13376        let mut results = Vec::new();
13377        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13378            return vec![];
13379        };
13380
13381        let start_ix = match ranges.binary_search_by(|probe| {
13382            let cmp = probe
13383                .end
13384                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13385            if cmp.is_gt() {
13386                Ordering::Greater
13387            } else {
13388                Ordering::Less
13389            }
13390        }) {
13391            Ok(i) | Err(i) => i,
13392        };
13393        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13394            if let (Some(start_display), Some(end_display)) = (start, end) {
13395                results.push(
13396                    start_display.to_display_point(display_snapshot)
13397                        ..=end_display.to_display_point(display_snapshot),
13398                );
13399            }
13400        };
13401        let mut start_row: Option<Point> = None;
13402        let mut end_row: Option<Point> = None;
13403        if ranges.len() > count {
13404            return Vec::new();
13405        }
13406        for range in &ranges[start_ix..] {
13407            if range
13408                .start
13409                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13410                .is_ge()
13411            {
13412                break;
13413            }
13414            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13415            if let Some(current_row) = &end_row {
13416                if end.row == current_row.row {
13417                    continue;
13418                }
13419            }
13420            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13421            if start_row.is_none() {
13422                assert_eq!(end_row, None);
13423                start_row = Some(start);
13424                end_row = Some(end);
13425                continue;
13426            }
13427            if let Some(current_end) = end_row.as_mut() {
13428                if start.row > current_end.row + 1 {
13429                    push_region(start_row, end_row);
13430                    start_row = Some(start);
13431                    end_row = Some(end);
13432                } else {
13433                    // Merge two hunks.
13434                    *current_end = end;
13435                }
13436            } else {
13437                unreachable!();
13438            }
13439        }
13440        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13441        push_region(start_row, end_row);
13442        results
13443    }
13444
13445    pub fn gutter_highlights_in_range(
13446        &self,
13447        search_range: Range<Anchor>,
13448        display_snapshot: &DisplaySnapshot,
13449        cx: &App,
13450    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13451        let mut results = Vec::new();
13452        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13453            let color = color_fetcher(cx);
13454            let start_ix = match ranges.binary_search_by(|probe| {
13455                let cmp = probe
13456                    .end
13457                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13458                if cmp.is_gt() {
13459                    Ordering::Greater
13460                } else {
13461                    Ordering::Less
13462                }
13463            }) {
13464                Ok(i) | Err(i) => i,
13465            };
13466            for range in &ranges[start_ix..] {
13467                if range
13468                    .start
13469                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13470                    .is_ge()
13471                {
13472                    break;
13473                }
13474
13475                let start = range.start.to_display_point(display_snapshot);
13476                let end = range.end.to_display_point(display_snapshot);
13477                results.push((start..end, color))
13478            }
13479        }
13480        results
13481    }
13482
13483    /// Get the text ranges corresponding to the redaction query
13484    pub fn redacted_ranges(
13485        &self,
13486        search_range: Range<Anchor>,
13487        display_snapshot: &DisplaySnapshot,
13488        cx: &App,
13489    ) -> Vec<Range<DisplayPoint>> {
13490        display_snapshot
13491            .buffer_snapshot
13492            .redacted_ranges(search_range, |file| {
13493                if let Some(file) = file {
13494                    file.is_private()
13495                        && EditorSettings::get(
13496                            Some(SettingsLocation {
13497                                worktree_id: file.worktree_id(cx),
13498                                path: file.path().as_ref(),
13499                            }),
13500                            cx,
13501                        )
13502                        .redact_private_values
13503                } else {
13504                    false
13505                }
13506            })
13507            .map(|range| {
13508                range.start.to_display_point(display_snapshot)
13509                    ..range.end.to_display_point(display_snapshot)
13510            })
13511            .collect()
13512    }
13513
13514    pub fn highlight_text<T: 'static>(
13515        &mut self,
13516        ranges: Vec<Range<Anchor>>,
13517        style: HighlightStyle,
13518        cx: &mut Context<Self>,
13519    ) {
13520        self.display_map.update(cx, |map, _| {
13521            map.highlight_text(TypeId::of::<T>(), ranges, style)
13522        });
13523        cx.notify();
13524    }
13525
13526    pub(crate) fn highlight_inlays<T: 'static>(
13527        &mut self,
13528        highlights: Vec<InlayHighlight>,
13529        style: HighlightStyle,
13530        cx: &mut Context<Self>,
13531    ) {
13532        self.display_map.update(cx, |map, _| {
13533            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13534        });
13535        cx.notify();
13536    }
13537
13538    pub fn text_highlights<'a, T: 'static>(
13539        &'a self,
13540        cx: &'a App,
13541    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13542        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13543    }
13544
13545    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13546        let cleared = self
13547            .display_map
13548            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13549        if cleared {
13550            cx.notify();
13551        }
13552    }
13553
13554    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13555        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13556            && self.focus_handle.is_focused(window)
13557    }
13558
13559    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13560        self.show_cursor_when_unfocused = is_enabled;
13561        cx.notify();
13562    }
13563
13564    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13565        self.project
13566            .as_ref()
13567            .map(|project| project.read(cx).lsp_store())
13568    }
13569
13570    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13571        cx.notify();
13572    }
13573
13574    fn on_buffer_event(
13575        &mut self,
13576        multibuffer: &Entity<MultiBuffer>,
13577        event: &multi_buffer::Event,
13578        window: &mut Window,
13579        cx: &mut Context<Self>,
13580    ) {
13581        match event {
13582            multi_buffer::Event::Edited {
13583                singleton_buffer_edited,
13584                edited_buffer: buffer_edited,
13585            } => {
13586                self.scrollbar_marker_state.dirty = true;
13587                self.active_indent_guides_state.dirty = true;
13588                self.refresh_active_diagnostics(cx);
13589                self.refresh_code_actions(window, cx);
13590                if self.has_active_inline_completion() {
13591                    self.update_visible_inline_completion(window, cx);
13592                }
13593                if let Some(buffer) = buffer_edited {
13594                    let buffer_id = buffer.read(cx).remote_id();
13595                    if !self.registered_buffers.contains_key(&buffer_id) {
13596                        if let Some(lsp_store) = self.lsp_store(cx) {
13597                            lsp_store.update(cx, |lsp_store, cx| {
13598                                self.registered_buffers.insert(
13599                                    buffer_id,
13600                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13601                                );
13602                            })
13603                        }
13604                    }
13605                }
13606                cx.emit(EditorEvent::BufferEdited);
13607                cx.emit(SearchEvent::MatchesInvalidated);
13608                if *singleton_buffer_edited {
13609                    if let Some(project) = &self.project {
13610                        let project = project.read(cx);
13611                        #[allow(clippy::mutable_key_type)]
13612                        let languages_affected = multibuffer
13613                            .read(cx)
13614                            .all_buffers()
13615                            .into_iter()
13616                            .filter_map(|buffer| {
13617                                let buffer = buffer.read(cx);
13618                                let language = buffer.language()?;
13619                                if project.is_local()
13620                                    && project
13621                                        .language_servers_for_local_buffer(buffer, cx)
13622                                        .count()
13623                                        == 0
13624                                {
13625                                    None
13626                                } else {
13627                                    Some(language)
13628                                }
13629                            })
13630                            .cloned()
13631                            .collect::<HashSet<_>>();
13632                        if !languages_affected.is_empty() {
13633                            self.refresh_inlay_hints(
13634                                InlayHintRefreshReason::BufferEdited(languages_affected),
13635                                cx,
13636                            );
13637                        }
13638                    }
13639                }
13640
13641                let Some(project) = &self.project else { return };
13642                let (telemetry, is_via_ssh) = {
13643                    let project = project.read(cx);
13644                    let telemetry = project.client().telemetry().clone();
13645                    let is_via_ssh = project.is_via_ssh();
13646                    (telemetry, is_via_ssh)
13647                };
13648                refresh_linked_ranges(self, window, cx);
13649                telemetry.log_edit_event("editor", is_via_ssh);
13650            }
13651            multi_buffer::Event::ExcerptsAdded {
13652                buffer,
13653                predecessor,
13654                excerpts,
13655            } => {
13656                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13657                let buffer_id = buffer.read(cx).remote_id();
13658                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13659                    if let Some(project) = &self.project {
13660                        get_uncommitted_changes_for_buffer(
13661                            project,
13662                            [buffer.clone()],
13663                            self.buffer.clone(),
13664                            cx,
13665                        );
13666                    }
13667                }
13668                cx.emit(EditorEvent::ExcerptsAdded {
13669                    buffer: buffer.clone(),
13670                    predecessor: *predecessor,
13671                    excerpts: excerpts.clone(),
13672                });
13673                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13674            }
13675            multi_buffer::Event::ExcerptsRemoved { ids } => {
13676                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13677                let buffer = self.buffer.read(cx);
13678                self.registered_buffers
13679                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13680                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13681            }
13682            multi_buffer::Event::ExcerptsEdited { ids } => {
13683                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13684            }
13685            multi_buffer::Event::ExcerptsExpanded { ids } => {
13686                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13687                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13688            }
13689            multi_buffer::Event::Reparsed(buffer_id) => {
13690                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13691
13692                cx.emit(EditorEvent::Reparsed(*buffer_id));
13693            }
13694            multi_buffer::Event::DiffHunksToggled => {
13695                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13696            }
13697            multi_buffer::Event::LanguageChanged(buffer_id) => {
13698                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13699                cx.emit(EditorEvent::Reparsed(*buffer_id));
13700                cx.notify();
13701            }
13702            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13703            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13704            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13705                cx.emit(EditorEvent::TitleChanged)
13706            }
13707            // multi_buffer::Event::DiffBaseChanged => {
13708            //     self.scrollbar_marker_state.dirty = true;
13709            //     cx.emit(EditorEvent::DiffBaseChanged);
13710            //     cx.notify();
13711            // }
13712            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13713            multi_buffer::Event::DiagnosticsUpdated => {
13714                self.refresh_active_diagnostics(cx);
13715                self.scrollbar_marker_state.dirty = true;
13716                cx.notify();
13717            }
13718            _ => {}
13719        };
13720    }
13721
13722    fn on_display_map_changed(
13723        &mut self,
13724        _: Entity<DisplayMap>,
13725        _: &mut Window,
13726        cx: &mut Context<Self>,
13727    ) {
13728        cx.notify();
13729    }
13730
13731    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13732        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13733        self.refresh_inline_completion(true, false, window, cx);
13734        self.refresh_inlay_hints(
13735            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13736                self.selections.newest_anchor().head(),
13737                &self.buffer.read(cx).snapshot(cx),
13738                cx,
13739            )),
13740            cx,
13741        );
13742
13743        let old_cursor_shape = self.cursor_shape;
13744
13745        {
13746            let editor_settings = EditorSettings::get_global(cx);
13747            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13748            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13749            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13750        }
13751
13752        if old_cursor_shape != self.cursor_shape {
13753            cx.emit(EditorEvent::CursorShapeChanged);
13754        }
13755
13756        let project_settings = ProjectSettings::get_global(cx);
13757        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13758
13759        if self.mode == EditorMode::Full {
13760            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13761            if self.git_blame_inline_enabled != inline_blame_enabled {
13762                self.toggle_git_blame_inline_internal(false, window, cx);
13763            }
13764        }
13765
13766        cx.notify();
13767    }
13768
13769    pub fn set_searchable(&mut self, searchable: bool) {
13770        self.searchable = searchable;
13771    }
13772
13773    pub fn searchable(&self) -> bool {
13774        self.searchable
13775    }
13776
13777    fn open_proposed_changes_editor(
13778        &mut self,
13779        _: &OpenProposedChangesEditor,
13780        window: &mut Window,
13781        cx: &mut Context<Self>,
13782    ) {
13783        let Some(workspace) = self.workspace() else {
13784            cx.propagate();
13785            return;
13786        };
13787
13788        let selections = self.selections.all::<usize>(cx);
13789        let multi_buffer = self.buffer.read(cx);
13790        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13791        let mut new_selections_by_buffer = HashMap::default();
13792        for selection in selections {
13793            for (buffer, range, _) in
13794                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13795            {
13796                let mut range = range.to_point(buffer);
13797                range.start.column = 0;
13798                range.end.column = buffer.line_len(range.end.row);
13799                new_selections_by_buffer
13800                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13801                    .or_insert(Vec::new())
13802                    .push(range)
13803            }
13804        }
13805
13806        let proposed_changes_buffers = new_selections_by_buffer
13807            .into_iter()
13808            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13809            .collect::<Vec<_>>();
13810        let proposed_changes_editor = cx.new(|cx| {
13811            ProposedChangesEditor::new(
13812                "Proposed changes",
13813                proposed_changes_buffers,
13814                self.project.clone(),
13815                window,
13816                cx,
13817            )
13818        });
13819
13820        window.defer(cx, move |window, cx| {
13821            workspace.update(cx, |workspace, cx| {
13822                workspace.active_pane().update(cx, |pane, cx| {
13823                    pane.add_item(
13824                        Box::new(proposed_changes_editor),
13825                        true,
13826                        true,
13827                        None,
13828                        window,
13829                        cx,
13830                    );
13831                });
13832            });
13833        });
13834    }
13835
13836    pub fn open_excerpts_in_split(
13837        &mut self,
13838        _: &OpenExcerptsSplit,
13839        window: &mut Window,
13840        cx: &mut Context<Self>,
13841    ) {
13842        self.open_excerpts_common(None, true, window, cx)
13843    }
13844
13845    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13846        self.open_excerpts_common(None, false, window, cx)
13847    }
13848
13849    fn open_excerpts_common(
13850        &mut self,
13851        jump_data: Option<JumpData>,
13852        split: bool,
13853        window: &mut Window,
13854        cx: &mut Context<Self>,
13855    ) {
13856        let Some(workspace) = self.workspace() else {
13857            cx.propagate();
13858            return;
13859        };
13860
13861        if self.buffer.read(cx).is_singleton() {
13862            cx.propagate();
13863            return;
13864        }
13865
13866        let mut new_selections_by_buffer = HashMap::default();
13867        match &jump_data {
13868            Some(JumpData::MultiBufferPoint {
13869                excerpt_id,
13870                position,
13871                anchor,
13872                line_offset_from_top,
13873            }) => {
13874                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13875                if let Some(buffer) = multi_buffer_snapshot
13876                    .buffer_id_for_excerpt(*excerpt_id)
13877                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13878                {
13879                    let buffer_snapshot = buffer.read(cx).snapshot();
13880                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13881                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13882                    } else {
13883                        buffer_snapshot.clip_point(*position, Bias::Left)
13884                    };
13885                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13886                    new_selections_by_buffer.insert(
13887                        buffer,
13888                        (
13889                            vec![jump_to_offset..jump_to_offset],
13890                            Some(*line_offset_from_top),
13891                        ),
13892                    );
13893                }
13894            }
13895            Some(JumpData::MultiBufferRow {
13896                row,
13897                line_offset_from_top,
13898            }) => {
13899                let point = MultiBufferPoint::new(row.0, 0);
13900                if let Some((buffer, buffer_point, _)) =
13901                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13902                {
13903                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13904                    new_selections_by_buffer
13905                        .entry(buffer)
13906                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13907                        .0
13908                        .push(buffer_offset..buffer_offset)
13909                }
13910            }
13911            None => {
13912                let selections = self.selections.all::<usize>(cx);
13913                let multi_buffer = self.buffer.read(cx);
13914                for selection in selections {
13915                    for (buffer, mut range, _) in multi_buffer
13916                        .snapshot(cx)
13917                        .range_to_buffer_ranges(selection.range())
13918                    {
13919                        // When editing branch buffers, jump to the corresponding location
13920                        // in their base buffer.
13921                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13922                        let buffer = buffer_handle.read(cx);
13923                        if let Some(base_buffer) = buffer.base_buffer() {
13924                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13925                            buffer_handle = base_buffer;
13926                        }
13927
13928                        if selection.reversed {
13929                            mem::swap(&mut range.start, &mut range.end);
13930                        }
13931                        new_selections_by_buffer
13932                            .entry(buffer_handle)
13933                            .or_insert((Vec::new(), None))
13934                            .0
13935                            .push(range)
13936                    }
13937                }
13938            }
13939        }
13940
13941        if new_selections_by_buffer.is_empty() {
13942            return;
13943        }
13944
13945        // We defer the pane interaction because we ourselves are a workspace item
13946        // and activating a new item causes the pane to call a method on us reentrantly,
13947        // which panics if we're on the stack.
13948        window.defer(cx, move |window, cx| {
13949            workspace.update(cx, |workspace, cx| {
13950                let pane = if split {
13951                    workspace.adjacent_pane(window, cx)
13952                } else {
13953                    workspace.active_pane().clone()
13954                };
13955
13956                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13957                    let editor = buffer
13958                        .read(cx)
13959                        .file()
13960                        .is_none()
13961                        .then(|| {
13962                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13963                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13964                            // Instead, we try to activate the existing editor in the pane first.
13965                            let (editor, pane_item_index) =
13966                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13967                                    let editor = item.downcast::<Editor>()?;
13968                                    let singleton_buffer =
13969                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13970                                    if singleton_buffer == buffer {
13971                                        Some((editor, i))
13972                                    } else {
13973                                        None
13974                                    }
13975                                })?;
13976                            pane.update(cx, |pane, cx| {
13977                                pane.activate_item(pane_item_index, true, true, window, cx)
13978                            });
13979                            Some(editor)
13980                        })
13981                        .flatten()
13982                        .unwrap_or_else(|| {
13983                            workspace.open_project_item::<Self>(
13984                                pane.clone(),
13985                                buffer,
13986                                true,
13987                                true,
13988                                window,
13989                                cx,
13990                            )
13991                        });
13992
13993                    editor.update(cx, |editor, cx| {
13994                        let autoscroll = match scroll_offset {
13995                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13996                            None => Autoscroll::newest(),
13997                        };
13998                        let nav_history = editor.nav_history.take();
13999                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14000                            s.select_ranges(ranges);
14001                        });
14002                        editor.nav_history = nav_history;
14003                    });
14004                }
14005            })
14006        });
14007    }
14008
14009    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14010        let snapshot = self.buffer.read(cx).read(cx);
14011        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14012        Some(
14013            ranges
14014                .iter()
14015                .map(move |range| {
14016                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14017                })
14018                .collect(),
14019        )
14020    }
14021
14022    fn selection_replacement_ranges(
14023        &self,
14024        range: Range<OffsetUtf16>,
14025        cx: &mut App,
14026    ) -> Vec<Range<OffsetUtf16>> {
14027        let selections = self.selections.all::<OffsetUtf16>(cx);
14028        let newest_selection = selections
14029            .iter()
14030            .max_by_key(|selection| selection.id)
14031            .unwrap();
14032        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14033        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14034        let snapshot = self.buffer.read(cx).read(cx);
14035        selections
14036            .into_iter()
14037            .map(|mut selection| {
14038                selection.start.0 =
14039                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14040                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14041                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14042                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14043            })
14044            .collect()
14045    }
14046
14047    fn report_editor_event(
14048        &self,
14049        event_type: &'static str,
14050        file_extension: Option<String>,
14051        cx: &App,
14052    ) {
14053        if cfg!(any(test, feature = "test-support")) {
14054            return;
14055        }
14056
14057        let Some(project) = &self.project else { return };
14058
14059        // If None, we are in a file without an extension
14060        let file = self
14061            .buffer
14062            .read(cx)
14063            .as_singleton()
14064            .and_then(|b| b.read(cx).file());
14065        let file_extension = file_extension.or(file
14066            .as_ref()
14067            .and_then(|file| Path::new(file.file_name(cx)).extension())
14068            .and_then(|e| e.to_str())
14069            .map(|a| a.to_string()));
14070
14071        let vim_mode = cx
14072            .global::<SettingsStore>()
14073            .raw_user_settings()
14074            .get("vim_mode")
14075            == Some(&serde_json::Value::Bool(true));
14076
14077        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14078            == language::language_settings::InlineCompletionProvider::Copilot;
14079        let copilot_enabled_for_language = self
14080            .buffer
14081            .read(cx)
14082            .settings_at(0, cx)
14083            .show_inline_completions;
14084
14085        let project = project.read(cx);
14086        telemetry::event!(
14087            event_type,
14088            file_extension,
14089            vim_mode,
14090            copilot_enabled,
14091            copilot_enabled_for_language,
14092            is_via_ssh = project.is_via_ssh(),
14093        );
14094    }
14095
14096    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14097    /// with each line being an array of {text, highlight} objects.
14098    fn copy_highlight_json(
14099        &mut self,
14100        _: &CopyHighlightJson,
14101        window: &mut Window,
14102        cx: &mut Context<Self>,
14103    ) {
14104        #[derive(Serialize)]
14105        struct Chunk<'a> {
14106            text: String,
14107            highlight: Option<&'a str>,
14108        }
14109
14110        let snapshot = self.buffer.read(cx).snapshot(cx);
14111        let range = self
14112            .selected_text_range(false, window, cx)
14113            .and_then(|selection| {
14114                if selection.range.is_empty() {
14115                    None
14116                } else {
14117                    Some(selection.range)
14118                }
14119            })
14120            .unwrap_or_else(|| 0..snapshot.len());
14121
14122        let chunks = snapshot.chunks(range, true);
14123        let mut lines = Vec::new();
14124        let mut line: VecDeque<Chunk> = VecDeque::new();
14125
14126        let Some(style) = self.style.as_ref() else {
14127            return;
14128        };
14129
14130        for chunk in chunks {
14131            let highlight = chunk
14132                .syntax_highlight_id
14133                .and_then(|id| id.name(&style.syntax));
14134            let mut chunk_lines = chunk.text.split('\n').peekable();
14135            while let Some(text) = chunk_lines.next() {
14136                let mut merged_with_last_token = false;
14137                if let Some(last_token) = line.back_mut() {
14138                    if last_token.highlight == highlight {
14139                        last_token.text.push_str(text);
14140                        merged_with_last_token = true;
14141                    }
14142                }
14143
14144                if !merged_with_last_token {
14145                    line.push_back(Chunk {
14146                        text: text.into(),
14147                        highlight,
14148                    });
14149                }
14150
14151                if chunk_lines.peek().is_some() {
14152                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14153                        line.pop_front();
14154                    }
14155                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14156                        line.pop_back();
14157                    }
14158
14159                    lines.push(mem::take(&mut line));
14160                }
14161            }
14162        }
14163
14164        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14165            return;
14166        };
14167        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14168    }
14169
14170    pub fn open_context_menu(
14171        &mut self,
14172        _: &OpenContextMenu,
14173        window: &mut Window,
14174        cx: &mut Context<Self>,
14175    ) {
14176        self.request_autoscroll(Autoscroll::newest(), cx);
14177        let position = self.selections.newest_display(cx).start;
14178        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14179    }
14180
14181    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14182        &self.inlay_hint_cache
14183    }
14184
14185    pub fn replay_insert_event(
14186        &mut self,
14187        text: &str,
14188        relative_utf16_range: Option<Range<isize>>,
14189        window: &mut Window,
14190        cx: &mut Context<Self>,
14191    ) {
14192        if !self.input_enabled {
14193            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14194            return;
14195        }
14196        if let Some(relative_utf16_range) = relative_utf16_range {
14197            let selections = self.selections.all::<OffsetUtf16>(cx);
14198            self.change_selections(None, window, cx, |s| {
14199                let new_ranges = selections.into_iter().map(|range| {
14200                    let start = OffsetUtf16(
14201                        range
14202                            .head()
14203                            .0
14204                            .saturating_add_signed(relative_utf16_range.start),
14205                    );
14206                    let end = OffsetUtf16(
14207                        range
14208                            .head()
14209                            .0
14210                            .saturating_add_signed(relative_utf16_range.end),
14211                    );
14212                    start..end
14213                });
14214                s.select_ranges(new_ranges);
14215            });
14216        }
14217
14218        self.handle_input(text, window, cx);
14219    }
14220
14221    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14222        let Some(provider) = self.semantics_provider.as_ref() else {
14223            return false;
14224        };
14225
14226        let mut supports = false;
14227        self.buffer().read(cx).for_each_buffer(|buffer| {
14228            supports |= provider.supports_inlay_hints(buffer, cx);
14229        });
14230        supports
14231    }
14232    pub fn is_focused(&self, window: &mut Window) -> bool {
14233        self.focus_handle.is_focused(window)
14234    }
14235
14236    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14237        cx.emit(EditorEvent::Focused);
14238
14239        if let Some(descendant) = self
14240            .last_focused_descendant
14241            .take()
14242            .and_then(|descendant| descendant.upgrade())
14243        {
14244            window.focus(&descendant);
14245        } else {
14246            if let Some(blame) = self.blame.as_ref() {
14247                blame.update(cx, GitBlame::focus)
14248            }
14249
14250            self.blink_manager.update(cx, BlinkManager::enable);
14251            self.show_cursor_names(window, cx);
14252            self.buffer.update(cx, |buffer, cx| {
14253                buffer.finalize_last_transaction(cx);
14254                if self.leader_peer_id.is_none() {
14255                    buffer.set_active_selections(
14256                        &self.selections.disjoint_anchors(),
14257                        self.selections.line_mode,
14258                        self.cursor_shape,
14259                        cx,
14260                    );
14261                }
14262            });
14263        }
14264    }
14265
14266    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14267        cx.emit(EditorEvent::FocusedIn)
14268    }
14269
14270    fn handle_focus_out(
14271        &mut self,
14272        event: FocusOutEvent,
14273        _window: &mut Window,
14274        _cx: &mut Context<Self>,
14275    ) {
14276        if event.blurred != self.focus_handle {
14277            self.last_focused_descendant = Some(event.blurred);
14278        }
14279    }
14280
14281    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14282        self.blink_manager.update(cx, BlinkManager::disable);
14283        self.buffer
14284            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14285
14286        if let Some(blame) = self.blame.as_ref() {
14287            blame.update(cx, GitBlame::blur)
14288        }
14289        if !self.hover_state.focused(window, cx) {
14290            hide_hover(self, cx);
14291        }
14292
14293        self.hide_context_menu(window, cx);
14294        cx.emit(EditorEvent::Blurred);
14295        cx.notify();
14296    }
14297
14298    pub fn register_action<A: Action>(
14299        &mut self,
14300        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14301    ) -> Subscription {
14302        let id = self.next_editor_action_id.post_inc();
14303        let listener = Arc::new(listener);
14304        self.editor_actions.borrow_mut().insert(
14305            id,
14306            Box::new(move |window, _| {
14307                let listener = listener.clone();
14308                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14309                    let action = action.downcast_ref().unwrap();
14310                    if phase == DispatchPhase::Bubble {
14311                        listener(action, window, cx)
14312                    }
14313                })
14314            }),
14315        );
14316
14317        let editor_actions = self.editor_actions.clone();
14318        Subscription::new(move || {
14319            editor_actions.borrow_mut().remove(&id);
14320        })
14321    }
14322
14323    pub fn file_header_size(&self) -> u32 {
14324        FILE_HEADER_HEIGHT
14325    }
14326
14327    pub fn revert(
14328        &mut self,
14329        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14330        window: &mut Window,
14331        cx: &mut Context<Self>,
14332    ) {
14333        self.buffer().update(cx, |multi_buffer, cx| {
14334            for (buffer_id, changes) in revert_changes {
14335                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14336                    buffer.update(cx, |buffer, cx| {
14337                        buffer.edit(
14338                            changes.into_iter().map(|(range, text)| {
14339                                (range, text.to_string().map(Arc::<str>::from))
14340                            }),
14341                            None,
14342                            cx,
14343                        );
14344                    });
14345                }
14346            }
14347        });
14348        self.change_selections(None, window, cx, |selections| selections.refresh());
14349    }
14350
14351    pub fn to_pixel_point(
14352        &self,
14353        source: multi_buffer::Anchor,
14354        editor_snapshot: &EditorSnapshot,
14355        window: &mut Window,
14356    ) -> Option<gpui::Point<Pixels>> {
14357        let source_point = source.to_display_point(editor_snapshot);
14358        self.display_to_pixel_point(source_point, editor_snapshot, window)
14359    }
14360
14361    pub fn display_to_pixel_point(
14362        &self,
14363        source: DisplayPoint,
14364        editor_snapshot: &EditorSnapshot,
14365        window: &mut Window,
14366    ) -> Option<gpui::Point<Pixels>> {
14367        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14368        let text_layout_details = self.text_layout_details(window);
14369        let scroll_top = text_layout_details
14370            .scroll_anchor
14371            .scroll_position(editor_snapshot)
14372            .y;
14373
14374        if source.row().as_f32() < scroll_top.floor() {
14375            return None;
14376        }
14377        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14378        let source_y = line_height * (source.row().as_f32() - scroll_top);
14379        Some(gpui::Point::new(source_x, source_y))
14380    }
14381
14382    pub fn has_active_completions_menu(&self) -> bool {
14383        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14384            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14385        })
14386    }
14387
14388    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14389        self.addons
14390            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14391    }
14392
14393    pub fn unregister_addon<T: Addon>(&mut self) {
14394        self.addons.remove(&std::any::TypeId::of::<T>());
14395    }
14396
14397    pub fn addon<T: Addon>(&self) -> Option<&T> {
14398        let type_id = std::any::TypeId::of::<T>();
14399        self.addons
14400            .get(&type_id)
14401            .and_then(|item| item.to_any().downcast_ref::<T>())
14402    }
14403
14404    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14405        let text_layout_details = self.text_layout_details(window);
14406        let style = &text_layout_details.editor_style;
14407        let font_id = window.text_system().resolve_font(&style.text.font());
14408        let font_size = style.text.font_size.to_pixels(window.rem_size());
14409        let line_height = style.text.line_height_in_pixels(window.rem_size());
14410        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14411
14412        gpui::Size::new(em_width, line_height)
14413    }
14414}
14415
14416fn get_uncommitted_changes_for_buffer(
14417    project: &Entity<Project>,
14418    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14419    buffer: Entity<MultiBuffer>,
14420    cx: &mut App,
14421) {
14422    let mut tasks = Vec::new();
14423    project.update(cx, |project, cx| {
14424        for buffer in buffers {
14425            tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14426        }
14427    });
14428    cx.spawn(|mut cx| async move {
14429        let change_sets = futures::future::join_all(tasks).await;
14430        buffer
14431            .update(&mut cx, |buffer, cx| {
14432                for change_set in change_sets {
14433                    if let Some(change_set) = change_set.log_err() {
14434                        buffer.add_change_set(change_set, cx);
14435                    }
14436                }
14437            })
14438            .ok();
14439    })
14440    .detach();
14441}
14442
14443fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14444    let tab_size = tab_size.get() as usize;
14445    let mut width = offset;
14446
14447    for ch in text.chars() {
14448        width += if ch == '\t' {
14449            tab_size - (width % tab_size)
14450        } else {
14451            1
14452        };
14453    }
14454
14455    width - offset
14456}
14457
14458#[cfg(test)]
14459mod tests {
14460    use super::*;
14461
14462    #[test]
14463    fn test_string_size_with_expanded_tabs() {
14464        let nz = |val| NonZeroU32::new(val).unwrap();
14465        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14466        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14467        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14468        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14469        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14470        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14471        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14472        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14473    }
14474}
14475
14476/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14477struct WordBreakingTokenizer<'a> {
14478    input: &'a str,
14479}
14480
14481impl<'a> WordBreakingTokenizer<'a> {
14482    fn new(input: &'a str) -> Self {
14483        Self { input }
14484    }
14485}
14486
14487fn is_char_ideographic(ch: char) -> bool {
14488    use unicode_script::Script::*;
14489    use unicode_script::UnicodeScript;
14490    matches!(ch.script(), Han | Tangut | Yi)
14491}
14492
14493fn is_grapheme_ideographic(text: &str) -> bool {
14494    text.chars().any(is_char_ideographic)
14495}
14496
14497fn is_grapheme_whitespace(text: &str) -> bool {
14498    text.chars().any(|x| x.is_whitespace())
14499}
14500
14501fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14502    text.chars().next().map_or(false, |ch| {
14503        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14504    })
14505}
14506
14507#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14508struct WordBreakToken<'a> {
14509    token: &'a str,
14510    grapheme_len: usize,
14511    is_whitespace: bool,
14512}
14513
14514impl<'a> Iterator for WordBreakingTokenizer<'a> {
14515    /// Yields a span, the count of graphemes in the token, and whether it was
14516    /// whitespace. Note that it also breaks at word boundaries.
14517    type Item = WordBreakToken<'a>;
14518
14519    fn next(&mut self) -> Option<Self::Item> {
14520        use unicode_segmentation::UnicodeSegmentation;
14521        if self.input.is_empty() {
14522            return None;
14523        }
14524
14525        let mut iter = self.input.graphemes(true).peekable();
14526        let mut offset = 0;
14527        let mut graphemes = 0;
14528        if let Some(first_grapheme) = iter.next() {
14529            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14530            offset += first_grapheme.len();
14531            graphemes += 1;
14532            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14533                if let Some(grapheme) = iter.peek().copied() {
14534                    if should_stay_with_preceding_ideograph(grapheme) {
14535                        offset += grapheme.len();
14536                        graphemes += 1;
14537                    }
14538                }
14539            } else {
14540                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14541                let mut next_word_bound = words.peek().copied();
14542                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14543                    next_word_bound = words.next();
14544                }
14545                while let Some(grapheme) = iter.peek().copied() {
14546                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14547                        break;
14548                    };
14549                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14550                        break;
14551                    };
14552                    offset += grapheme.len();
14553                    graphemes += 1;
14554                    iter.next();
14555                }
14556            }
14557            let token = &self.input[..offset];
14558            self.input = &self.input[offset..];
14559            if is_whitespace {
14560                Some(WordBreakToken {
14561                    token: " ",
14562                    grapheme_len: 1,
14563                    is_whitespace: true,
14564                })
14565            } else {
14566                Some(WordBreakToken {
14567                    token,
14568                    grapheme_len: graphemes,
14569                    is_whitespace: false,
14570                })
14571            }
14572        } else {
14573            None
14574        }
14575    }
14576}
14577
14578#[test]
14579fn test_word_breaking_tokenizer() {
14580    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14581        ("", &[]),
14582        ("  ", &[(" ", 1, true)]),
14583        ("Ʒ", &[("Ʒ", 1, false)]),
14584        ("Ǽ", &[("Ǽ", 1, false)]),
14585        ("", &[("", 1, false)]),
14586        ("⋑⋑", &[("⋑⋑", 2, false)]),
14587        (
14588            "原理,进而",
14589            &[
14590                ("", 1, false),
14591                ("理,", 2, false),
14592                ("", 1, false),
14593                ("", 1, false),
14594            ],
14595        ),
14596        (
14597            "hello world",
14598            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14599        ),
14600        (
14601            "hello, world",
14602            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14603        ),
14604        (
14605            "  hello world",
14606            &[
14607                (" ", 1, true),
14608                ("hello", 5, false),
14609                (" ", 1, true),
14610                ("world", 5, false),
14611            ],
14612        ),
14613        (
14614            "这是什么 \n 钢笔",
14615            &[
14616                ("", 1, false),
14617                ("", 1, false),
14618                ("", 1, false),
14619                ("", 1, false),
14620                (" ", 1, true),
14621                ("", 1, false),
14622                ("", 1, false),
14623            ],
14624        ),
14625        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14626    ];
14627
14628    for (input, result) in tests {
14629        assert_eq!(
14630            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14631            result
14632                .iter()
14633                .copied()
14634                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14635                    token,
14636                    grapheme_len,
14637                    is_whitespace,
14638                })
14639                .collect::<Vec<_>>()
14640        );
14641    }
14642}
14643
14644fn wrap_with_prefix(
14645    line_prefix: String,
14646    unwrapped_text: String,
14647    wrap_column: usize,
14648    tab_size: NonZeroU32,
14649) -> String {
14650    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14651    let mut wrapped_text = String::new();
14652    let mut current_line = line_prefix.clone();
14653
14654    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14655    let mut current_line_len = line_prefix_len;
14656    for WordBreakToken {
14657        token,
14658        grapheme_len,
14659        is_whitespace,
14660    } in tokenizer
14661    {
14662        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14663            wrapped_text.push_str(current_line.trim_end());
14664            wrapped_text.push('\n');
14665            current_line.truncate(line_prefix.len());
14666            current_line_len = line_prefix_len;
14667            if !is_whitespace {
14668                current_line.push_str(token);
14669                current_line_len += grapheme_len;
14670            }
14671        } else if !is_whitespace {
14672            current_line.push_str(token);
14673            current_line_len += grapheme_len;
14674        } else if current_line_len != line_prefix_len {
14675            current_line.push(' ');
14676            current_line_len += 1;
14677        }
14678    }
14679
14680    if !current_line.is_empty() {
14681        wrapped_text.push_str(&current_line);
14682    }
14683    wrapped_text
14684}
14685
14686#[test]
14687fn test_wrap_with_prefix() {
14688    assert_eq!(
14689        wrap_with_prefix(
14690            "# ".to_string(),
14691            "abcdefg".to_string(),
14692            4,
14693            NonZeroU32::new(4).unwrap()
14694        ),
14695        "# abcdefg"
14696    );
14697    assert_eq!(
14698        wrap_with_prefix(
14699            "".to_string(),
14700            "\thello world".to_string(),
14701            8,
14702            NonZeroU32::new(4).unwrap()
14703        ),
14704        "hello\nworld"
14705    );
14706    assert_eq!(
14707        wrap_with_prefix(
14708            "// ".to_string(),
14709            "xx \nyy zz aa bb cc".to_string(),
14710            12,
14711            NonZeroU32::new(4).unwrap()
14712        ),
14713        "// xx yy zz\n// aa bb cc"
14714    );
14715    assert_eq!(
14716        wrap_with_prefix(
14717            String::new(),
14718            "这是什么 \n 钢笔".to_string(),
14719            3,
14720            NonZeroU32::new(4).unwrap()
14721        ),
14722        "这是什\n么 钢\n"
14723    );
14724}
14725
14726pub trait CollaborationHub {
14727    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14728    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14729    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14730}
14731
14732impl CollaborationHub for Entity<Project> {
14733    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14734        self.read(cx).collaborators()
14735    }
14736
14737    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14738        self.read(cx).user_store().read(cx).participant_indices()
14739    }
14740
14741    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14742        let this = self.read(cx);
14743        let user_ids = this.collaborators().values().map(|c| c.user_id);
14744        this.user_store().read_with(cx, |user_store, cx| {
14745            user_store.participant_names(user_ids, cx)
14746        })
14747    }
14748}
14749
14750pub trait SemanticsProvider {
14751    fn hover(
14752        &self,
14753        buffer: &Entity<Buffer>,
14754        position: text::Anchor,
14755        cx: &mut App,
14756    ) -> Option<Task<Vec<project::Hover>>>;
14757
14758    fn inlay_hints(
14759        &self,
14760        buffer_handle: Entity<Buffer>,
14761        range: Range<text::Anchor>,
14762        cx: &mut App,
14763    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14764
14765    fn resolve_inlay_hint(
14766        &self,
14767        hint: InlayHint,
14768        buffer_handle: Entity<Buffer>,
14769        server_id: LanguageServerId,
14770        cx: &mut App,
14771    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14772
14773    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14774
14775    fn document_highlights(
14776        &self,
14777        buffer: &Entity<Buffer>,
14778        position: text::Anchor,
14779        cx: &mut App,
14780    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14781
14782    fn definitions(
14783        &self,
14784        buffer: &Entity<Buffer>,
14785        position: text::Anchor,
14786        kind: GotoDefinitionKind,
14787        cx: &mut App,
14788    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14789
14790    fn range_for_rename(
14791        &self,
14792        buffer: &Entity<Buffer>,
14793        position: text::Anchor,
14794        cx: &mut App,
14795    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14796
14797    fn perform_rename(
14798        &self,
14799        buffer: &Entity<Buffer>,
14800        position: text::Anchor,
14801        new_name: String,
14802        cx: &mut App,
14803    ) -> Option<Task<Result<ProjectTransaction>>>;
14804}
14805
14806pub trait CompletionProvider {
14807    fn completions(
14808        &self,
14809        buffer: &Entity<Buffer>,
14810        buffer_position: text::Anchor,
14811        trigger: CompletionContext,
14812        window: &mut Window,
14813        cx: &mut Context<Editor>,
14814    ) -> Task<Result<Vec<Completion>>>;
14815
14816    fn resolve_completions(
14817        &self,
14818        buffer: Entity<Buffer>,
14819        completion_indices: Vec<usize>,
14820        completions: Rc<RefCell<Box<[Completion]>>>,
14821        cx: &mut Context<Editor>,
14822    ) -> Task<Result<bool>>;
14823
14824    fn apply_additional_edits_for_completion(
14825        &self,
14826        _buffer: Entity<Buffer>,
14827        _completions: Rc<RefCell<Box<[Completion]>>>,
14828        _completion_index: usize,
14829        _push_to_history: bool,
14830        _cx: &mut Context<Editor>,
14831    ) -> Task<Result<Option<language::Transaction>>> {
14832        Task::ready(Ok(None))
14833    }
14834
14835    fn is_completion_trigger(
14836        &self,
14837        buffer: &Entity<Buffer>,
14838        position: language::Anchor,
14839        text: &str,
14840        trigger_in_words: bool,
14841        cx: &mut Context<Editor>,
14842    ) -> bool;
14843
14844    fn sort_completions(&self) -> bool {
14845        true
14846    }
14847}
14848
14849pub trait CodeActionProvider {
14850    fn id(&self) -> Arc<str>;
14851
14852    fn code_actions(
14853        &self,
14854        buffer: &Entity<Buffer>,
14855        range: Range<text::Anchor>,
14856        window: &mut Window,
14857        cx: &mut App,
14858    ) -> Task<Result<Vec<CodeAction>>>;
14859
14860    fn apply_code_action(
14861        &self,
14862        buffer_handle: Entity<Buffer>,
14863        action: CodeAction,
14864        excerpt_id: ExcerptId,
14865        push_to_history: bool,
14866        window: &mut Window,
14867        cx: &mut App,
14868    ) -> Task<Result<ProjectTransaction>>;
14869}
14870
14871impl CodeActionProvider for Entity<Project> {
14872    fn id(&self) -> Arc<str> {
14873        "project".into()
14874    }
14875
14876    fn code_actions(
14877        &self,
14878        buffer: &Entity<Buffer>,
14879        range: Range<text::Anchor>,
14880        _window: &mut Window,
14881        cx: &mut App,
14882    ) -> Task<Result<Vec<CodeAction>>> {
14883        self.update(cx, |project, cx| {
14884            project.code_actions(buffer, range, None, cx)
14885        })
14886    }
14887
14888    fn apply_code_action(
14889        &self,
14890        buffer_handle: Entity<Buffer>,
14891        action: CodeAction,
14892        _excerpt_id: ExcerptId,
14893        push_to_history: bool,
14894        _window: &mut Window,
14895        cx: &mut App,
14896    ) -> Task<Result<ProjectTransaction>> {
14897        self.update(cx, |project, cx| {
14898            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14899        })
14900    }
14901}
14902
14903fn snippet_completions(
14904    project: &Project,
14905    buffer: &Entity<Buffer>,
14906    buffer_position: text::Anchor,
14907    cx: &mut App,
14908) -> Task<Result<Vec<Completion>>> {
14909    let language = buffer.read(cx).language_at(buffer_position);
14910    let language_name = language.as_ref().map(|language| language.lsp_id());
14911    let snippet_store = project.snippets().read(cx);
14912    let snippets = snippet_store.snippets_for(language_name, cx);
14913
14914    if snippets.is_empty() {
14915        return Task::ready(Ok(vec![]));
14916    }
14917    let snapshot = buffer.read(cx).text_snapshot();
14918    let chars: String = snapshot
14919        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14920        .collect();
14921
14922    let scope = language.map(|language| language.default_scope());
14923    let executor = cx.background_executor().clone();
14924
14925    cx.background_executor().spawn(async move {
14926        let classifier = CharClassifier::new(scope).for_completion(true);
14927        let mut last_word = chars
14928            .chars()
14929            .take_while(|c| classifier.is_word(*c))
14930            .collect::<String>();
14931        last_word = last_word.chars().rev().collect();
14932
14933        if last_word.is_empty() {
14934            return Ok(vec![]);
14935        }
14936
14937        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14938        let to_lsp = |point: &text::Anchor| {
14939            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14940            point_to_lsp(end)
14941        };
14942        let lsp_end = to_lsp(&buffer_position);
14943
14944        let candidates = snippets
14945            .iter()
14946            .enumerate()
14947            .flat_map(|(ix, snippet)| {
14948                snippet
14949                    .prefix
14950                    .iter()
14951                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14952            })
14953            .collect::<Vec<StringMatchCandidate>>();
14954
14955        let mut matches = fuzzy::match_strings(
14956            &candidates,
14957            &last_word,
14958            last_word.chars().any(|c| c.is_uppercase()),
14959            100,
14960            &Default::default(),
14961            executor,
14962        )
14963        .await;
14964
14965        // Remove all candidates where the query's start does not match the start of any word in the candidate
14966        if let Some(query_start) = last_word.chars().next() {
14967            matches.retain(|string_match| {
14968                split_words(&string_match.string).any(|word| {
14969                    // Check that the first codepoint of the word as lowercase matches the first
14970                    // codepoint of the query as lowercase
14971                    word.chars()
14972                        .flat_map(|codepoint| codepoint.to_lowercase())
14973                        .zip(query_start.to_lowercase())
14974                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14975                })
14976            });
14977        }
14978
14979        let matched_strings = matches
14980            .into_iter()
14981            .map(|m| m.string)
14982            .collect::<HashSet<_>>();
14983
14984        let result: Vec<Completion> = snippets
14985            .into_iter()
14986            .filter_map(|snippet| {
14987                let matching_prefix = snippet
14988                    .prefix
14989                    .iter()
14990                    .find(|prefix| matched_strings.contains(*prefix))?;
14991                let start = as_offset - last_word.len();
14992                let start = snapshot.anchor_before(start);
14993                let range = start..buffer_position;
14994                let lsp_start = to_lsp(&start);
14995                let lsp_range = lsp::Range {
14996                    start: lsp_start,
14997                    end: lsp_end,
14998                };
14999                Some(Completion {
15000                    old_range: range,
15001                    new_text: snippet.body.clone(),
15002                    resolved: false,
15003                    label: CodeLabel {
15004                        text: matching_prefix.clone(),
15005                        runs: vec![],
15006                        filter_range: 0..matching_prefix.len(),
15007                    },
15008                    server_id: LanguageServerId(usize::MAX),
15009                    documentation: snippet
15010                        .description
15011                        .clone()
15012                        .map(CompletionDocumentation::SingleLine),
15013                    lsp_completion: lsp::CompletionItem {
15014                        label: snippet.prefix.first().unwrap().clone(),
15015                        kind: Some(CompletionItemKind::SNIPPET),
15016                        label_details: snippet.description.as_ref().map(|description| {
15017                            lsp::CompletionItemLabelDetails {
15018                                detail: Some(description.clone()),
15019                                description: None,
15020                            }
15021                        }),
15022                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15023                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15024                            lsp::InsertReplaceEdit {
15025                                new_text: snippet.body.clone(),
15026                                insert: lsp_range,
15027                                replace: lsp_range,
15028                            },
15029                        )),
15030                        filter_text: Some(snippet.body.clone()),
15031                        sort_text: Some(char::MAX.to_string()),
15032                        ..Default::default()
15033                    },
15034                    confirm: None,
15035                })
15036            })
15037            .collect();
15038
15039        Ok(result)
15040    })
15041}
15042
15043impl CompletionProvider for Entity<Project> {
15044    fn completions(
15045        &self,
15046        buffer: &Entity<Buffer>,
15047        buffer_position: text::Anchor,
15048        options: CompletionContext,
15049        _window: &mut Window,
15050        cx: &mut Context<Editor>,
15051    ) -> Task<Result<Vec<Completion>>> {
15052        self.update(cx, |project, cx| {
15053            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15054            let project_completions = project.completions(buffer, buffer_position, options, cx);
15055            cx.background_executor().spawn(async move {
15056                let mut completions = project_completions.await?;
15057                let snippets_completions = snippets.await?;
15058                completions.extend(snippets_completions);
15059                Ok(completions)
15060            })
15061        })
15062    }
15063
15064    fn resolve_completions(
15065        &self,
15066        buffer: Entity<Buffer>,
15067        completion_indices: Vec<usize>,
15068        completions: Rc<RefCell<Box<[Completion]>>>,
15069        cx: &mut Context<Editor>,
15070    ) -> Task<Result<bool>> {
15071        self.update(cx, |project, cx| {
15072            project.lsp_store().update(cx, |lsp_store, cx| {
15073                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15074            })
15075        })
15076    }
15077
15078    fn apply_additional_edits_for_completion(
15079        &self,
15080        buffer: Entity<Buffer>,
15081        completions: Rc<RefCell<Box<[Completion]>>>,
15082        completion_index: usize,
15083        push_to_history: bool,
15084        cx: &mut Context<Editor>,
15085    ) -> Task<Result<Option<language::Transaction>>> {
15086        self.update(cx, |project, cx| {
15087            project.lsp_store().update(cx, |lsp_store, cx| {
15088                lsp_store.apply_additional_edits_for_completion(
15089                    buffer,
15090                    completions,
15091                    completion_index,
15092                    push_to_history,
15093                    cx,
15094                )
15095            })
15096        })
15097    }
15098
15099    fn is_completion_trigger(
15100        &self,
15101        buffer: &Entity<Buffer>,
15102        position: language::Anchor,
15103        text: &str,
15104        trigger_in_words: bool,
15105        cx: &mut Context<Editor>,
15106    ) -> bool {
15107        let mut chars = text.chars();
15108        let char = if let Some(char) = chars.next() {
15109            char
15110        } else {
15111            return false;
15112        };
15113        if chars.next().is_some() {
15114            return false;
15115        }
15116
15117        let buffer = buffer.read(cx);
15118        let snapshot = buffer.snapshot();
15119        if !snapshot.settings_at(position, cx).show_completions_on_input {
15120            return false;
15121        }
15122        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15123        if trigger_in_words && classifier.is_word(char) {
15124            return true;
15125        }
15126
15127        buffer.completion_triggers().contains(text)
15128    }
15129}
15130
15131impl SemanticsProvider for Entity<Project> {
15132    fn hover(
15133        &self,
15134        buffer: &Entity<Buffer>,
15135        position: text::Anchor,
15136        cx: &mut App,
15137    ) -> Option<Task<Vec<project::Hover>>> {
15138        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15139    }
15140
15141    fn document_highlights(
15142        &self,
15143        buffer: &Entity<Buffer>,
15144        position: text::Anchor,
15145        cx: &mut App,
15146    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15147        Some(self.update(cx, |project, cx| {
15148            project.document_highlights(buffer, position, cx)
15149        }))
15150    }
15151
15152    fn definitions(
15153        &self,
15154        buffer: &Entity<Buffer>,
15155        position: text::Anchor,
15156        kind: GotoDefinitionKind,
15157        cx: &mut App,
15158    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15159        Some(self.update(cx, |project, cx| match kind {
15160            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15161            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15162            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15163            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15164        }))
15165    }
15166
15167    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15168        // TODO: make this work for remote projects
15169        self.read(cx)
15170            .language_servers_for_local_buffer(buffer.read(cx), cx)
15171            .any(
15172                |(_, server)| match server.capabilities().inlay_hint_provider {
15173                    Some(lsp::OneOf::Left(enabled)) => enabled,
15174                    Some(lsp::OneOf::Right(_)) => true,
15175                    None => false,
15176                },
15177            )
15178    }
15179
15180    fn inlay_hints(
15181        &self,
15182        buffer_handle: Entity<Buffer>,
15183        range: Range<text::Anchor>,
15184        cx: &mut App,
15185    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15186        Some(self.update(cx, |project, cx| {
15187            project.inlay_hints(buffer_handle, range, cx)
15188        }))
15189    }
15190
15191    fn resolve_inlay_hint(
15192        &self,
15193        hint: InlayHint,
15194        buffer_handle: Entity<Buffer>,
15195        server_id: LanguageServerId,
15196        cx: &mut App,
15197    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15198        Some(self.update(cx, |project, cx| {
15199            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15200        }))
15201    }
15202
15203    fn range_for_rename(
15204        &self,
15205        buffer: &Entity<Buffer>,
15206        position: text::Anchor,
15207        cx: &mut App,
15208    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15209        Some(self.update(cx, |project, cx| {
15210            let buffer = buffer.clone();
15211            let task = project.prepare_rename(buffer.clone(), position, cx);
15212            cx.spawn(|_, mut cx| async move {
15213                Ok(match task.await? {
15214                    PrepareRenameResponse::Success(range) => Some(range),
15215                    PrepareRenameResponse::InvalidPosition => None,
15216                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15217                        // Fallback on using TreeSitter info to determine identifier range
15218                        buffer.update(&mut cx, |buffer, _| {
15219                            let snapshot = buffer.snapshot();
15220                            let (range, kind) = snapshot.surrounding_word(position);
15221                            if kind != Some(CharKind::Word) {
15222                                return None;
15223                            }
15224                            Some(
15225                                snapshot.anchor_before(range.start)
15226                                    ..snapshot.anchor_after(range.end),
15227                            )
15228                        })?
15229                    }
15230                })
15231            })
15232        }))
15233    }
15234
15235    fn perform_rename(
15236        &self,
15237        buffer: &Entity<Buffer>,
15238        position: text::Anchor,
15239        new_name: String,
15240        cx: &mut App,
15241    ) -> Option<Task<Result<ProjectTransaction>>> {
15242        Some(self.update(cx, |project, cx| {
15243            project.perform_rename(buffer.clone(), position, new_name, cx)
15244        }))
15245    }
15246}
15247
15248fn inlay_hint_settings(
15249    location: Anchor,
15250    snapshot: &MultiBufferSnapshot,
15251    cx: &mut Context<Editor>,
15252) -> InlayHintSettings {
15253    let file = snapshot.file_at(location);
15254    let language = snapshot.language_at(location).map(|l| l.name());
15255    language_settings(language, file, cx).inlay_hints
15256}
15257
15258fn consume_contiguous_rows(
15259    contiguous_row_selections: &mut Vec<Selection<Point>>,
15260    selection: &Selection<Point>,
15261    display_map: &DisplaySnapshot,
15262    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15263) -> (MultiBufferRow, MultiBufferRow) {
15264    contiguous_row_selections.push(selection.clone());
15265    let start_row = MultiBufferRow(selection.start.row);
15266    let mut end_row = ending_row(selection, display_map);
15267
15268    while let Some(next_selection) = selections.peek() {
15269        if next_selection.start.row <= end_row.0 {
15270            end_row = ending_row(next_selection, display_map);
15271            contiguous_row_selections.push(selections.next().unwrap().clone());
15272        } else {
15273            break;
15274        }
15275    }
15276    (start_row, end_row)
15277}
15278
15279fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15280    if next_selection.end.column > 0 || next_selection.is_empty() {
15281        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15282    } else {
15283        MultiBufferRow(next_selection.end.row)
15284    }
15285}
15286
15287impl EditorSnapshot {
15288    pub fn remote_selections_in_range<'a>(
15289        &'a self,
15290        range: &'a Range<Anchor>,
15291        collaboration_hub: &dyn CollaborationHub,
15292        cx: &'a App,
15293    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15294        let participant_names = collaboration_hub.user_names(cx);
15295        let participant_indices = collaboration_hub.user_participant_indices(cx);
15296        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15297        let collaborators_by_replica_id = collaborators_by_peer_id
15298            .iter()
15299            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15300            .collect::<HashMap<_, _>>();
15301        self.buffer_snapshot
15302            .selections_in_range(range, false)
15303            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15304                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15305                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15306                let user_name = participant_names.get(&collaborator.user_id).cloned();
15307                Some(RemoteSelection {
15308                    replica_id,
15309                    selection,
15310                    cursor_shape,
15311                    line_mode,
15312                    participant_index,
15313                    peer_id: collaborator.peer_id,
15314                    user_name,
15315                })
15316            })
15317    }
15318
15319    pub fn hunks_for_ranges(
15320        &self,
15321        ranges: impl Iterator<Item = Range<Point>>,
15322    ) -> Vec<MultiBufferDiffHunk> {
15323        let mut hunks = Vec::new();
15324        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15325            HashMap::default();
15326        for query_range in ranges {
15327            let query_rows =
15328                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15329            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15330                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15331            ) {
15332                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15333                // when the caret is just above or just below the deleted hunk.
15334                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15335                let related_to_selection = if allow_adjacent {
15336                    hunk.row_range.overlaps(&query_rows)
15337                        || hunk.row_range.start == query_rows.end
15338                        || hunk.row_range.end == query_rows.start
15339                } else {
15340                    hunk.row_range.overlaps(&query_rows)
15341                };
15342                if related_to_selection {
15343                    if !processed_buffer_rows
15344                        .entry(hunk.buffer_id)
15345                        .or_default()
15346                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15347                    {
15348                        continue;
15349                    }
15350                    hunks.push(hunk);
15351                }
15352            }
15353        }
15354
15355        hunks
15356    }
15357
15358    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15359        self.display_snapshot.buffer_snapshot.language_at(position)
15360    }
15361
15362    pub fn is_focused(&self) -> bool {
15363        self.is_focused
15364    }
15365
15366    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15367        self.placeholder_text.as_ref()
15368    }
15369
15370    pub fn scroll_position(&self) -> gpui::Point<f32> {
15371        self.scroll_anchor.scroll_position(&self.display_snapshot)
15372    }
15373
15374    fn gutter_dimensions(
15375        &self,
15376        font_id: FontId,
15377        font_size: Pixels,
15378        max_line_number_width: Pixels,
15379        cx: &App,
15380    ) -> Option<GutterDimensions> {
15381        if !self.show_gutter {
15382            return None;
15383        }
15384
15385        let descent = cx.text_system().descent(font_id, font_size);
15386        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15387        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15388
15389        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15390            matches!(
15391                ProjectSettings::get_global(cx).git.git_gutter,
15392                Some(GitGutterSetting::TrackedFiles)
15393            )
15394        });
15395        let gutter_settings = EditorSettings::get_global(cx).gutter;
15396        let show_line_numbers = self
15397            .show_line_numbers
15398            .unwrap_or(gutter_settings.line_numbers);
15399        let line_gutter_width = if show_line_numbers {
15400            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15401            let min_width_for_number_on_gutter = em_advance * 4.0;
15402            max_line_number_width.max(min_width_for_number_on_gutter)
15403        } else {
15404            0.0.into()
15405        };
15406
15407        let show_code_actions = self
15408            .show_code_actions
15409            .unwrap_or(gutter_settings.code_actions);
15410
15411        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15412
15413        let git_blame_entries_width =
15414            self.git_blame_gutter_max_author_length
15415                .map(|max_author_length| {
15416                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15417
15418                    /// The number of characters to dedicate to gaps and margins.
15419                    const SPACING_WIDTH: usize = 4;
15420
15421                    let max_char_count = max_author_length
15422                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15423                        + ::git::SHORT_SHA_LENGTH
15424                        + MAX_RELATIVE_TIMESTAMP.len()
15425                        + SPACING_WIDTH;
15426
15427                    em_advance * max_char_count
15428                });
15429
15430        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15431        left_padding += if show_code_actions || show_runnables {
15432            em_width * 3.0
15433        } else if show_git_gutter && show_line_numbers {
15434            em_width * 2.0
15435        } else if show_git_gutter || show_line_numbers {
15436            em_width
15437        } else {
15438            px(0.)
15439        };
15440
15441        let right_padding = if gutter_settings.folds && show_line_numbers {
15442            em_width * 4.0
15443        } else if gutter_settings.folds {
15444            em_width * 3.0
15445        } else if show_line_numbers {
15446            em_width
15447        } else {
15448            px(0.)
15449        };
15450
15451        Some(GutterDimensions {
15452            left_padding,
15453            right_padding,
15454            width: line_gutter_width + left_padding + right_padding,
15455            margin: -descent,
15456            git_blame_entries_width,
15457        })
15458    }
15459
15460    pub fn render_crease_toggle(
15461        &self,
15462        buffer_row: MultiBufferRow,
15463        row_contains_cursor: bool,
15464        editor: Entity<Editor>,
15465        window: &mut Window,
15466        cx: &mut App,
15467    ) -> Option<AnyElement> {
15468        let folded = self.is_line_folded(buffer_row);
15469        let mut is_foldable = false;
15470
15471        if let Some(crease) = self
15472            .crease_snapshot
15473            .query_row(buffer_row, &self.buffer_snapshot)
15474        {
15475            is_foldable = true;
15476            match crease {
15477                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15478                    if let Some(render_toggle) = render_toggle {
15479                        let toggle_callback =
15480                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15481                                if folded {
15482                                    editor.update(cx, |editor, cx| {
15483                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15484                                    });
15485                                } else {
15486                                    editor.update(cx, |editor, cx| {
15487                                        editor.unfold_at(
15488                                            &crate::UnfoldAt { buffer_row },
15489                                            window,
15490                                            cx,
15491                                        )
15492                                    });
15493                                }
15494                            });
15495                        return Some((render_toggle)(
15496                            buffer_row,
15497                            folded,
15498                            toggle_callback,
15499                            window,
15500                            cx,
15501                        ));
15502                    }
15503                }
15504            }
15505        }
15506
15507        is_foldable |= self.starts_indent(buffer_row);
15508
15509        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15510            Some(
15511                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15512                    .toggle_state(folded)
15513                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15514                        if folded {
15515                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15516                        } else {
15517                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15518                        }
15519                    }))
15520                    .into_any_element(),
15521            )
15522        } else {
15523            None
15524        }
15525    }
15526
15527    pub fn render_crease_trailer(
15528        &self,
15529        buffer_row: MultiBufferRow,
15530        window: &mut Window,
15531        cx: &mut App,
15532    ) -> Option<AnyElement> {
15533        let folded = self.is_line_folded(buffer_row);
15534        if let Crease::Inline { render_trailer, .. } = self
15535            .crease_snapshot
15536            .query_row(buffer_row, &self.buffer_snapshot)?
15537        {
15538            let render_trailer = render_trailer.as_ref()?;
15539            Some(render_trailer(buffer_row, folded, window, cx))
15540        } else {
15541            None
15542        }
15543    }
15544}
15545
15546impl Deref for EditorSnapshot {
15547    type Target = DisplaySnapshot;
15548
15549    fn deref(&self) -> &Self::Target {
15550        &self.display_snapshot
15551    }
15552}
15553
15554#[derive(Clone, Debug, PartialEq, Eq)]
15555pub enum EditorEvent {
15556    InputIgnored {
15557        text: Arc<str>,
15558    },
15559    InputHandled {
15560        utf16_range_to_replace: Option<Range<isize>>,
15561        text: Arc<str>,
15562    },
15563    ExcerptsAdded {
15564        buffer: Entity<Buffer>,
15565        predecessor: ExcerptId,
15566        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15567    },
15568    ExcerptsRemoved {
15569        ids: Vec<ExcerptId>,
15570    },
15571    BufferFoldToggled {
15572        ids: Vec<ExcerptId>,
15573        folded: bool,
15574    },
15575    ExcerptsEdited {
15576        ids: Vec<ExcerptId>,
15577    },
15578    ExcerptsExpanded {
15579        ids: Vec<ExcerptId>,
15580    },
15581    BufferEdited,
15582    Edited {
15583        transaction_id: clock::Lamport,
15584    },
15585    Reparsed(BufferId),
15586    Focused,
15587    FocusedIn,
15588    Blurred,
15589    DirtyChanged,
15590    Saved,
15591    TitleChanged,
15592    DiffBaseChanged,
15593    SelectionsChanged {
15594        local: bool,
15595    },
15596    ScrollPositionChanged {
15597        local: bool,
15598        autoscroll: bool,
15599    },
15600    Closed,
15601    TransactionUndone {
15602        transaction_id: clock::Lamport,
15603    },
15604    TransactionBegun {
15605        transaction_id: clock::Lamport,
15606    },
15607    Reloaded,
15608    CursorShapeChanged,
15609}
15610
15611impl EventEmitter<EditorEvent> for Editor {}
15612
15613impl Focusable for Editor {
15614    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15615        self.focus_handle.clone()
15616    }
15617}
15618
15619impl Render for Editor {
15620    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15621        let settings = ThemeSettings::get_global(cx);
15622
15623        let mut text_style = match self.mode {
15624            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15625                color: cx.theme().colors().editor_foreground,
15626                font_family: settings.ui_font.family.clone(),
15627                font_features: settings.ui_font.features.clone(),
15628                font_fallbacks: settings.ui_font.fallbacks.clone(),
15629                font_size: rems(0.875).into(),
15630                font_weight: settings.ui_font.weight,
15631                line_height: relative(settings.buffer_line_height.value()),
15632                ..Default::default()
15633            },
15634            EditorMode::Full => TextStyle {
15635                color: cx.theme().colors().editor_foreground,
15636                font_family: settings.buffer_font.family.clone(),
15637                font_features: settings.buffer_font.features.clone(),
15638                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15639                font_size: settings.buffer_font_size().into(),
15640                font_weight: settings.buffer_font.weight,
15641                line_height: relative(settings.buffer_line_height.value()),
15642                ..Default::default()
15643            },
15644        };
15645        if let Some(text_style_refinement) = &self.text_style_refinement {
15646            text_style.refine(text_style_refinement)
15647        }
15648
15649        let background = match self.mode {
15650            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15651            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15652            EditorMode::Full => cx.theme().colors().editor_background,
15653        };
15654
15655        EditorElement::new(
15656            &cx.entity(),
15657            EditorStyle {
15658                background,
15659                local_player: cx.theme().players().local(),
15660                text: text_style,
15661                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15662                syntax: cx.theme().syntax().clone(),
15663                status: cx.theme().status().clone(),
15664                inlay_hints_style: make_inlay_hints_style(cx),
15665                inline_completion_styles: make_suggestion_styles(cx),
15666                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15667            },
15668        )
15669    }
15670}
15671
15672impl EntityInputHandler for Editor {
15673    fn text_for_range(
15674        &mut self,
15675        range_utf16: Range<usize>,
15676        adjusted_range: &mut Option<Range<usize>>,
15677        _: &mut Window,
15678        cx: &mut Context<Self>,
15679    ) -> Option<String> {
15680        let snapshot = self.buffer.read(cx).read(cx);
15681        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15682        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15683        if (start.0..end.0) != range_utf16 {
15684            adjusted_range.replace(start.0..end.0);
15685        }
15686        Some(snapshot.text_for_range(start..end).collect())
15687    }
15688
15689    fn selected_text_range(
15690        &mut self,
15691        ignore_disabled_input: bool,
15692        _: &mut Window,
15693        cx: &mut Context<Self>,
15694    ) -> Option<UTF16Selection> {
15695        // Prevent the IME menu from appearing when holding down an alphabetic key
15696        // while input is disabled.
15697        if !ignore_disabled_input && !self.input_enabled {
15698            return None;
15699        }
15700
15701        let selection = self.selections.newest::<OffsetUtf16>(cx);
15702        let range = selection.range();
15703
15704        Some(UTF16Selection {
15705            range: range.start.0..range.end.0,
15706            reversed: selection.reversed,
15707        })
15708    }
15709
15710    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15711        let snapshot = self.buffer.read(cx).read(cx);
15712        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15713        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15714    }
15715
15716    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15717        self.clear_highlights::<InputComposition>(cx);
15718        self.ime_transaction.take();
15719    }
15720
15721    fn replace_text_in_range(
15722        &mut self,
15723        range_utf16: Option<Range<usize>>,
15724        text: &str,
15725        window: &mut Window,
15726        cx: &mut Context<Self>,
15727    ) {
15728        if !self.input_enabled {
15729            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15730            return;
15731        }
15732
15733        self.transact(window, cx, |this, window, cx| {
15734            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15735                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15736                Some(this.selection_replacement_ranges(range_utf16, cx))
15737            } else {
15738                this.marked_text_ranges(cx)
15739            };
15740
15741            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15742                let newest_selection_id = this.selections.newest_anchor().id;
15743                this.selections
15744                    .all::<OffsetUtf16>(cx)
15745                    .iter()
15746                    .zip(ranges_to_replace.iter())
15747                    .find_map(|(selection, range)| {
15748                        if selection.id == newest_selection_id {
15749                            Some(
15750                                (range.start.0 as isize - selection.head().0 as isize)
15751                                    ..(range.end.0 as isize - selection.head().0 as isize),
15752                            )
15753                        } else {
15754                            None
15755                        }
15756                    })
15757            });
15758
15759            cx.emit(EditorEvent::InputHandled {
15760                utf16_range_to_replace: range_to_replace,
15761                text: text.into(),
15762            });
15763
15764            if let Some(new_selected_ranges) = new_selected_ranges {
15765                this.change_selections(None, window, cx, |selections| {
15766                    selections.select_ranges(new_selected_ranges)
15767                });
15768                this.backspace(&Default::default(), window, cx);
15769            }
15770
15771            this.handle_input(text, window, cx);
15772        });
15773
15774        if let Some(transaction) = self.ime_transaction {
15775            self.buffer.update(cx, |buffer, cx| {
15776                buffer.group_until_transaction(transaction, cx);
15777            });
15778        }
15779
15780        self.unmark_text(window, cx);
15781    }
15782
15783    fn replace_and_mark_text_in_range(
15784        &mut self,
15785        range_utf16: Option<Range<usize>>,
15786        text: &str,
15787        new_selected_range_utf16: Option<Range<usize>>,
15788        window: &mut Window,
15789        cx: &mut Context<Self>,
15790    ) {
15791        if !self.input_enabled {
15792            return;
15793        }
15794
15795        let transaction = self.transact(window, cx, |this, window, cx| {
15796            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15797                let snapshot = this.buffer.read(cx).read(cx);
15798                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15799                    for marked_range in &mut marked_ranges {
15800                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15801                        marked_range.start.0 += relative_range_utf16.start;
15802                        marked_range.start =
15803                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15804                        marked_range.end =
15805                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15806                    }
15807                }
15808                Some(marked_ranges)
15809            } else if let Some(range_utf16) = range_utf16 {
15810                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15811                Some(this.selection_replacement_ranges(range_utf16, cx))
15812            } else {
15813                None
15814            };
15815
15816            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15817                let newest_selection_id = this.selections.newest_anchor().id;
15818                this.selections
15819                    .all::<OffsetUtf16>(cx)
15820                    .iter()
15821                    .zip(ranges_to_replace.iter())
15822                    .find_map(|(selection, range)| {
15823                        if selection.id == newest_selection_id {
15824                            Some(
15825                                (range.start.0 as isize - selection.head().0 as isize)
15826                                    ..(range.end.0 as isize - selection.head().0 as isize),
15827                            )
15828                        } else {
15829                            None
15830                        }
15831                    })
15832            });
15833
15834            cx.emit(EditorEvent::InputHandled {
15835                utf16_range_to_replace: range_to_replace,
15836                text: text.into(),
15837            });
15838
15839            if let Some(ranges) = ranges_to_replace {
15840                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15841            }
15842
15843            let marked_ranges = {
15844                let snapshot = this.buffer.read(cx).read(cx);
15845                this.selections
15846                    .disjoint_anchors()
15847                    .iter()
15848                    .map(|selection| {
15849                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15850                    })
15851                    .collect::<Vec<_>>()
15852            };
15853
15854            if text.is_empty() {
15855                this.unmark_text(window, cx);
15856            } else {
15857                this.highlight_text::<InputComposition>(
15858                    marked_ranges.clone(),
15859                    HighlightStyle {
15860                        underline: Some(UnderlineStyle {
15861                            thickness: px(1.),
15862                            color: None,
15863                            wavy: false,
15864                        }),
15865                        ..Default::default()
15866                    },
15867                    cx,
15868                );
15869            }
15870
15871            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15872            let use_autoclose = this.use_autoclose;
15873            let use_auto_surround = this.use_auto_surround;
15874            this.set_use_autoclose(false);
15875            this.set_use_auto_surround(false);
15876            this.handle_input(text, window, cx);
15877            this.set_use_autoclose(use_autoclose);
15878            this.set_use_auto_surround(use_auto_surround);
15879
15880            if let Some(new_selected_range) = new_selected_range_utf16 {
15881                let snapshot = this.buffer.read(cx).read(cx);
15882                let new_selected_ranges = marked_ranges
15883                    .into_iter()
15884                    .map(|marked_range| {
15885                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15886                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15887                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15888                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15889                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15890                    })
15891                    .collect::<Vec<_>>();
15892
15893                drop(snapshot);
15894                this.change_selections(None, window, cx, |selections| {
15895                    selections.select_ranges(new_selected_ranges)
15896                });
15897            }
15898        });
15899
15900        self.ime_transaction = self.ime_transaction.or(transaction);
15901        if let Some(transaction) = self.ime_transaction {
15902            self.buffer.update(cx, |buffer, cx| {
15903                buffer.group_until_transaction(transaction, cx);
15904            });
15905        }
15906
15907        if self.text_highlights::<InputComposition>(cx).is_none() {
15908            self.ime_transaction.take();
15909        }
15910    }
15911
15912    fn bounds_for_range(
15913        &mut self,
15914        range_utf16: Range<usize>,
15915        element_bounds: gpui::Bounds<Pixels>,
15916        window: &mut Window,
15917        cx: &mut Context<Self>,
15918    ) -> Option<gpui::Bounds<Pixels>> {
15919        let text_layout_details = self.text_layout_details(window);
15920        let gpui::Size {
15921            width: em_width,
15922            height: line_height,
15923        } = self.character_size(window);
15924
15925        let snapshot = self.snapshot(window, cx);
15926        let scroll_position = snapshot.scroll_position();
15927        let scroll_left = scroll_position.x * em_width;
15928
15929        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15930        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15931            + self.gutter_dimensions.width
15932            + self.gutter_dimensions.margin;
15933        let y = line_height * (start.row().as_f32() - scroll_position.y);
15934
15935        Some(Bounds {
15936            origin: element_bounds.origin + point(x, y),
15937            size: size(em_width, line_height),
15938        })
15939    }
15940
15941    fn character_index_for_point(
15942        &mut self,
15943        point: gpui::Point<Pixels>,
15944        _window: &mut Window,
15945        _cx: &mut Context<Self>,
15946    ) -> Option<usize> {
15947        let position_map = self.last_position_map.as_ref()?;
15948        if !position_map.text_hitbox.contains(&point) {
15949            return None;
15950        }
15951        let display_point = position_map.point_for_position(point).previous_valid;
15952        let anchor = position_map
15953            .snapshot
15954            .display_point_to_anchor(display_point, Bias::Left);
15955        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
15956        Some(utf16_offset.0)
15957    }
15958}
15959
15960trait SelectionExt {
15961    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15962    fn spanned_rows(
15963        &self,
15964        include_end_if_at_line_start: bool,
15965        map: &DisplaySnapshot,
15966    ) -> Range<MultiBufferRow>;
15967}
15968
15969impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15970    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15971        let start = self
15972            .start
15973            .to_point(&map.buffer_snapshot)
15974            .to_display_point(map);
15975        let end = self
15976            .end
15977            .to_point(&map.buffer_snapshot)
15978            .to_display_point(map);
15979        if self.reversed {
15980            end..start
15981        } else {
15982            start..end
15983        }
15984    }
15985
15986    fn spanned_rows(
15987        &self,
15988        include_end_if_at_line_start: bool,
15989        map: &DisplaySnapshot,
15990    ) -> Range<MultiBufferRow> {
15991        let start = self.start.to_point(&map.buffer_snapshot);
15992        let mut end = self.end.to_point(&map.buffer_snapshot);
15993        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15994            end.row -= 1;
15995        }
15996
15997        let buffer_start = map.prev_line_boundary(start).0;
15998        let buffer_end = map.next_line_boundary(end).0;
15999        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16000    }
16001}
16002
16003impl<T: InvalidationRegion> InvalidationStack<T> {
16004    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16005    where
16006        S: Clone + ToOffset,
16007    {
16008        while let Some(region) = self.last() {
16009            let all_selections_inside_invalidation_ranges =
16010                if selections.len() == region.ranges().len() {
16011                    selections
16012                        .iter()
16013                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16014                        .all(|(selection, invalidation_range)| {
16015                            let head = selection.head().to_offset(buffer);
16016                            invalidation_range.start <= head && invalidation_range.end >= head
16017                        })
16018                } else {
16019                    false
16020                };
16021
16022            if all_selections_inside_invalidation_ranges {
16023                break;
16024            } else {
16025                self.pop();
16026            }
16027        }
16028    }
16029}
16030
16031impl<T> Default for InvalidationStack<T> {
16032    fn default() -> Self {
16033        Self(Default::default())
16034    }
16035}
16036
16037impl<T> Deref for InvalidationStack<T> {
16038    type Target = Vec<T>;
16039
16040    fn deref(&self) -> &Self::Target {
16041        &self.0
16042    }
16043}
16044
16045impl<T> DerefMut for InvalidationStack<T> {
16046    fn deref_mut(&mut self) -> &mut Self::Target {
16047        &mut self.0
16048    }
16049}
16050
16051impl InvalidationRegion for SnippetState {
16052    fn ranges(&self) -> &[Range<Anchor>] {
16053        &self.ranges[self.active_index]
16054    }
16055}
16056
16057pub fn diagnostic_block_renderer(
16058    diagnostic: Diagnostic,
16059    max_message_rows: Option<u8>,
16060    allow_closing: bool,
16061    _is_valid: bool,
16062) -> RenderBlock {
16063    let (text_without_backticks, code_ranges) =
16064        highlight_diagnostic_message(&diagnostic, max_message_rows);
16065
16066    Arc::new(move |cx: &mut BlockContext| {
16067        let group_id: SharedString = cx.block_id.to_string().into();
16068
16069        let mut text_style = cx.window.text_style().clone();
16070        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16071        let theme_settings = ThemeSettings::get_global(cx);
16072        text_style.font_family = theme_settings.buffer_font.family.clone();
16073        text_style.font_style = theme_settings.buffer_font.style;
16074        text_style.font_features = theme_settings.buffer_font.features.clone();
16075        text_style.font_weight = theme_settings.buffer_font.weight;
16076
16077        let multi_line_diagnostic = diagnostic.message.contains('\n');
16078
16079        let buttons = |diagnostic: &Diagnostic| {
16080            if multi_line_diagnostic {
16081                v_flex()
16082            } else {
16083                h_flex()
16084            }
16085            .when(allow_closing, |div| {
16086                div.children(diagnostic.is_primary.then(|| {
16087                    IconButton::new("close-block", IconName::XCircle)
16088                        .icon_color(Color::Muted)
16089                        .size(ButtonSize::Compact)
16090                        .style(ButtonStyle::Transparent)
16091                        .visible_on_hover(group_id.clone())
16092                        .on_click(move |_click, window, cx| {
16093                            window.dispatch_action(Box::new(Cancel), cx)
16094                        })
16095                        .tooltip(|window, cx| {
16096                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16097                        })
16098                }))
16099            })
16100            .child(
16101                IconButton::new("copy-block", IconName::Copy)
16102                    .icon_color(Color::Muted)
16103                    .size(ButtonSize::Compact)
16104                    .style(ButtonStyle::Transparent)
16105                    .visible_on_hover(group_id.clone())
16106                    .on_click({
16107                        let message = diagnostic.message.clone();
16108                        move |_click, _, cx| {
16109                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16110                        }
16111                    })
16112                    .tooltip(Tooltip::text("Copy diagnostic message")),
16113            )
16114        };
16115
16116        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16117            AvailableSpace::min_size(),
16118            cx.window,
16119            cx.app,
16120        );
16121
16122        h_flex()
16123            .id(cx.block_id)
16124            .group(group_id.clone())
16125            .relative()
16126            .size_full()
16127            .block_mouse_down()
16128            .pl(cx.gutter_dimensions.width)
16129            .w(cx.max_width - cx.gutter_dimensions.full_width())
16130            .child(
16131                div()
16132                    .flex()
16133                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16134                    .flex_shrink(),
16135            )
16136            .child(buttons(&diagnostic))
16137            .child(div().flex().flex_shrink_0().child(
16138                StyledText::new(text_without_backticks.clone()).with_highlights(
16139                    &text_style,
16140                    code_ranges.iter().map(|range| {
16141                        (
16142                            range.clone(),
16143                            HighlightStyle {
16144                                font_weight: Some(FontWeight::BOLD),
16145                                ..Default::default()
16146                            },
16147                        )
16148                    }),
16149                ),
16150            ))
16151            .into_any_element()
16152    })
16153}
16154
16155fn inline_completion_edit_text(
16156    current_snapshot: &BufferSnapshot,
16157    edits: &[(Range<Anchor>, String)],
16158    edit_preview: &EditPreview,
16159    include_deletions: bool,
16160    cx: &App,
16161) -> HighlightedText {
16162    let edits = edits
16163        .iter()
16164        .map(|(anchor, text)| {
16165            (
16166                anchor.start.text_anchor..anchor.end.text_anchor,
16167                text.clone(),
16168            )
16169        })
16170        .collect::<Vec<_>>();
16171
16172    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16173}
16174
16175pub fn highlight_diagnostic_message(
16176    diagnostic: &Diagnostic,
16177    mut max_message_rows: Option<u8>,
16178) -> (SharedString, Vec<Range<usize>>) {
16179    let mut text_without_backticks = String::new();
16180    let mut code_ranges = Vec::new();
16181
16182    if let Some(source) = &diagnostic.source {
16183        text_without_backticks.push_str(source);
16184        code_ranges.push(0..source.len());
16185        text_without_backticks.push_str(": ");
16186    }
16187
16188    let mut prev_offset = 0;
16189    let mut in_code_block = false;
16190    let has_row_limit = max_message_rows.is_some();
16191    let mut newline_indices = diagnostic
16192        .message
16193        .match_indices('\n')
16194        .filter(|_| has_row_limit)
16195        .map(|(ix, _)| ix)
16196        .fuse()
16197        .peekable();
16198
16199    for (quote_ix, _) in diagnostic
16200        .message
16201        .match_indices('`')
16202        .chain([(diagnostic.message.len(), "")])
16203    {
16204        let mut first_newline_ix = None;
16205        let mut last_newline_ix = None;
16206        while let Some(newline_ix) = newline_indices.peek() {
16207            if *newline_ix < quote_ix {
16208                if first_newline_ix.is_none() {
16209                    first_newline_ix = Some(*newline_ix);
16210                }
16211                last_newline_ix = Some(*newline_ix);
16212
16213                if let Some(rows_left) = &mut max_message_rows {
16214                    if *rows_left == 0 {
16215                        break;
16216                    } else {
16217                        *rows_left -= 1;
16218                    }
16219                }
16220                let _ = newline_indices.next();
16221            } else {
16222                break;
16223            }
16224        }
16225        let prev_len = text_without_backticks.len();
16226        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16227        text_without_backticks.push_str(new_text);
16228        if in_code_block {
16229            code_ranges.push(prev_len..text_without_backticks.len());
16230        }
16231        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16232        in_code_block = !in_code_block;
16233        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16234            text_without_backticks.push_str("...");
16235            break;
16236        }
16237    }
16238
16239    (text_without_backticks.into(), code_ranges)
16240}
16241
16242fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16243    match severity {
16244        DiagnosticSeverity::ERROR => colors.error,
16245        DiagnosticSeverity::WARNING => colors.warning,
16246        DiagnosticSeverity::INFORMATION => colors.info,
16247        DiagnosticSeverity::HINT => colors.info,
16248        _ => colors.ignored,
16249    }
16250}
16251
16252pub fn styled_runs_for_code_label<'a>(
16253    label: &'a CodeLabel,
16254    syntax_theme: &'a theme::SyntaxTheme,
16255) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16256    let fade_out = HighlightStyle {
16257        fade_out: Some(0.35),
16258        ..Default::default()
16259    };
16260
16261    let mut prev_end = label.filter_range.end;
16262    label
16263        .runs
16264        .iter()
16265        .enumerate()
16266        .flat_map(move |(ix, (range, highlight_id))| {
16267            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16268                style
16269            } else {
16270                return Default::default();
16271            };
16272            let mut muted_style = style;
16273            muted_style.highlight(fade_out);
16274
16275            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16276            if range.start >= label.filter_range.end {
16277                if range.start > prev_end {
16278                    runs.push((prev_end..range.start, fade_out));
16279                }
16280                runs.push((range.clone(), muted_style));
16281            } else if range.end <= label.filter_range.end {
16282                runs.push((range.clone(), style));
16283            } else {
16284                runs.push((range.start..label.filter_range.end, style));
16285                runs.push((label.filter_range.end..range.end, muted_style));
16286            }
16287            prev_end = cmp::max(prev_end, range.end);
16288
16289            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16290                runs.push((prev_end..label.text.len(), fade_out));
16291            }
16292
16293            runs
16294        })
16295}
16296
16297pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16298    let mut prev_index = 0;
16299    let mut prev_codepoint: Option<char> = None;
16300    text.char_indices()
16301        .chain([(text.len(), '\0')])
16302        .filter_map(move |(index, codepoint)| {
16303            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16304            let is_boundary = index == text.len()
16305                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16306                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16307            if is_boundary {
16308                let chunk = &text[prev_index..index];
16309                prev_index = index;
16310                Some(chunk)
16311            } else {
16312                None
16313            }
16314        })
16315}
16316
16317pub trait RangeToAnchorExt: Sized {
16318    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16319
16320    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16321        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16322        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16323    }
16324}
16325
16326impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16327    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16328        let start_offset = self.start.to_offset(snapshot);
16329        let end_offset = self.end.to_offset(snapshot);
16330        if start_offset == end_offset {
16331            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16332        } else {
16333            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16334        }
16335    }
16336}
16337
16338pub trait RowExt {
16339    fn as_f32(&self) -> f32;
16340
16341    fn next_row(&self) -> Self;
16342
16343    fn previous_row(&self) -> Self;
16344
16345    fn minus(&self, other: Self) -> u32;
16346}
16347
16348impl RowExt for DisplayRow {
16349    fn as_f32(&self) -> f32 {
16350        self.0 as f32
16351    }
16352
16353    fn next_row(&self) -> Self {
16354        Self(self.0 + 1)
16355    }
16356
16357    fn previous_row(&self) -> Self {
16358        Self(self.0.saturating_sub(1))
16359    }
16360
16361    fn minus(&self, other: Self) -> u32 {
16362        self.0 - other.0
16363    }
16364}
16365
16366impl RowExt for MultiBufferRow {
16367    fn as_f32(&self) -> f32 {
16368        self.0 as f32
16369    }
16370
16371    fn next_row(&self) -> Self {
16372        Self(self.0 + 1)
16373    }
16374
16375    fn previous_row(&self) -> Self {
16376        Self(self.0.saturating_sub(1))
16377    }
16378
16379    fn minus(&self, other: Self) -> u32 {
16380        self.0 - other.0
16381    }
16382}
16383
16384trait RowRangeExt {
16385    type Row;
16386
16387    fn len(&self) -> usize;
16388
16389    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16390}
16391
16392impl RowRangeExt for Range<MultiBufferRow> {
16393    type Row = MultiBufferRow;
16394
16395    fn len(&self) -> usize {
16396        (self.end.0 - self.start.0) as usize
16397    }
16398
16399    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16400        (self.start.0..self.end.0).map(MultiBufferRow)
16401    }
16402}
16403
16404impl RowRangeExt for Range<DisplayRow> {
16405    type Row = DisplayRow;
16406
16407    fn len(&self) -> usize {
16408        (self.end.0 - self.start.0) as usize
16409    }
16410
16411    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16412        (self.start.0..self.end.0).map(DisplayRow)
16413    }
16414}
16415
16416/// If select range has more than one line, we
16417/// just point the cursor to range.start.
16418fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16419    if range.start.row == range.end.row {
16420        range
16421    } else {
16422        range.start..range.start
16423    }
16424}
16425pub struct KillRing(ClipboardItem);
16426impl Global for KillRing {}
16427
16428const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16429
16430fn all_edits_insertions_or_deletions(
16431    edits: &Vec<(Range<Anchor>, String)>,
16432    snapshot: &MultiBufferSnapshot,
16433) -> bool {
16434    let mut all_insertions = true;
16435    let mut all_deletions = true;
16436
16437    for (range, new_text) in edits.iter() {
16438        let range_is_empty = range.to_offset(&snapshot).is_empty();
16439        let text_is_empty = new_text.is_empty();
16440
16441        if range_is_empty != text_is_empty {
16442            if range_is_empty {
16443                all_deletions = false;
16444            } else {
16445                all_insertions = false;
16446            }
16447        } else {
16448            return false;
16449        }
16450
16451        if !all_insertions && !all_deletions {
16452            return false;
16453        }
16454    }
16455    all_insertions || all_deletions
16456}