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        },
  310    )
  311    .detach();
  312
  313    cx.on_action(move |_: &workspace::NewFile, cx| {
  314        let app_state = workspace::AppState::global(cx);
  315        if let Some(app_state) = app_state.upgrade() {
  316            workspace::open_new(
  317                Default::default(),
  318                app_state,
  319                cx,
  320                |workspace, window, cx| {
  321                    Editor::new_file(workspace, &Default::default(), window, cx)
  322                },
  323            )
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(
  331                Default::default(),
  332                app_state,
  333                cx,
  334                |workspace, window, cx| {
  335                    cx.activate(true);
  336                    Editor::new_file(workspace, &Default::default(), window, cx)
  337                },
  338            )
  339            .detach();
  340        }
  341    });
  342}
  343
  344pub struct SearchWithinRange;
  345
  346trait InvalidationRegion {
  347    fn ranges(&self) -> &[Range<Anchor>];
  348}
  349
  350#[derive(Clone, Debug, PartialEq)]
  351pub enum SelectPhase {
  352    Begin {
  353        position: DisplayPoint,
  354        add: bool,
  355        click_count: usize,
  356    },
  357    BeginColumnar {
  358        position: DisplayPoint,
  359        reset: bool,
  360        goal_column: u32,
  361    },
  362    Extend {
  363        position: DisplayPoint,
  364        click_count: usize,
  365    },
  366    Update {
  367        position: DisplayPoint,
  368        goal_column: u32,
  369        scroll_delta: gpui::Point<f32>,
  370    },
  371    End,
  372}
  373
  374#[derive(Clone, Debug)]
  375pub enum SelectMode {
  376    Character,
  377    Word(Range<Anchor>),
  378    Line(Range<Anchor>),
  379    All,
  380}
  381
  382#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  383pub enum EditorMode {
  384    SingleLine { auto_width: bool },
  385    AutoHeight { max_lines: usize },
  386    Full,
  387}
  388
  389#[derive(Copy, Clone, Debug)]
  390pub enum SoftWrap {
  391    /// Prefer not to wrap at all.
  392    ///
  393    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  394    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  395    GitDiff,
  396    /// Prefer a single line generally, unless an overly long line is encountered.
  397    None,
  398    /// Soft wrap lines that exceed the editor width.
  399    EditorWidth,
  400    /// Soft wrap lines at the preferred line length.
  401    Column(u32),
  402    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  403    Bounded(u32),
  404}
  405
  406#[derive(Clone)]
  407pub struct EditorStyle {
  408    pub background: Hsla,
  409    pub local_player: PlayerColor,
  410    pub text: TextStyle,
  411    pub scrollbar_width: Pixels,
  412    pub syntax: Arc<SyntaxTheme>,
  413    pub status: StatusColors,
  414    pub inlay_hints_style: HighlightStyle,
  415    pub inline_completion_styles: InlineCompletionStyles,
  416    pub unnecessary_code_fade: f32,
  417}
  418
  419impl Default for EditorStyle {
  420    fn default() -> Self {
  421        Self {
  422            background: Hsla::default(),
  423            local_player: PlayerColor::default(),
  424            text: TextStyle::default(),
  425            scrollbar_width: Pixels::default(),
  426            syntax: Default::default(),
  427            // HACK: Status colors don't have a real default.
  428            // We should look into removing the status colors from the editor
  429            // style and retrieve them directly from the theme.
  430            status: StatusColors::dark(),
  431            inlay_hints_style: HighlightStyle::default(),
  432            inline_completion_styles: InlineCompletionStyles {
  433                insertion: HighlightStyle::default(),
  434                whitespace: HighlightStyle::default(),
  435            },
  436            unnecessary_code_fade: Default::default(),
  437        }
  438    }
  439}
  440
  441pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  442    let show_background = language_settings::language_settings(None, None, cx)
  443        .inlay_hints
  444        .show_background;
  445
  446    HighlightStyle {
  447        color: Some(cx.theme().status().hint),
  448        background_color: show_background.then(|| cx.theme().status().hint_background),
  449        ..HighlightStyle::default()
  450    }
  451}
  452
  453pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  454    InlineCompletionStyles {
  455        insertion: HighlightStyle {
  456            color: Some(cx.theme().status().predictive),
  457            ..HighlightStyle::default()
  458        },
  459        whitespace: HighlightStyle {
  460            background_color: Some(cx.theme().status().created_background),
  461            ..HighlightStyle::default()
  462        },
  463    }
  464}
  465
  466type CompletionId = usize;
  467
  468pub(crate) enum EditDisplayMode {
  469    TabAccept(bool),
  470    DiffPopover,
  471    Inline,
  472}
  473
  474enum InlineCompletion {
  475    Edit {
  476        edits: Vec<(Range<Anchor>, String)>,
  477        edit_preview: Option<EditPreview>,
  478        display_mode: EditDisplayMode,
  479        snapshot: BufferSnapshot,
  480    },
  481    Move {
  482        target: Anchor,
  483        range_around_target: Range<text::Anchor>,
  484        snapshot: BufferSnapshot,
  485    },
  486}
  487
  488struct InlineCompletionState {
  489    inlay_ids: Vec<InlayId>,
  490    completion: InlineCompletion,
  491    invalidation_range: Range<Anchor>,
  492}
  493
  494impl InlineCompletionState {
  495    pub fn is_move(&self) -> bool {
  496        match &self.completion {
  497            InlineCompletion::Move { .. } => true,
  498            _ => false,
  499        }
  500    }
  501}
  502
  503enum InlineCompletionHighlight {}
  504
  505pub enum MenuInlineCompletionsPolicy {
  506    Never,
  507    ByProvider,
  508}
  509
  510#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  511struct EditorActionId(usize);
  512
  513impl EditorActionId {
  514    pub fn post_inc(&mut self) -> Self {
  515        let answer = self.0;
  516
  517        *self = Self(answer + 1);
  518
  519        Self(answer)
  520    }
  521}
  522
  523// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  524// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  525
  526type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  527type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  528
  529#[derive(Default)]
  530struct ScrollbarMarkerState {
  531    scrollbar_size: Size<Pixels>,
  532    dirty: bool,
  533    markers: Arc<[PaintQuad]>,
  534    pending_refresh: Option<Task<Result<()>>>,
  535}
  536
  537impl ScrollbarMarkerState {
  538    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  539        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  540    }
  541}
  542
  543#[derive(Clone, Debug)]
  544struct RunnableTasks {
  545    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  546    offset: MultiBufferOffset,
  547    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  548    column: u32,
  549    // Values of all named captures, including those starting with '_'
  550    extra_variables: HashMap<String, String>,
  551    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  552    context_range: Range<BufferOffset>,
  553}
  554
  555impl RunnableTasks {
  556    fn resolve<'a>(
  557        &'a self,
  558        cx: &'a task::TaskContext,
  559    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  560        self.templates.iter().filter_map(|(kind, template)| {
  561            template
  562                .resolve_task(&kind.to_id_base(), cx)
  563                .map(|task| (kind.clone(), task))
  564        })
  565    }
  566}
  567
  568#[derive(Clone)]
  569struct ResolvedTasks {
  570    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  571    position: Anchor,
  572}
  573#[derive(Copy, Clone, Debug)]
  574struct MultiBufferOffset(usize);
  575#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  576struct BufferOffset(usize);
  577
  578// Addons allow storing per-editor state in other crates (e.g. Vim)
  579pub trait Addon: 'static {
  580    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  581
  582    fn to_any(&self) -> &dyn std::any::Any;
  583}
  584
  585#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  586pub enum IsVimMode {
  587    Yes,
  588    No,
  589}
  590
  591/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  592///
  593/// See the [module level documentation](self) for more information.
  594pub struct Editor {
  595    focus_handle: FocusHandle,
  596    last_focused_descendant: Option<WeakFocusHandle>,
  597    /// The text buffer being edited
  598    buffer: Entity<MultiBuffer>,
  599    /// Map of how text in the buffer should be displayed.
  600    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  601    pub display_map: Entity<DisplayMap>,
  602    pub selections: SelectionsCollection,
  603    pub scroll_manager: ScrollManager,
  604    /// When inline assist editors are linked, they all render cursors because
  605    /// typing enters text into each of them, even the ones that aren't focused.
  606    pub(crate) show_cursor_when_unfocused: bool,
  607    columnar_selection_tail: Option<Anchor>,
  608    add_selections_state: Option<AddSelectionsState>,
  609    select_next_state: Option<SelectNextState>,
  610    select_prev_state: Option<SelectNextState>,
  611    selection_history: SelectionHistory,
  612    autoclose_regions: Vec<AutocloseRegion>,
  613    snippet_stack: InvalidationStack<SnippetState>,
  614    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  615    ime_transaction: Option<TransactionId>,
  616    active_diagnostics: Option<ActiveDiagnosticGroup>,
  617    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  618
  619    // TODO: make this a access method
  620    pub project: Option<Entity<Project>>,
  621    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  622    completion_provider: Option<Box<dyn CompletionProvider>>,
  623    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  624    blink_manager: Entity<BlinkManager>,
  625    show_cursor_names: bool,
  626    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  627    pub show_local_selections: bool,
  628    mode: EditorMode,
  629    show_breadcrumbs: bool,
  630    show_gutter: bool,
  631    show_scrollbars: bool,
  632    show_line_numbers: Option<bool>,
  633    use_relative_line_numbers: Option<bool>,
  634    show_git_diff_gutter: Option<bool>,
  635    show_code_actions: Option<bool>,
  636    show_runnables: Option<bool>,
  637    show_wrap_guides: Option<bool>,
  638    show_indent_guides: Option<bool>,
  639    placeholder_text: Option<Arc<str>>,
  640    highlight_order: usize,
  641    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  642    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  643    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  644    scrollbar_marker_state: ScrollbarMarkerState,
  645    active_indent_guides_state: ActiveIndentGuidesState,
  646    nav_history: Option<ItemNavHistory>,
  647    context_menu: RefCell<Option<CodeContextMenu>>,
  648    mouse_context_menu: Option<MouseContextMenu>,
  649    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  650    signature_help_state: SignatureHelpState,
  651    auto_signature_help: Option<bool>,
  652    find_all_references_task_sources: Vec<Anchor>,
  653    next_completion_id: CompletionId,
  654    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  655    code_actions_task: Option<Task<Result<()>>>,
  656    document_highlights_task: Option<Task<()>>,
  657    linked_editing_range_task: Option<Task<Option<()>>>,
  658    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  659    pending_rename: Option<RenameState>,
  660    searchable: bool,
  661    cursor_shape: CursorShape,
  662    current_line_highlight: Option<CurrentLineHighlight>,
  663    collapse_matches: bool,
  664    autoindent_mode: Option<AutoindentMode>,
  665    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  666    input_enabled: bool,
  667    use_modal_editing: bool,
  668    read_only: bool,
  669    leader_peer_id: Option<PeerId>,
  670    remote_id: Option<ViewId>,
  671    hover_state: HoverState,
  672    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  673    gutter_hovered: bool,
  674    hovered_link_state: Option<HoveredLinkState>,
  675    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  676    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  677    active_inline_completion: Option<InlineCompletionState>,
  678    /// Used to prevent flickering as the user types while the menu is open
  679    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  680    // enable_inline_completions is a switch that Vim can use to disable
  681    // edit predictions based on its mode.
  682    enable_inline_completions: bool,
  683    show_inline_completions_override: Option<bool>,
  684    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  685    inlay_hint_cache: InlayHintCache,
  686    next_inlay_id: usize,
  687    _subscriptions: Vec<Subscription>,
  688    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  689    gutter_dimensions: GutterDimensions,
  690    style: Option<EditorStyle>,
  691    text_style_refinement: Option<TextStyleRefinement>,
  692    next_editor_action_id: EditorActionId,
  693    editor_actions:
  694        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  695    use_autoclose: bool,
  696    use_auto_surround: bool,
  697    auto_replace_emoji_shortcode: bool,
  698    show_git_blame_gutter: bool,
  699    show_git_blame_inline: bool,
  700    show_git_blame_inline_delay_task: Option<Task<()>>,
  701    git_blame_inline_enabled: bool,
  702    serialize_dirty_buffers: bool,
  703    show_selection_menu: Option<bool>,
  704    blame: Option<Entity<GitBlame>>,
  705    blame_subscription: Option<Subscription>,
  706    custom_context_menu: Option<
  707        Box<
  708            dyn 'static
  709                + Fn(
  710                    &mut Self,
  711                    DisplayPoint,
  712                    &mut Window,
  713                    &mut Context<Self>,
  714                ) -> Option<Entity<ui::ContextMenu>>,
  715        >,
  716    >,
  717    last_bounds: Option<Bounds<Pixels>>,
  718    last_position_map: Option<Rc<PositionMap>>,
  719    expect_bounds_change: Option<Bounds<Pixels>>,
  720    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  721    tasks_update_task: Option<Task<()>>,
  722    in_project_search: bool,
  723    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  724    breadcrumb_header: Option<String>,
  725    focused_block: Option<FocusedBlock>,
  726    next_scroll_position: NextScrollCursorCenterTopBottom,
  727    addons: HashMap<TypeId, Box<dyn Addon>>,
  728    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  729    selection_mark_mode: bool,
  730    toggle_fold_multiple_buffers: Task<()>,
  731    _scroll_cursor_center_top_bottom_task: Task<()>,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  735enum NextScrollCursorCenterTopBottom {
  736    #[default]
  737    Center,
  738    Top,
  739    Bottom,
  740}
  741
  742impl NextScrollCursorCenterTopBottom {
  743    fn next(&self) -> Self {
  744        match self {
  745            Self::Center => Self::Top,
  746            Self::Top => Self::Bottom,
  747            Self::Bottom => Self::Center,
  748        }
  749    }
  750}
  751
  752#[derive(Clone)]
  753pub struct EditorSnapshot {
  754    pub mode: EditorMode,
  755    show_gutter: bool,
  756    show_line_numbers: Option<bool>,
  757    show_git_diff_gutter: Option<bool>,
  758    show_code_actions: Option<bool>,
  759    show_runnables: Option<bool>,
  760    git_blame_gutter_max_author_length: Option<usize>,
  761    pub display_snapshot: DisplaySnapshot,
  762    pub placeholder_text: Option<Arc<str>>,
  763    is_focused: bool,
  764    scroll_anchor: ScrollAnchor,
  765    ongoing_scroll: OngoingScroll,
  766    current_line_highlight: CurrentLineHighlight,
  767    gutter_hovered: bool,
  768}
  769
  770const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  771
  772#[derive(Default, Debug, Clone, Copy)]
  773pub struct GutterDimensions {
  774    pub left_padding: Pixels,
  775    pub right_padding: Pixels,
  776    pub width: Pixels,
  777    pub margin: Pixels,
  778    pub git_blame_entries_width: Option<Pixels>,
  779}
  780
  781impl GutterDimensions {
  782    /// The full width of the space taken up by the gutter.
  783    pub fn full_width(&self) -> Pixels {
  784        self.margin + self.width
  785    }
  786
  787    /// The width of the space reserved for the fold indicators,
  788    /// use alongside 'justify_end' and `gutter_width` to
  789    /// right align content with the line numbers
  790    pub fn fold_area_width(&self) -> Pixels {
  791        self.margin + self.right_padding
  792    }
  793}
  794
  795#[derive(Debug)]
  796pub struct RemoteSelection {
  797    pub replica_id: ReplicaId,
  798    pub selection: Selection<Anchor>,
  799    pub cursor_shape: CursorShape,
  800    pub peer_id: PeerId,
  801    pub line_mode: bool,
  802    pub participant_index: Option<ParticipantIndex>,
  803    pub user_name: Option<SharedString>,
  804}
  805
  806#[derive(Clone, Debug)]
  807struct SelectionHistoryEntry {
  808    selections: Arc<[Selection<Anchor>]>,
  809    select_next_state: Option<SelectNextState>,
  810    select_prev_state: Option<SelectNextState>,
  811    add_selections_state: Option<AddSelectionsState>,
  812}
  813
  814enum SelectionHistoryMode {
  815    Normal,
  816    Undoing,
  817    Redoing,
  818}
  819
  820#[derive(Clone, PartialEq, Eq, Hash)]
  821struct HoveredCursor {
  822    replica_id: u16,
  823    selection_id: usize,
  824}
  825
  826impl Default for SelectionHistoryMode {
  827    fn default() -> Self {
  828        Self::Normal
  829    }
  830}
  831
  832#[derive(Default)]
  833struct SelectionHistory {
  834    #[allow(clippy::type_complexity)]
  835    selections_by_transaction:
  836        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  837    mode: SelectionHistoryMode,
  838    undo_stack: VecDeque<SelectionHistoryEntry>,
  839    redo_stack: VecDeque<SelectionHistoryEntry>,
  840}
  841
  842impl SelectionHistory {
  843    fn insert_transaction(
  844        &mut self,
  845        transaction_id: TransactionId,
  846        selections: Arc<[Selection<Anchor>]>,
  847    ) {
  848        self.selections_by_transaction
  849            .insert(transaction_id, (selections, None));
  850    }
  851
  852    #[allow(clippy::type_complexity)]
  853    fn transaction(
  854        &self,
  855        transaction_id: TransactionId,
  856    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  857        self.selections_by_transaction.get(&transaction_id)
  858    }
  859
  860    #[allow(clippy::type_complexity)]
  861    fn transaction_mut(
  862        &mut self,
  863        transaction_id: TransactionId,
  864    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  865        self.selections_by_transaction.get_mut(&transaction_id)
  866    }
  867
  868    fn push(&mut self, entry: SelectionHistoryEntry) {
  869        if !entry.selections.is_empty() {
  870            match self.mode {
  871                SelectionHistoryMode::Normal => {
  872                    self.push_undo(entry);
  873                    self.redo_stack.clear();
  874                }
  875                SelectionHistoryMode::Undoing => self.push_redo(entry),
  876                SelectionHistoryMode::Redoing => self.push_undo(entry),
  877            }
  878        }
  879    }
  880
  881    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  882        if self
  883            .undo_stack
  884            .back()
  885            .map_or(true, |e| e.selections != entry.selections)
  886        {
  887            self.undo_stack.push_back(entry);
  888            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  889                self.undo_stack.pop_front();
  890            }
  891        }
  892    }
  893
  894    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  895        if self
  896            .redo_stack
  897            .back()
  898            .map_or(true, |e| e.selections != entry.selections)
  899        {
  900            self.redo_stack.push_back(entry);
  901            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  902                self.redo_stack.pop_front();
  903            }
  904        }
  905    }
  906}
  907
  908struct RowHighlight {
  909    index: usize,
  910    range: Range<Anchor>,
  911    color: Hsla,
  912    should_autoscroll: bool,
  913}
  914
  915#[derive(Clone, Debug)]
  916struct AddSelectionsState {
  917    above: bool,
  918    stack: Vec<usize>,
  919}
  920
  921#[derive(Clone)]
  922struct SelectNextState {
  923    query: AhoCorasick,
  924    wordwise: bool,
  925    done: bool,
  926}
  927
  928impl std::fmt::Debug for SelectNextState {
  929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  930        f.debug_struct(std::any::type_name::<Self>())
  931            .field("wordwise", &self.wordwise)
  932            .field("done", &self.done)
  933            .finish()
  934    }
  935}
  936
  937#[derive(Debug)]
  938struct AutocloseRegion {
  939    selection_id: usize,
  940    range: Range<Anchor>,
  941    pair: BracketPair,
  942}
  943
  944#[derive(Debug)]
  945struct SnippetState {
  946    ranges: Vec<Vec<Range<Anchor>>>,
  947    active_index: usize,
  948    choices: Vec<Option<Vec<String>>>,
  949}
  950
  951#[doc(hidden)]
  952pub struct RenameState {
  953    pub range: Range<Anchor>,
  954    pub old_name: Arc<str>,
  955    pub editor: Entity<Editor>,
  956    block_id: CustomBlockId,
  957}
  958
  959struct InvalidationStack<T>(Vec<T>);
  960
  961struct RegisteredInlineCompletionProvider {
  962    provider: Arc<dyn InlineCompletionProviderHandle>,
  963    _subscription: Subscription,
  964}
  965
  966#[derive(Debug)]
  967struct ActiveDiagnosticGroup {
  968    primary_range: Range<Anchor>,
  969    primary_message: String,
  970    group_id: usize,
  971    blocks: HashMap<CustomBlockId, Diagnostic>,
  972    is_valid: bool,
  973}
  974
  975#[derive(Serialize, Deserialize, Clone, Debug)]
  976pub struct ClipboardSelection {
  977    pub len: usize,
  978    pub is_entire_line: bool,
  979    pub first_line_indent: u32,
  980}
  981
  982#[derive(Debug)]
  983pub(crate) struct NavigationData {
  984    cursor_anchor: Anchor,
  985    cursor_position: Point,
  986    scroll_anchor: ScrollAnchor,
  987    scroll_top_row: u32,
  988}
  989
  990#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  991pub enum GotoDefinitionKind {
  992    Symbol,
  993    Declaration,
  994    Type,
  995    Implementation,
  996}
  997
  998#[derive(Debug, Clone)]
  999enum InlayHintRefreshReason {
 1000    Toggle(bool),
 1001    SettingsChange(InlayHintSettings),
 1002    NewLinesShown,
 1003    BufferEdited(HashSet<Arc<Language>>),
 1004    RefreshRequested,
 1005    ExcerptsRemoved(Vec<ExcerptId>),
 1006}
 1007
 1008impl InlayHintRefreshReason {
 1009    fn description(&self) -> &'static str {
 1010        match self {
 1011            Self::Toggle(_) => "toggle",
 1012            Self::SettingsChange(_) => "settings change",
 1013            Self::NewLinesShown => "new lines shown",
 1014            Self::BufferEdited(_) => "buffer edited",
 1015            Self::RefreshRequested => "refresh requested",
 1016            Self::ExcerptsRemoved(_) => "excerpts removed",
 1017        }
 1018    }
 1019}
 1020
 1021pub enum FormatTarget {
 1022    Buffers,
 1023    Ranges(Vec<Range<MultiBufferPoint>>),
 1024}
 1025
 1026pub(crate) struct FocusedBlock {
 1027    id: BlockId,
 1028    focus_handle: WeakFocusHandle,
 1029}
 1030
 1031#[derive(Clone)]
 1032enum JumpData {
 1033    MultiBufferRow {
 1034        row: MultiBufferRow,
 1035        line_offset_from_top: u32,
 1036    },
 1037    MultiBufferPoint {
 1038        excerpt_id: ExcerptId,
 1039        position: Point,
 1040        anchor: text::Anchor,
 1041        line_offset_from_top: u32,
 1042    },
 1043}
 1044
 1045pub enum MultibufferSelectionMode {
 1046    First,
 1047    All,
 1048}
 1049
 1050impl Editor {
 1051    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1052        let buffer = cx.new(|cx| Buffer::local("", cx));
 1053        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1054        Self::new(
 1055            EditorMode::SingleLine { auto_width: false },
 1056            buffer,
 1057            None,
 1058            false,
 1059            window,
 1060            cx,
 1061        )
 1062    }
 1063
 1064    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1065        let buffer = cx.new(|cx| Buffer::local("", cx));
 1066        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1067        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1068    }
 1069
 1070    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1071        let buffer = cx.new(|cx| Buffer::local("", cx));
 1072        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1073        Self::new(
 1074            EditorMode::SingleLine { auto_width: true },
 1075            buffer,
 1076            None,
 1077            false,
 1078            window,
 1079            cx,
 1080        )
 1081    }
 1082
 1083    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1084        let buffer = cx.new(|cx| Buffer::local("", cx));
 1085        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1086        Self::new(
 1087            EditorMode::AutoHeight { max_lines },
 1088            buffer,
 1089            None,
 1090            false,
 1091            window,
 1092            cx,
 1093        )
 1094    }
 1095
 1096    pub fn for_buffer(
 1097        buffer: Entity<Buffer>,
 1098        project: Option<Entity<Project>>,
 1099        window: &mut Window,
 1100        cx: &mut Context<Self>,
 1101    ) -> Self {
 1102        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1103        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1104    }
 1105
 1106    pub fn for_multibuffer(
 1107        buffer: Entity<MultiBuffer>,
 1108        project: Option<Entity<Project>>,
 1109        show_excerpt_controls: bool,
 1110        window: &mut Window,
 1111        cx: &mut Context<Self>,
 1112    ) -> Self {
 1113        Self::new(
 1114            EditorMode::Full,
 1115            buffer,
 1116            project,
 1117            show_excerpt_controls,
 1118            window,
 1119            cx,
 1120        )
 1121    }
 1122
 1123    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1124        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1125        let mut clone = Self::new(
 1126            self.mode,
 1127            self.buffer.clone(),
 1128            self.project.clone(),
 1129            show_excerpt_controls,
 1130            window,
 1131            cx,
 1132        );
 1133        self.display_map.update(cx, |display_map, cx| {
 1134            let snapshot = display_map.snapshot(cx);
 1135            clone.display_map.update(cx, |display_map, cx| {
 1136                display_map.set_state(&snapshot, cx);
 1137            });
 1138        });
 1139        clone.selections.clone_state(&self.selections);
 1140        clone.scroll_manager.clone_state(&self.scroll_manager);
 1141        clone.searchable = self.searchable;
 1142        clone
 1143    }
 1144
 1145    pub fn new(
 1146        mode: EditorMode,
 1147        buffer: Entity<MultiBuffer>,
 1148        project: Option<Entity<Project>>,
 1149        show_excerpt_controls: bool,
 1150        window: &mut Window,
 1151        cx: &mut Context<Self>,
 1152    ) -> Self {
 1153        let style = window.text_style();
 1154        let font_size = style.font_size.to_pixels(window.rem_size());
 1155        let editor = cx.entity().downgrade();
 1156        let fold_placeholder = FoldPlaceholder {
 1157            constrain_width: true,
 1158            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1159                let editor = editor.clone();
 1160                div()
 1161                    .id(fold_id)
 1162                    .bg(cx.theme().colors().ghost_element_background)
 1163                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1164                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1165                    .rounded_sm()
 1166                    .size_full()
 1167                    .cursor_pointer()
 1168                    .child("")
 1169                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1170                    .on_click(move |_, _window, cx| {
 1171                        editor
 1172                            .update(cx, |editor, cx| {
 1173                                editor.unfold_ranges(
 1174                                    &[fold_range.start..fold_range.end],
 1175                                    true,
 1176                                    false,
 1177                                    cx,
 1178                                );
 1179                                cx.stop_propagation();
 1180                            })
 1181                            .ok();
 1182                    })
 1183                    .into_any()
 1184            }),
 1185            merge_adjacent: true,
 1186            ..Default::default()
 1187        };
 1188        let display_map = cx.new(|cx| {
 1189            DisplayMap::new(
 1190                buffer.clone(),
 1191                style.font(),
 1192                font_size,
 1193                None,
 1194                show_excerpt_controls,
 1195                FILE_HEADER_HEIGHT,
 1196                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1197                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1198                fold_placeholder,
 1199                cx,
 1200            )
 1201        });
 1202
 1203        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1204
 1205        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1206
 1207        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1208            .then(|| language_settings::SoftWrap::None);
 1209
 1210        let mut project_subscriptions = Vec::new();
 1211        if mode == EditorMode::Full {
 1212            if let Some(project) = project.as_ref() {
 1213                if buffer.read(cx).is_singleton() {
 1214                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1215                        cx.emit(EditorEvent::TitleChanged);
 1216                    }));
 1217                }
 1218                project_subscriptions.push(cx.subscribe_in(
 1219                    project,
 1220                    window,
 1221                    |editor, _, event, window, cx| {
 1222                        if let project::Event::RefreshInlayHints = event {
 1223                            editor
 1224                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1225                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1226                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1227                                let focus_handle = editor.focus_handle(cx);
 1228                                if focus_handle.is_focused(window) {
 1229                                    let snapshot = buffer.read(cx).snapshot();
 1230                                    for (range, snippet) in snippet_edits {
 1231                                        let editor_range =
 1232                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1233                                        editor
 1234                                            .insert_snippet(
 1235                                                &[editor_range],
 1236                                                snippet.clone(),
 1237                                                window,
 1238                                                cx,
 1239                                            )
 1240                                            .ok();
 1241                                    }
 1242                                }
 1243                            }
 1244                        }
 1245                    },
 1246                ));
 1247                if let Some(task_inventory) = project
 1248                    .read(cx)
 1249                    .task_store()
 1250                    .read(cx)
 1251                    .task_inventory()
 1252                    .cloned()
 1253                {
 1254                    project_subscriptions.push(cx.observe_in(
 1255                        &task_inventory,
 1256                        window,
 1257                        |editor, _, window, cx| {
 1258                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1259                        },
 1260                    ));
 1261                }
 1262            }
 1263        }
 1264
 1265        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1266
 1267        let inlay_hint_settings =
 1268            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1269        let focus_handle = cx.focus_handle();
 1270        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1271            .detach();
 1272        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1273            .detach();
 1274        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1275            .detach();
 1276        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1277            .detach();
 1278
 1279        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1280            Some(false)
 1281        } else {
 1282            None
 1283        };
 1284
 1285        let mut code_action_providers = Vec::new();
 1286        if let Some(project) = project.clone() {
 1287            get_unstaged_changes_for_buffers(
 1288                &project,
 1289                buffer.read(cx).all_buffers(),
 1290                buffer.clone(),
 1291                cx,
 1292            );
 1293            code_action_providers.push(Rc::new(project) as Rc<_>);
 1294        }
 1295
 1296        let mut this = Self {
 1297            focus_handle,
 1298            show_cursor_when_unfocused: false,
 1299            last_focused_descendant: None,
 1300            buffer: buffer.clone(),
 1301            display_map: display_map.clone(),
 1302            selections,
 1303            scroll_manager: ScrollManager::new(cx),
 1304            columnar_selection_tail: None,
 1305            add_selections_state: None,
 1306            select_next_state: None,
 1307            select_prev_state: None,
 1308            selection_history: Default::default(),
 1309            autoclose_regions: Default::default(),
 1310            snippet_stack: Default::default(),
 1311            select_larger_syntax_node_stack: Vec::new(),
 1312            ime_transaction: Default::default(),
 1313            active_diagnostics: None,
 1314            soft_wrap_mode_override,
 1315            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1316            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1317            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1318            project,
 1319            blink_manager: blink_manager.clone(),
 1320            show_local_selections: true,
 1321            show_scrollbars: true,
 1322            mode,
 1323            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1324            show_gutter: mode == EditorMode::Full,
 1325            show_line_numbers: None,
 1326            use_relative_line_numbers: None,
 1327            show_git_diff_gutter: None,
 1328            show_code_actions: None,
 1329            show_runnables: None,
 1330            show_wrap_guides: None,
 1331            show_indent_guides,
 1332            placeholder_text: None,
 1333            highlight_order: 0,
 1334            highlighted_rows: HashMap::default(),
 1335            background_highlights: Default::default(),
 1336            gutter_highlights: TreeMap::default(),
 1337            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1338            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1339            nav_history: None,
 1340            context_menu: RefCell::new(None),
 1341            mouse_context_menu: None,
 1342            completion_tasks: Default::default(),
 1343            signature_help_state: SignatureHelpState::default(),
 1344            auto_signature_help: None,
 1345            find_all_references_task_sources: Vec::new(),
 1346            next_completion_id: 0,
 1347            next_inlay_id: 0,
 1348            code_action_providers,
 1349            available_code_actions: Default::default(),
 1350            code_actions_task: Default::default(),
 1351            document_highlights_task: Default::default(),
 1352            linked_editing_range_task: Default::default(),
 1353            pending_rename: Default::default(),
 1354            searchable: true,
 1355            cursor_shape: EditorSettings::get_global(cx)
 1356                .cursor_shape
 1357                .unwrap_or_default(),
 1358            current_line_highlight: None,
 1359            autoindent_mode: Some(AutoindentMode::EachLine),
 1360            collapse_matches: false,
 1361            workspace: None,
 1362            input_enabled: true,
 1363            use_modal_editing: mode == EditorMode::Full,
 1364            read_only: false,
 1365            use_autoclose: true,
 1366            use_auto_surround: true,
 1367            auto_replace_emoji_shortcode: false,
 1368            leader_peer_id: None,
 1369            remote_id: None,
 1370            hover_state: Default::default(),
 1371            pending_mouse_down: None,
 1372            hovered_link_state: Default::default(),
 1373            inline_completion_provider: None,
 1374            active_inline_completion: None,
 1375            stale_inline_completion_in_menu: None,
 1376            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1377
 1378            gutter_hovered: false,
 1379            pixel_position_of_newest_cursor: None,
 1380            last_bounds: None,
 1381            last_position_map: None,
 1382            expect_bounds_change: None,
 1383            gutter_dimensions: GutterDimensions::default(),
 1384            style: None,
 1385            show_cursor_names: false,
 1386            hovered_cursors: Default::default(),
 1387            next_editor_action_id: EditorActionId::default(),
 1388            editor_actions: Rc::default(),
 1389            show_inline_completions_override: None,
 1390            enable_inline_completions: true,
 1391            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1392            custom_context_menu: None,
 1393            show_git_blame_gutter: false,
 1394            show_git_blame_inline: false,
 1395            show_selection_menu: None,
 1396            show_git_blame_inline_delay_task: None,
 1397            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1398            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1399                .session
 1400                .restore_unsaved_buffers,
 1401            blame: None,
 1402            blame_subscription: None,
 1403            tasks: Default::default(),
 1404            _subscriptions: vec![
 1405                cx.observe(&buffer, Self::on_buffer_changed),
 1406                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1407                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1408                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1409                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1410                cx.observe_window_activation(window, |editor, window, cx| {
 1411                    let active = window.is_window_active();
 1412                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1413                        if active {
 1414                            blink_manager.enable(cx);
 1415                        } else {
 1416                            blink_manager.disable(cx);
 1417                        }
 1418                    });
 1419                }),
 1420            ],
 1421            tasks_update_task: None,
 1422            linked_edit_ranges: Default::default(),
 1423            in_project_search: false,
 1424            previous_search_ranges: None,
 1425            breadcrumb_header: None,
 1426            focused_block: None,
 1427            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1428            addons: HashMap::default(),
 1429            registered_buffers: HashMap::default(),
 1430            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1431            selection_mark_mode: false,
 1432            toggle_fold_multiple_buffers: Task::ready(()),
 1433            text_style_refinement: None,
 1434        };
 1435        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1436        this._subscriptions.extend(project_subscriptions);
 1437
 1438        this.end_selection(window, cx);
 1439        this.scroll_manager.show_scrollbar(window, cx);
 1440
 1441        if mode == EditorMode::Full {
 1442            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1443            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1444
 1445            if this.git_blame_inline_enabled {
 1446                this.git_blame_inline_enabled = true;
 1447                this.start_git_blame_inline(false, window, cx);
 1448            }
 1449
 1450            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1451                if let Some(project) = this.project.as_ref() {
 1452                    let lsp_store = project.read(cx).lsp_store();
 1453                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1454                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1455                    });
 1456                    this.registered_buffers
 1457                        .insert(buffer.read(cx).remote_id(), handle);
 1458                }
 1459            }
 1460        }
 1461
 1462        this.report_editor_event("Editor Opened", None, cx);
 1463        this
 1464    }
 1465
 1466    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1467        self.mouse_context_menu
 1468            .as_ref()
 1469            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1470    }
 1471
 1472    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1473        let mut key_context = KeyContext::new_with_defaults();
 1474        key_context.add("Editor");
 1475        let mode = match self.mode {
 1476            EditorMode::SingleLine { .. } => "single_line",
 1477            EditorMode::AutoHeight { .. } => "auto_height",
 1478            EditorMode::Full => "full",
 1479        };
 1480
 1481        if EditorSettings::jupyter_enabled(cx) {
 1482            key_context.add("jupyter");
 1483        }
 1484
 1485        key_context.set("mode", mode);
 1486        if self.pending_rename.is_some() {
 1487            key_context.add("renaming");
 1488        }
 1489        match self.context_menu.borrow().as_ref() {
 1490            Some(CodeContextMenu::Completions(_)) => {
 1491                key_context.add("menu");
 1492                key_context.add("showing_completions");
 1493            }
 1494            Some(CodeContextMenu::CodeActions(_)) => {
 1495                key_context.add("menu");
 1496                key_context.add("showing_code_actions")
 1497            }
 1498            None => {}
 1499        }
 1500
 1501        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1502        if !self.focus_handle(cx).contains_focused(window, cx)
 1503            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1504        {
 1505            for addon in self.addons.values() {
 1506                addon.extend_key_context(&mut key_context, cx)
 1507            }
 1508        }
 1509
 1510        if let Some(extension) = self
 1511            .buffer
 1512            .read(cx)
 1513            .as_singleton()
 1514            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1515        {
 1516            key_context.set("extension", extension.to_string());
 1517        }
 1518
 1519        if self.has_active_inline_completion() {
 1520            key_context.add("copilot_suggestion");
 1521            key_context.add("inline_completion");
 1522        }
 1523
 1524        if self.selection_mark_mode {
 1525            key_context.add("selection_mode");
 1526        }
 1527
 1528        key_context
 1529    }
 1530
 1531    pub fn new_file(
 1532        workspace: &mut Workspace,
 1533        _: &workspace::NewFile,
 1534        window: &mut Window,
 1535        cx: &mut Context<Workspace>,
 1536    ) {
 1537        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1538            "Failed to create buffer",
 1539            window,
 1540            cx,
 1541            |e, _, _| match e.error_code() {
 1542                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1543                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1544                e.error_tag("required").unwrap_or("the latest version")
 1545            )),
 1546                _ => None,
 1547            },
 1548        );
 1549    }
 1550
 1551    pub fn new_in_workspace(
 1552        workspace: &mut Workspace,
 1553        window: &mut Window,
 1554        cx: &mut Context<Workspace>,
 1555    ) -> Task<Result<Entity<Editor>>> {
 1556        let project = workspace.project().clone();
 1557        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1558
 1559        cx.spawn_in(window, |workspace, mut cx| async move {
 1560            let buffer = create.await?;
 1561            workspace.update_in(&mut cx, |workspace, window, cx| {
 1562                let editor =
 1563                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1564                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1565                editor
 1566            })
 1567        })
 1568    }
 1569
 1570    fn new_file_vertical(
 1571        workspace: &mut Workspace,
 1572        _: &workspace::NewFileSplitVertical,
 1573        window: &mut Window,
 1574        cx: &mut Context<Workspace>,
 1575    ) {
 1576        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1577    }
 1578
 1579    fn new_file_horizontal(
 1580        workspace: &mut Workspace,
 1581        _: &workspace::NewFileSplitHorizontal,
 1582        window: &mut Window,
 1583        cx: &mut Context<Workspace>,
 1584    ) {
 1585        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1586    }
 1587
 1588    fn new_file_in_direction(
 1589        workspace: &mut Workspace,
 1590        direction: SplitDirection,
 1591        window: &mut Window,
 1592        cx: &mut Context<Workspace>,
 1593    ) {
 1594        let project = workspace.project().clone();
 1595        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1596
 1597        cx.spawn_in(window, |workspace, mut cx| async move {
 1598            let buffer = create.await?;
 1599            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1600                workspace.split_item(
 1601                    direction,
 1602                    Box::new(
 1603                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1604                    ),
 1605                    window,
 1606                    cx,
 1607                )
 1608            })?;
 1609            anyhow::Ok(())
 1610        })
 1611        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1612            match e.error_code() {
 1613                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1614                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1615                e.error_tag("required").unwrap_or("the latest version")
 1616            )),
 1617                _ => None,
 1618            }
 1619        });
 1620    }
 1621
 1622    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1623        self.leader_peer_id
 1624    }
 1625
 1626    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1627        &self.buffer
 1628    }
 1629
 1630    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1631        self.workspace.as_ref()?.0.upgrade()
 1632    }
 1633
 1634    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1635        self.buffer().read(cx).title(cx)
 1636    }
 1637
 1638    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1639        let git_blame_gutter_max_author_length = self
 1640            .render_git_blame_gutter(cx)
 1641            .then(|| {
 1642                if let Some(blame) = self.blame.as_ref() {
 1643                    let max_author_length =
 1644                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1645                    Some(max_author_length)
 1646                } else {
 1647                    None
 1648                }
 1649            })
 1650            .flatten();
 1651
 1652        EditorSnapshot {
 1653            mode: self.mode,
 1654            show_gutter: self.show_gutter,
 1655            show_line_numbers: self.show_line_numbers,
 1656            show_git_diff_gutter: self.show_git_diff_gutter,
 1657            show_code_actions: self.show_code_actions,
 1658            show_runnables: self.show_runnables,
 1659            git_blame_gutter_max_author_length,
 1660            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1661            scroll_anchor: self.scroll_manager.anchor(),
 1662            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1663            placeholder_text: self.placeholder_text.clone(),
 1664            is_focused: self.focus_handle.is_focused(window),
 1665            current_line_highlight: self
 1666                .current_line_highlight
 1667                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1668            gutter_hovered: self.gutter_hovered,
 1669        }
 1670    }
 1671
 1672    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1673        self.buffer.read(cx).language_at(point, cx)
 1674    }
 1675
 1676    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1677        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1678    }
 1679
 1680    pub fn active_excerpt(
 1681        &self,
 1682        cx: &App,
 1683    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1684        self.buffer
 1685            .read(cx)
 1686            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1687    }
 1688
 1689    pub fn mode(&self) -> EditorMode {
 1690        self.mode
 1691    }
 1692
 1693    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1694        self.collaboration_hub.as_deref()
 1695    }
 1696
 1697    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1698        self.collaboration_hub = Some(hub);
 1699    }
 1700
 1701    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1702        self.in_project_search = in_project_search;
 1703    }
 1704
 1705    pub fn set_custom_context_menu(
 1706        &mut self,
 1707        f: impl 'static
 1708            + Fn(
 1709                &mut Self,
 1710                DisplayPoint,
 1711                &mut Window,
 1712                &mut Context<Self>,
 1713            ) -> Option<Entity<ui::ContextMenu>>,
 1714    ) {
 1715        self.custom_context_menu = Some(Box::new(f))
 1716    }
 1717
 1718    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1719        self.completion_provider = provider;
 1720    }
 1721
 1722    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1723        self.semantics_provider.clone()
 1724    }
 1725
 1726    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1727        self.semantics_provider = provider;
 1728    }
 1729
 1730    pub fn set_inline_completion_provider<T>(
 1731        &mut self,
 1732        provider: Option<Entity<T>>,
 1733        window: &mut Window,
 1734        cx: &mut Context<Self>,
 1735    ) where
 1736        T: InlineCompletionProvider,
 1737    {
 1738        self.inline_completion_provider =
 1739            provider.map(|provider| RegisteredInlineCompletionProvider {
 1740                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1741                    if this.focus_handle.is_focused(window) {
 1742                        this.update_visible_inline_completion(window, cx);
 1743                    }
 1744                }),
 1745                provider: Arc::new(provider),
 1746            });
 1747        self.refresh_inline_completion(false, false, window, cx);
 1748    }
 1749
 1750    pub fn placeholder_text(&self) -> Option<&str> {
 1751        self.placeholder_text.as_deref()
 1752    }
 1753
 1754    pub fn set_placeholder_text(
 1755        &mut self,
 1756        placeholder_text: impl Into<Arc<str>>,
 1757        cx: &mut Context<Self>,
 1758    ) {
 1759        let placeholder_text = Some(placeholder_text.into());
 1760        if self.placeholder_text != placeholder_text {
 1761            self.placeholder_text = placeholder_text;
 1762            cx.notify();
 1763        }
 1764    }
 1765
 1766    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1767        self.cursor_shape = cursor_shape;
 1768
 1769        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1770        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1771
 1772        cx.notify();
 1773    }
 1774
 1775    pub fn set_current_line_highlight(
 1776        &mut self,
 1777        current_line_highlight: Option<CurrentLineHighlight>,
 1778    ) {
 1779        self.current_line_highlight = current_line_highlight;
 1780    }
 1781
 1782    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1783        self.collapse_matches = collapse_matches;
 1784    }
 1785
 1786    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1787        let buffers = self.buffer.read(cx).all_buffers();
 1788        let Some(lsp_store) = self.lsp_store(cx) else {
 1789            return;
 1790        };
 1791        lsp_store.update(cx, |lsp_store, cx| {
 1792            for buffer in buffers {
 1793                self.registered_buffers
 1794                    .entry(buffer.read(cx).remote_id())
 1795                    .or_insert_with(|| {
 1796                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1797                    });
 1798            }
 1799        })
 1800    }
 1801
 1802    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1803        if self.collapse_matches {
 1804            return range.start..range.start;
 1805        }
 1806        range.clone()
 1807    }
 1808
 1809    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1810        if self.display_map.read(cx).clip_at_line_ends != clip {
 1811            self.display_map
 1812                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1813        }
 1814    }
 1815
 1816    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1817        self.input_enabled = input_enabled;
 1818    }
 1819
 1820    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1821        self.enable_inline_completions = enabled;
 1822        if !self.enable_inline_completions {
 1823            self.take_active_inline_completion(cx);
 1824            cx.notify();
 1825        }
 1826    }
 1827
 1828    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1829        self.menu_inline_completions_policy = value;
 1830    }
 1831
 1832    pub fn set_autoindent(&mut self, autoindent: bool) {
 1833        if autoindent {
 1834            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1835        } else {
 1836            self.autoindent_mode = None;
 1837        }
 1838    }
 1839
 1840    pub fn read_only(&self, cx: &App) -> bool {
 1841        self.read_only || self.buffer.read(cx).read_only()
 1842    }
 1843
 1844    pub fn set_read_only(&mut self, read_only: bool) {
 1845        self.read_only = read_only;
 1846    }
 1847
 1848    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1849        self.use_autoclose = autoclose;
 1850    }
 1851
 1852    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1853        self.use_auto_surround = auto_surround;
 1854    }
 1855
 1856    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1857        self.auto_replace_emoji_shortcode = auto_replace;
 1858    }
 1859
 1860    pub fn toggle_inline_completions(
 1861        &mut self,
 1862        _: &ToggleInlineCompletions,
 1863        window: &mut Window,
 1864        cx: &mut Context<Self>,
 1865    ) {
 1866        if self.show_inline_completions_override.is_some() {
 1867            self.set_show_inline_completions(None, window, cx);
 1868        } else {
 1869            let cursor = self.selections.newest_anchor().head();
 1870            if let Some((buffer, cursor_buffer_position)) =
 1871                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1872            {
 1873                let show_inline_completions =
 1874                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1875                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1876            }
 1877        }
 1878    }
 1879
 1880    pub fn set_show_inline_completions(
 1881        &mut self,
 1882        show_inline_completions: Option<bool>,
 1883        window: &mut Window,
 1884        cx: &mut Context<Self>,
 1885    ) {
 1886        self.show_inline_completions_override = show_inline_completions;
 1887        self.refresh_inline_completion(false, true, window, cx);
 1888    }
 1889
 1890    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1891        let cursor = self.selections.newest_anchor().head();
 1892        if let Some((buffer, buffer_position)) =
 1893            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1894        {
 1895            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1896        } else {
 1897            false
 1898        }
 1899    }
 1900
 1901    fn should_show_inline_completions(
 1902        &self,
 1903        buffer: &Entity<Buffer>,
 1904        buffer_position: language::Anchor,
 1905        cx: &App,
 1906    ) -> bool {
 1907        if !self.snippet_stack.is_empty() {
 1908            return false;
 1909        }
 1910
 1911        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1912            return false;
 1913        }
 1914
 1915        if let Some(provider) = self.inline_completion_provider() {
 1916            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1917                show_inline_completions
 1918            } else {
 1919                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1920            }
 1921        } else {
 1922            false
 1923        }
 1924    }
 1925
 1926    fn inline_completions_disabled_in_scope(
 1927        &self,
 1928        buffer: &Entity<Buffer>,
 1929        buffer_position: language::Anchor,
 1930        cx: &App,
 1931    ) -> bool {
 1932        let snapshot = buffer.read(cx).snapshot();
 1933        let settings = snapshot.settings_at(buffer_position, cx);
 1934
 1935        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1936            return false;
 1937        };
 1938
 1939        scope.override_name().map_or(false, |scope_name| {
 1940            settings
 1941                .inline_completions_disabled_in
 1942                .iter()
 1943                .any(|s| s == scope_name)
 1944        })
 1945    }
 1946
 1947    pub fn set_use_modal_editing(&mut self, to: bool) {
 1948        self.use_modal_editing = to;
 1949    }
 1950
 1951    pub fn use_modal_editing(&self) -> bool {
 1952        self.use_modal_editing
 1953    }
 1954
 1955    fn selections_did_change(
 1956        &mut self,
 1957        local: bool,
 1958        old_cursor_position: &Anchor,
 1959        show_completions: bool,
 1960        window: &mut Window,
 1961        cx: &mut Context<Self>,
 1962    ) {
 1963        window.invalidate_character_coordinates();
 1964
 1965        // Copy selections to primary selection buffer
 1966        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1967        if local {
 1968            let selections = self.selections.all::<usize>(cx);
 1969            let buffer_handle = self.buffer.read(cx).read(cx);
 1970
 1971            let mut text = String::new();
 1972            for (index, selection) in selections.iter().enumerate() {
 1973                let text_for_selection = buffer_handle
 1974                    .text_for_range(selection.start..selection.end)
 1975                    .collect::<String>();
 1976
 1977                text.push_str(&text_for_selection);
 1978                if index != selections.len() - 1 {
 1979                    text.push('\n');
 1980                }
 1981            }
 1982
 1983            if !text.is_empty() {
 1984                cx.write_to_primary(ClipboardItem::new_string(text));
 1985            }
 1986        }
 1987
 1988        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1989            self.buffer.update(cx, |buffer, cx| {
 1990                buffer.set_active_selections(
 1991                    &self.selections.disjoint_anchors(),
 1992                    self.selections.line_mode,
 1993                    self.cursor_shape,
 1994                    cx,
 1995                )
 1996            });
 1997        }
 1998        let display_map = self
 1999            .display_map
 2000            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2001        let buffer = &display_map.buffer_snapshot;
 2002        self.add_selections_state = None;
 2003        self.select_next_state = None;
 2004        self.select_prev_state = None;
 2005        self.select_larger_syntax_node_stack.clear();
 2006        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2007        self.snippet_stack
 2008            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2009        self.take_rename(false, window, cx);
 2010
 2011        let new_cursor_position = self.selections.newest_anchor().head();
 2012
 2013        self.push_to_nav_history(
 2014            *old_cursor_position,
 2015            Some(new_cursor_position.to_point(buffer)),
 2016            cx,
 2017        );
 2018
 2019        if local {
 2020            let new_cursor_position = self.selections.newest_anchor().head();
 2021            let mut context_menu = self.context_menu.borrow_mut();
 2022            let completion_menu = match context_menu.as_ref() {
 2023                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2024                _ => {
 2025                    *context_menu = None;
 2026                    None
 2027                }
 2028            };
 2029
 2030            if let Some(completion_menu) = completion_menu {
 2031                let cursor_position = new_cursor_position.to_offset(buffer);
 2032                let (word_range, kind) =
 2033                    buffer.surrounding_word(completion_menu.initial_position, true);
 2034                if kind == Some(CharKind::Word)
 2035                    && word_range.to_inclusive().contains(&cursor_position)
 2036                {
 2037                    let mut completion_menu = completion_menu.clone();
 2038                    drop(context_menu);
 2039
 2040                    let query = Self::completion_query(buffer, cursor_position);
 2041                    cx.spawn(move |this, mut cx| async move {
 2042                        completion_menu
 2043                            .filter(query.as_deref(), cx.background_executor().clone())
 2044                            .await;
 2045
 2046                        this.update(&mut cx, |this, cx| {
 2047                            let mut context_menu = this.context_menu.borrow_mut();
 2048                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2049                            else {
 2050                                return;
 2051                            };
 2052
 2053                            if menu.id > completion_menu.id {
 2054                                return;
 2055                            }
 2056
 2057                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2058                            drop(context_menu);
 2059                            cx.notify();
 2060                        })
 2061                    })
 2062                    .detach();
 2063
 2064                    if show_completions {
 2065                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2066                    }
 2067                } else {
 2068                    drop(context_menu);
 2069                    self.hide_context_menu(window, cx);
 2070                }
 2071            } else {
 2072                drop(context_menu);
 2073            }
 2074
 2075            hide_hover(self, cx);
 2076
 2077            if old_cursor_position.to_display_point(&display_map).row()
 2078                != new_cursor_position.to_display_point(&display_map).row()
 2079            {
 2080                self.available_code_actions.take();
 2081            }
 2082            self.refresh_code_actions(window, cx);
 2083            self.refresh_document_highlights(cx);
 2084            refresh_matching_bracket_highlights(self, window, cx);
 2085            self.update_visible_inline_completion(window, cx);
 2086            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2087            if self.git_blame_inline_enabled {
 2088                self.start_inline_blame_timer(window, cx);
 2089            }
 2090        }
 2091
 2092        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2093        cx.emit(EditorEvent::SelectionsChanged { local });
 2094
 2095        if self.selections.disjoint_anchors().len() == 1 {
 2096            cx.emit(SearchEvent::ActiveMatchChanged)
 2097        }
 2098        cx.notify();
 2099    }
 2100
 2101    pub fn change_selections<R>(
 2102        &mut self,
 2103        autoscroll: Option<Autoscroll>,
 2104        window: &mut Window,
 2105        cx: &mut Context<Self>,
 2106        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2107    ) -> R {
 2108        self.change_selections_inner(autoscroll, true, window, cx, change)
 2109    }
 2110
 2111    pub fn change_selections_inner<R>(
 2112        &mut self,
 2113        autoscroll: Option<Autoscroll>,
 2114        request_completions: bool,
 2115        window: &mut Window,
 2116        cx: &mut Context<Self>,
 2117        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2118    ) -> R {
 2119        let old_cursor_position = self.selections.newest_anchor().head();
 2120        self.push_to_selection_history();
 2121
 2122        let (changed, result) = self.selections.change_with(cx, change);
 2123
 2124        if changed {
 2125            if let Some(autoscroll) = autoscroll {
 2126                self.request_autoscroll(autoscroll, cx);
 2127            }
 2128            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2129
 2130            if self.should_open_signature_help_automatically(
 2131                &old_cursor_position,
 2132                self.signature_help_state.backspace_pressed(),
 2133                cx,
 2134            ) {
 2135                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2136            }
 2137            self.signature_help_state.set_backspace_pressed(false);
 2138        }
 2139
 2140        result
 2141    }
 2142
 2143    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2144    where
 2145        I: IntoIterator<Item = (Range<S>, T)>,
 2146        S: ToOffset,
 2147        T: Into<Arc<str>>,
 2148    {
 2149        if self.read_only(cx) {
 2150            return;
 2151        }
 2152
 2153        self.buffer
 2154            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2155    }
 2156
 2157    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2158    where
 2159        I: IntoIterator<Item = (Range<S>, T)>,
 2160        S: ToOffset,
 2161        T: Into<Arc<str>>,
 2162    {
 2163        if self.read_only(cx) {
 2164            return;
 2165        }
 2166
 2167        self.buffer.update(cx, |buffer, cx| {
 2168            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2169        });
 2170    }
 2171
 2172    pub fn edit_with_block_indent<I, S, T>(
 2173        &mut self,
 2174        edits: I,
 2175        original_indent_columns: Vec<u32>,
 2176        cx: &mut Context<Self>,
 2177    ) where
 2178        I: IntoIterator<Item = (Range<S>, T)>,
 2179        S: ToOffset,
 2180        T: Into<Arc<str>>,
 2181    {
 2182        if self.read_only(cx) {
 2183            return;
 2184        }
 2185
 2186        self.buffer.update(cx, |buffer, cx| {
 2187            buffer.edit(
 2188                edits,
 2189                Some(AutoindentMode::Block {
 2190                    original_indent_columns,
 2191                }),
 2192                cx,
 2193            )
 2194        });
 2195    }
 2196
 2197    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2198        self.hide_context_menu(window, cx);
 2199
 2200        match phase {
 2201            SelectPhase::Begin {
 2202                position,
 2203                add,
 2204                click_count,
 2205            } => self.begin_selection(position, add, click_count, window, cx),
 2206            SelectPhase::BeginColumnar {
 2207                position,
 2208                goal_column,
 2209                reset,
 2210            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2211            SelectPhase::Extend {
 2212                position,
 2213                click_count,
 2214            } => self.extend_selection(position, click_count, window, cx),
 2215            SelectPhase::Update {
 2216                position,
 2217                goal_column,
 2218                scroll_delta,
 2219            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2220            SelectPhase::End => self.end_selection(window, cx),
 2221        }
 2222    }
 2223
 2224    fn extend_selection(
 2225        &mut self,
 2226        position: DisplayPoint,
 2227        click_count: usize,
 2228        window: &mut Window,
 2229        cx: &mut Context<Self>,
 2230    ) {
 2231        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2232        let tail = self.selections.newest::<usize>(cx).tail();
 2233        self.begin_selection(position, false, click_count, window, cx);
 2234
 2235        let position = position.to_offset(&display_map, Bias::Left);
 2236        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2237
 2238        let mut pending_selection = self
 2239            .selections
 2240            .pending_anchor()
 2241            .expect("extend_selection not called with pending selection");
 2242        if position >= tail {
 2243            pending_selection.start = tail_anchor;
 2244        } else {
 2245            pending_selection.end = tail_anchor;
 2246            pending_selection.reversed = true;
 2247        }
 2248
 2249        let mut pending_mode = self.selections.pending_mode().unwrap();
 2250        match &mut pending_mode {
 2251            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2252            _ => {}
 2253        }
 2254
 2255        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2256            s.set_pending(pending_selection, pending_mode)
 2257        });
 2258    }
 2259
 2260    fn begin_selection(
 2261        &mut self,
 2262        position: DisplayPoint,
 2263        add: bool,
 2264        click_count: usize,
 2265        window: &mut Window,
 2266        cx: &mut Context<Self>,
 2267    ) {
 2268        if !self.focus_handle.is_focused(window) {
 2269            self.last_focused_descendant = None;
 2270            window.focus(&self.focus_handle);
 2271        }
 2272
 2273        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2274        let buffer = &display_map.buffer_snapshot;
 2275        let newest_selection = self.selections.newest_anchor().clone();
 2276        let position = display_map.clip_point(position, Bias::Left);
 2277
 2278        let start;
 2279        let end;
 2280        let mode;
 2281        let mut auto_scroll;
 2282        match click_count {
 2283            1 => {
 2284                start = buffer.anchor_before(position.to_point(&display_map));
 2285                end = start;
 2286                mode = SelectMode::Character;
 2287                auto_scroll = true;
 2288            }
 2289            2 => {
 2290                let range = movement::surrounding_word(&display_map, position);
 2291                start = buffer.anchor_before(range.start.to_point(&display_map));
 2292                end = buffer.anchor_before(range.end.to_point(&display_map));
 2293                mode = SelectMode::Word(start..end);
 2294                auto_scroll = true;
 2295            }
 2296            3 => {
 2297                let position = display_map
 2298                    .clip_point(position, Bias::Left)
 2299                    .to_point(&display_map);
 2300                let line_start = display_map.prev_line_boundary(position).0;
 2301                let next_line_start = buffer.clip_point(
 2302                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2303                    Bias::Left,
 2304                );
 2305                start = buffer.anchor_before(line_start);
 2306                end = buffer.anchor_before(next_line_start);
 2307                mode = SelectMode::Line(start..end);
 2308                auto_scroll = true;
 2309            }
 2310            _ => {
 2311                start = buffer.anchor_before(0);
 2312                end = buffer.anchor_before(buffer.len());
 2313                mode = SelectMode::All;
 2314                auto_scroll = false;
 2315            }
 2316        }
 2317        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2318
 2319        let point_to_delete: Option<usize> = {
 2320            let selected_points: Vec<Selection<Point>> =
 2321                self.selections.disjoint_in_range(start..end, cx);
 2322
 2323            if !add || click_count > 1 {
 2324                None
 2325            } else if !selected_points.is_empty() {
 2326                Some(selected_points[0].id)
 2327            } else {
 2328                let clicked_point_already_selected =
 2329                    self.selections.disjoint.iter().find(|selection| {
 2330                        selection.start.to_point(buffer) == start.to_point(buffer)
 2331                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2332                    });
 2333
 2334                clicked_point_already_selected.map(|selection| selection.id)
 2335            }
 2336        };
 2337
 2338        let selections_count = self.selections.count();
 2339
 2340        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2341            if let Some(point_to_delete) = point_to_delete {
 2342                s.delete(point_to_delete);
 2343
 2344                if selections_count == 1 {
 2345                    s.set_pending_anchor_range(start..end, mode);
 2346                }
 2347            } else {
 2348                if !add {
 2349                    s.clear_disjoint();
 2350                } else if click_count > 1 {
 2351                    s.delete(newest_selection.id)
 2352                }
 2353
 2354                s.set_pending_anchor_range(start..end, mode);
 2355            }
 2356        });
 2357    }
 2358
 2359    fn begin_columnar_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        goal_column: u32,
 2363        reset: bool,
 2364        window: &mut Window,
 2365        cx: &mut Context<Self>,
 2366    ) {
 2367        if !self.focus_handle.is_focused(window) {
 2368            self.last_focused_descendant = None;
 2369            window.focus(&self.focus_handle);
 2370        }
 2371
 2372        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2373
 2374        if reset {
 2375            let pointer_position = display_map
 2376                .buffer_snapshot
 2377                .anchor_before(position.to_point(&display_map));
 2378
 2379            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2380                s.clear_disjoint();
 2381                s.set_pending_anchor_range(
 2382                    pointer_position..pointer_position,
 2383                    SelectMode::Character,
 2384                );
 2385            });
 2386        }
 2387
 2388        let tail = self.selections.newest::<Point>(cx).tail();
 2389        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2390
 2391        if !reset {
 2392            self.select_columns(
 2393                tail.to_display_point(&display_map),
 2394                position,
 2395                goal_column,
 2396                &display_map,
 2397                window,
 2398                cx,
 2399            );
 2400        }
 2401    }
 2402
 2403    fn update_selection(
 2404        &mut self,
 2405        position: DisplayPoint,
 2406        goal_column: u32,
 2407        scroll_delta: gpui::Point<f32>,
 2408        window: &mut Window,
 2409        cx: &mut Context<Self>,
 2410    ) {
 2411        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2412
 2413        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2414            let tail = tail.to_display_point(&display_map);
 2415            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2416        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2417            let buffer = self.buffer.read(cx).snapshot(cx);
 2418            let head;
 2419            let tail;
 2420            let mode = self.selections.pending_mode().unwrap();
 2421            match &mode {
 2422                SelectMode::Character => {
 2423                    head = position.to_point(&display_map);
 2424                    tail = pending.tail().to_point(&buffer);
 2425                }
 2426                SelectMode::Word(original_range) => {
 2427                    let original_display_range = original_range.start.to_display_point(&display_map)
 2428                        ..original_range.end.to_display_point(&display_map);
 2429                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2430                        ..original_display_range.end.to_point(&display_map);
 2431                    if movement::is_inside_word(&display_map, position)
 2432                        || original_display_range.contains(&position)
 2433                    {
 2434                        let word_range = movement::surrounding_word(&display_map, position);
 2435                        if word_range.start < original_display_range.start {
 2436                            head = word_range.start.to_point(&display_map);
 2437                        } else {
 2438                            head = word_range.end.to_point(&display_map);
 2439                        }
 2440                    } else {
 2441                        head = position.to_point(&display_map);
 2442                    }
 2443
 2444                    if head <= original_buffer_range.start {
 2445                        tail = original_buffer_range.end;
 2446                    } else {
 2447                        tail = original_buffer_range.start;
 2448                    }
 2449                }
 2450                SelectMode::Line(original_range) => {
 2451                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2452
 2453                    let position = display_map
 2454                        .clip_point(position, Bias::Left)
 2455                        .to_point(&display_map);
 2456                    let line_start = display_map.prev_line_boundary(position).0;
 2457                    let next_line_start = buffer.clip_point(
 2458                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2459                        Bias::Left,
 2460                    );
 2461
 2462                    if line_start < original_range.start {
 2463                        head = line_start
 2464                    } else {
 2465                        head = next_line_start
 2466                    }
 2467
 2468                    if head <= original_range.start {
 2469                        tail = original_range.end;
 2470                    } else {
 2471                        tail = original_range.start;
 2472                    }
 2473                }
 2474                SelectMode::All => {
 2475                    return;
 2476                }
 2477            };
 2478
 2479            if head < tail {
 2480                pending.start = buffer.anchor_before(head);
 2481                pending.end = buffer.anchor_before(tail);
 2482                pending.reversed = true;
 2483            } else {
 2484                pending.start = buffer.anchor_before(tail);
 2485                pending.end = buffer.anchor_before(head);
 2486                pending.reversed = false;
 2487            }
 2488
 2489            self.change_selections(None, window, cx, |s| {
 2490                s.set_pending(pending, mode);
 2491            });
 2492        } else {
 2493            log::error!("update_selection dispatched with no pending selection");
 2494            return;
 2495        }
 2496
 2497        self.apply_scroll_delta(scroll_delta, window, cx);
 2498        cx.notify();
 2499    }
 2500
 2501    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2502        self.columnar_selection_tail.take();
 2503        if self.selections.pending_anchor().is_some() {
 2504            let selections = self.selections.all::<usize>(cx);
 2505            self.change_selections(None, window, cx, |s| {
 2506                s.select(selections);
 2507                s.clear_pending();
 2508            });
 2509        }
 2510    }
 2511
 2512    fn select_columns(
 2513        &mut self,
 2514        tail: DisplayPoint,
 2515        head: DisplayPoint,
 2516        goal_column: u32,
 2517        display_map: &DisplaySnapshot,
 2518        window: &mut Window,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        let start_row = cmp::min(tail.row(), head.row());
 2522        let end_row = cmp::max(tail.row(), head.row());
 2523        let start_column = cmp::min(tail.column(), goal_column);
 2524        let end_column = cmp::max(tail.column(), goal_column);
 2525        let reversed = start_column < tail.column();
 2526
 2527        let selection_ranges = (start_row.0..=end_row.0)
 2528            .map(DisplayRow)
 2529            .filter_map(|row| {
 2530                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2531                    let start = display_map
 2532                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2533                        .to_point(display_map);
 2534                    let end = display_map
 2535                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2536                        .to_point(display_map);
 2537                    if reversed {
 2538                        Some(end..start)
 2539                    } else {
 2540                        Some(start..end)
 2541                    }
 2542                } else {
 2543                    None
 2544                }
 2545            })
 2546            .collect::<Vec<_>>();
 2547
 2548        self.change_selections(None, window, cx, |s| {
 2549            s.select_ranges(selection_ranges);
 2550        });
 2551        cx.notify();
 2552    }
 2553
 2554    pub fn has_pending_nonempty_selection(&self) -> bool {
 2555        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2556            Some(Selection { start, end, .. }) => start != end,
 2557            None => false,
 2558        };
 2559
 2560        pending_nonempty_selection
 2561            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2562    }
 2563
 2564    pub fn has_pending_selection(&self) -> bool {
 2565        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2566    }
 2567
 2568    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2569        self.selection_mark_mode = false;
 2570
 2571        if self.clear_expanded_diff_hunks(cx) {
 2572            cx.notify();
 2573            return;
 2574        }
 2575        if self.dismiss_menus_and_popups(true, window, cx) {
 2576            return;
 2577        }
 2578
 2579        if self.mode == EditorMode::Full
 2580            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2581        {
 2582            return;
 2583        }
 2584
 2585        cx.propagate();
 2586    }
 2587
 2588    pub fn dismiss_menus_and_popups(
 2589        &mut self,
 2590        should_report_inline_completion_event: bool,
 2591        window: &mut Window,
 2592        cx: &mut Context<Self>,
 2593    ) -> bool {
 2594        if self.take_rename(false, window, cx).is_some() {
 2595            return true;
 2596        }
 2597
 2598        if hide_hover(self, cx) {
 2599            return true;
 2600        }
 2601
 2602        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2603            return true;
 2604        }
 2605
 2606        if self.hide_context_menu(window, cx).is_some() {
 2607            return true;
 2608        }
 2609
 2610        if self.mouse_context_menu.take().is_some() {
 2611            return true;
 2612        }
 2613
 2614        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2615            return true;
 2616        }
 2617
 2618        if self.snippet_stack.pop().is_some() {
 2619            return true;
 2620        }
 2621
 2622        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2623            self.dismiss_diagnostics(cx);
 2624            return true;
 2625        }
 2626
 2627        false
 2628    }
 2629
 2630    fn linked_editing_ranges_for(
 2631        &self,
 2632        selection: Range<text::Anchor>,
 2633        cx: &App,
 2634    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2635        if self.linked_edit_ranges.is_empty() {
 2636            return None;
 2637        }
 2638        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2639            selection.end.buffer_id.and_then(|end_buffer_id| {
 2640                if selection.start.buffer_id != Some(end_buffer_id) {
 2641                    return None;
 2642                }
 2643                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2644                let snapshot = buffer.read(cx).snapshot();
 2645                self.linked_edit_ranges
 2646                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2647                    .map(|ranges| (ranges, snapshot, buffer))
 2648            })?;
 2649        use text::ToOffset as TO;
 2650        // find offset from the start of current range to current cursor position
 2651        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2652
 2653        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2654        let start_difference = start_offset - start_byte_offset;
 2655        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2656        let end_difference = end_offset - start_byte_offset;
 2657        // Current range has associated linked ranges.
 2658        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2659        for range in linked_ranges.iter() {
 2660            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2661            let end_offset = start_offset + end_difference;
 2662            let start_offset = start_offset + start_difference;
 2663            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2664                continue;
 2665            }
 2666            if self.selections.disjoint_anchor_ranges().any(|s| {
 2667                if s.start.buffer_id != selection.start.buffer_id
 2668                    || s.end.buffer_id != selection.end.buffer_id
 2669                {
 2670                    return false;
 2671                }
 2672                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2673                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2674            }) {
 2675                continue;
 2676            }
 2677            let start = buffer_snapshot.anchor_after(start_offset);
 2678            let end = buffer_snapshot.anchor_after(end_offset);
 2679            linked_edits
 2680                .entry(buffer.clone())
 2681                .or_default()
 2682                .push(start..end);
 2683        }
 2684        Some(linked_edits)
 2685    }
 2686
 2687    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2688        let text: Arc<str> = text.into();
 2689
 2690        if self.read_only(cx) {
 2691            return;
 2692        }
 2693
 2694        let selections = self.selections.all_adjusted(cx);
 2695        let mut bracket_inserted = false;
 2696        let mut edits = Vec::new();
 2697        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2698        let mut new_selections = Vec::with_capacity(selections.len());
 2699        let mut new_autoclose_regions = Vec::new();
 2700        let snapshot = self.buffer.read(cx).read(cx);
 2701
 2702        for (selection, autoclose_region) in
 2703            self.selections_with_autoclose_regions(selections, &snapshot)
 2704        {
 2705            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2706                // Determine if the inserted text matches the opening or closing
 2707                // bracket of any of this language's bracket pairs.
 2708                let mut bracket_pair = None;
 2709                let mut is_bracket_pair_start = false;
 2710                let mut is_bracket_pair_end = false;
 2711                if !text.is_empty() {
 2712                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2713                    //  and they are removing the character that triggered IME popup.
 2714                    for (pair, enabled) in scope.brackets() {
 2715                        if !pair.close && !pair.surround {
 2716                            continue;
 2717                        }
 2718
 2719                        if enabled && pair.start.ends_with(text.as_ref()) {
 2720                            let prefix_len = pair.start.len() - text.len();
 2721                            let preceding_text_matches_prefix = prefix_len == 0
 2722                                || (selection.start.column >= (prefix_len as u32)
 2723                                    && snapshot.contains_str_at(
 2724                                        Point::new(
 2725                                            selection.start.row,
 2726                                            selection.start.column - (prefix_len as u32),
 2727                                        ),
 2728                                        &pair.start[..prefix_len],
 2729                                    ));
 2730                            if preceding_text_matches_prefix {
 2731                                bracket_pair = Some(pair.clone());
 2732                                is_bracket_pair_start = true;
 2733                                break;
 2734                            }
 2735                        }
 2736                        if pair.end.as_str() == text.as_ref() {
 2737                            bracket_pair = Some(pair.clone());
 2738                            is_bracket_pair_end = true;
 2739                            break;
 2740                        }
 2741                    }
 2742                }
 2743
 2744                if let Some(bracket_pair) = bracket_pair {
 2745                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2746                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2747                    let auto_surround =
 2748                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2749                    if selection.is_empty() {
 2750                        if is_bracket_pair_start {
 2751                            // If the inserted text is a suffix of an opening bracket and the
 2752                            // selection is preceded by the rest of the opening bracket, then
 2753                            // insert the closing bracket.
 2754                            let following_text_allows_autoclose = snapshot
 2755                                .chars_at(selection.start)
 2756                                .next()
 2757                                .map_or(true, |c| scope.should_autoclose_before(c));
 2758
 2759                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2760                                && bracket_pair.start.len() == 1
 2761                            {
 2762                                let target = bracket_pair.start.chars().next().unwrap();
 2763                                let current_line_count = snapshot
 2764                                    .reversed_chars_at(selection.start)
 2765                                    .take_while(|&c| c != '\n')
 2766                                    .filter(|&c| c == target)
 2767                                    .count();
 2768                                current_line_count % 2 == 1
 2769                            } else {
 2770                                false
 2771                            };
 2772
 2773                            if autoclose
 2774                                && bracket_pair.close
 2775                                && following_text_allows_autoclose
 2776                                && !is_closing_quote
 2777                            {
 2778                                let anchor = snapshot.anchor_before(selection.end);
 2779                                new_selections.push((selection.map(|_| anchor), text.len()));
 2780                                new_autoclose_regions.push((
 2781                                    anchor,
 2782                                    text.len(),
 2783                                    selection.id,
 2784                                    bracket_pair.clone(),
 2785                                ));
 2786                                edits.push((
 2787                                    selection.range(),
 2788                                    format!("{}{}", text, bracket_pair.end).into(),
 2789                                ));
 2790                                bracket_inserted = true;
 2791                                continue;
 2792                            }
 2793                        }
 2794
 2795                        if let Some(region) = autoclose_region {
 2796                            // If the selection is followed by an auto-inserted closing bracket,
 2797                            // then don't insert that closing bracket again; just move the selection
 2798                            // past the closing bracket.
 2799                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2800                                && text.as_ref() == region.pair.end.as_str();
 2801                            if should_skip {
 2802                                let anchor = snapshot.anchor_after(selection.end);
 2803                                new_selections
 2804                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2805                                continue;
 2806                            }
 2807                        }
 2808
 2809                        let always_treat_brackets_as_autoclosed = snapshot
 2810                            .settings_at(selection.start, cx)
 2811                            .always_treat_brackets_as_autoclosed;
 2812                        if always_treat_brackets_as_autoclosed
 2813                            && is_bracket_pair_end
 2814                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2815                        {
 2816                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2817                            // and the inserted text is a closing bracket and the selection is followed
 2818                            // by the closing bracket then move the selection past the closing bracket.
 2819                            let anchor = snapshot.anchor_after(selection.end);
 2820                            new_selections.push((selection.map(|_| anchor), text.len()));
 2821                            continue;
 2822                        }
 2823                    }
 2824                    // If an opening bracket is 1 character long and is typed while
 2825                    // text is selected, then surround that text with the bracket pair.
 2826                    else if auto_surround
 2827                        && bracket_pair.surround
 2828                        && is_bracket_pair_start
 2829                        && bracket_pair.start.chars().count() == 1
 2830                    {
 2831                        edits.push((selection.start..selection.start, text.clone()));
 2832                        edits.push((
 2833                            selection.end..selection.end,
 2834                            bracket_pair.end.as_str().into(),
 2835                        ));
 2836                        bracket_inserted = true;
 2837                        new_selections.push((
 2838                            Selection {
 2839                                id: selection.id,
 2840                                start: snapshot.anchor_after(selection.start),
 2841                                end: snapshot.anchor_before(selection.end),
 2842                                reversed: selection.reversed,
 2843                                goal: selection.goal,
 2844                            },
 2845                            0,
 2846                        ));
 2847                        continue;
 2848                    }
 2849                }
 2850            }
 2851
 2852            if self.auto_replace_emoji_shortcode
 2853                && selection.is_empty()
 2854                && text.as_ref().ends_with(':')
 2855            {
 2856                if let Some(possible_emoji_short_code) =
 2857                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2858                {
 2859                    if !possible_emoji_short_code.is_empty() {
 2860                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2861                            let emoji_shortcode_start = Point::new(
 2862                                selection.start.row,
 2863                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2864                            );
 2865
 2866                            // Remove shortcode from buffer
 2867                            edits.push((
 2868                                emoji_shortcode_start..selection.start,
 2869                                "".to_string().into(),
 2870                            ));
 2871                            new_selections.push((
 2872                                Selection {
 2873                                    id: selection.id,
 2874                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2875                                    end: snapshot.anchor_before(selection.start),
 2876                                    reversed: selection.reversed,
 2877                                    goal: selection.goal,
 2878                                },
 2879                                0,
 2880                            ));
 2881
 2882                            // Insert emoji
 2883                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2884                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2885                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2886
 2887                            continue;
 2888                        }
 2889                    }
 2890                }
 2891            }
 2892
 2893            // If not handling any auto-close operation, then just replace the selected
 2894            // text with the given input and move the selection to the end of the
 2895            // newly inserted text.
 2896            let anchor = snapshot.anchor_after(selection.end);
 2897            if !self.linked_edit_ranges.is_empty() {
 2898                let start_anchor = snapshot.anchor_before(selection.start);
 2899
 2900                let is_word_char = text.chars().next().map_or(true, |char| {
 2901                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2902                    classifier.is_word(char)
 2903                });
 2904
 2905                if is_word_char {
 2906                    if let Some(ranges) = self
 2907                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2908                    {
 2909                        for (buffer, edits) in ranges {
 2910                            linked_edits
 2911                                .entry(buffer.clone())
 2912                                .or_default()
 2913                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2914                        }
 2915                    }
 2916                }
 2917            }
 2918
 2919            new_selections.push((selection.map(|_| anchor), 0));
 2920            edits.push((selection.start..selection.end, text.clone()));
 2921        }
 2922
 2923        drop(snapshot);
 2924
 2925        self.transact(window, cx, |this, window, cx| {
 2926            this.buffer.update(cx, |buffer, cx| {
 2927                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2928            });
 2929            for (buffer, edits) in linked_edits {
 2930                buffer.update(cx, |buffer, cx| {
 2931                    let snapshot = buffer.snapshot();
 2932                    let edits = edits
 2933                        .into_iter()
 2934                        .map(|(range, text)| {
 2935                            use text::ToPoint as TP;
 2936                            let end_point = TP::to_point(&range.end, &snapshot);
 2937                            let start_point = TP::to_point(&range.start, &snapshot);
 2938                            (start_point..end_point, text)
 2939                        })
 2940                        .sorted_by_key(|(range, _)| range.start)
 2941                        .collect::<Vec<_>>();
 2942                    buffer.edit(edits, None, cx);
 2943                })
 2944            }
 2945            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2946            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2947            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2948            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2949                .zip(new_selection_deltas)
 2950                .map(|(selection, delta)| Selection {
 2951                    id: selection.id,
 2952                    start: selection.start + delta,
 2953                    end: selection.end + delta,
 2954                    reversed: selection.reversed,
 2955                    goal: SelectionGoal::None,
 2956                })
 2957                .collect::<Vec<_>>();
 2958
 2959            let mut i = 0;
 2960            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2961                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2962                let start = map.buffer_snapshot.anchor_before(position);
 2963                let end = map.buffer_snapshot.anchor_after(position);
 2964                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2965                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2966                        Ordering::Less => i += 1,
 2967                        Ordering::Greater => break,
 2968                        Ordering::Equal => {
 2969                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2970                                Ordering::Less => i += 1,
 2971                                Ordering::Equal => break,
 2972                                Ordering::Greater => break,
 2973                            }
 2974                        }
 2975                    }
 2976                }
 2977                this.autoclose_regions.insert(
 2978                    i,
 2979                    AutocloseRegion {
 2980                        selection_id,
 2981                        range: start..end,
 2982                        pair,
 2983                    },
 2984                );
 2985            }
 2986
 2987            let had_active_inline_completion = this.has_active_inline_completion();
 2988            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2989                s.select(new_selections)
 2990            });
 2991
 2992            if !bracket_inserted {
 2993                if let Some(on_type_format_task) =
 2994                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2995                {
 2996                    on_type_format_task.detach_and_log_err(cx);
 2997                }
 2998            }
 2999
 3000            let editor_settings = EditorSettings::get_global(cx);
 3001            if bracket_inserted
 3002                && (editor_settings.auto_signature_help
 3003                    || editor_settings.show_signature_help_after_edits)
 3004            {
 3005                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3006            }
 3007
 3008            let trigger_in_words =
 3009                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3010            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3011            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3012            this.refresh_inline_completion(true, false, window, cx);
 3013        });
 3014    }
 3015
 3016    fn find_possible_emoji_shortcode_at_position(
 3017        snapshot: &MultiBufferSnapshot,
 3018        position: Point,
 3019    ) -> Option<String> {
 3020        let mut chars = Vec::new();
 3021        let mut found_colon = false;
 3022        for char in snapshot.reversed_chars_at(position).take(100) {
 3023            // Found a possible emoji shortcode in the middle of the buffer
 3024            if found_colon {
 3025                if char.is_whitespace() {
 3026                    chars.reverse();
 3027                    return Some(chars.iter().collect());
 3028                }
 3029                // If the previous character is not a whitespace, we are in the middle of a word
 3030                // and we only want to complete the shortcode if the word is made up of other emojis
 3031                let mut containing_word = String::new();
 3032                for ch in snapshot
 3033                    .reversed_chars_at(position)
 3034                    .skip(chars.len() + 1)
 3035                    .take(100)
 3036                {
 3037                    if ch.is_whitespace() {
 3038                        break;
 3039                    }
 3040                    containing_word.push(ch);
 3041                }
 3042                let containing_word = containing_word.chars().rev().collect::<String>();
 3043                if util::word_consists_of_emojis(containing_word.as_str()) {
 3044                    chars.reverse();
 3045                    return Some(chars.iter().collect());
 3046                }
 3047            }
 3048
 3049            if char.is_whitespace() || !char.is_ascii() {
 3050                return None;
 3051            }
 3052            if char == ':' {
 3053                found_colon = true;
 3054            } else {
 3055                chars.push(char);
 3056            }
 3057        }
 3058        // Found a possible emoji shortcode at the beginning of the buffer
 3059        chars.reverse();
 3060        Some(chars.iter().collect())
 3061    }
 3062
 3063    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3064        self.transact(window, cx, |this, window, cx| {
 3065            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3066                let selections = this.selections.all::<usize>(cx);
 3067                let multi_buffer = this.buffer.read(cx);
 3068                let buffer = multi_buffer.snapshot(cx);
 3069                selections
 3070                    .iter()
 3071                    .map(|selection| {
 3072                        let start_point = selection.start.to_point(&buffer);
 3073                        let mut indent =
 3074                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3075                        indent.len = cmp::min(indent.len, start_point.column);
 3076                        let start = selection.start;
 3077                        let end = selection.end;
 3078                        let selection_is_empty = start == end;
 3079                        let language_scope = buffer.language_scope_at(start);
 3080                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3081                            &language_scope
 3082                        {
 3083                            let leading_whitespace_len = buffer
 3084                                .reversed_chars_at(start)
 3085                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3086                                .map(|c| c.len_utf8())
 3087                                .sum::<usize>();
 3088
 3089                            let trailing_whitespace_len = buffer
 3090                                .chars_at(end)
 3091                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3092                                .map(|c| c.len_utf8())
 3093                                .sum::<usize>();
 3094
 3095                            let insert_extra_newline =
 3096                                language.brackets().any(|(pair, enabled)| {
 3097                                    let pair_start = pair.start.trim_end();
 3098                                    let pair_end = pair.end.trim_start();
 3099
 3100                                    enabled
 3101                                        && pair.newline
 3102                                        && buffer.contains_str_at(
 3103                                            end + trailing_whitespace_len,
 3104                                            pair_end,
 3105                                        )
 3106                                        && buffer.contains_str_at(
 3107                                            (start - leading_whitespace_len)
 3108                                                .saturating_sub(pair_start.len()),
 3109                                            pair_start,
 3110                                        )
 3111                                });
 3112
 3113                            // Comment extension on newline is allowed only for cursor selections
 3114                            let comment_delimiter = maybe!({
 3115                                if !selection_is_empty {
 3116                                    return None;
 3117                                }
 3118
 3119                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3120                                    return None;
 3121                                }
 3122
 3123                                let delimiters = language.line_comment_prefixes();
 3124                                let max_len_of_delimiter =
 3125                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3126                                let (snapshot, range) =
 3127                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3128
 3129                                let mut index_of_first_non_whitespace = 0;
 3130                                let comment_candidate = snapshot
 3131                                    .chars_for_range(range)
 3132                                    .skip_while(|c| {
 3133                                        let should_skip = c.is_whitespace();
 3134                                        if should_skip {
 3135                                            index_of_first_non_whitespace += 1;
 3136                                        }
 3137                                        should_skip
 3138                                    })
 3139                                    .take(max_len_of_delimiter)
 3140                                    .collect::<String>();
 3141                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3142                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3143                                })?;
 3144                                let cursor_is_placed_after_comment_marker =
 3145                                    index_of_first_non_whitespace + comment_prefix.len()
 3146                                        <= start_point.column as usize;
 3147                                if cursor_is_placed_after_comment_marker {
 3148                                    Some(comment_prefix.clone())
 3149                                } else {
 3150                                    None
 3151                                }
 3152                            });
 3153                            (comment_delimiter, insert_extra_newline)
 3154                        } else {
 3155                            (None, false)
 3156                        };
 3157
 3158                        let capacity_for_delimiter = comment_delimiter
 3159                            .as_deref()
 3160                            .map(str::len)
 3161                            .unwrap_or_default();
 3162                        let mut new_text =
 3163                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3164                        new_text.push('\n');
 3165                        new_text.extend(indent.chars());
 3166                        if let Some(delimiter) = &comment_delimiter {
 3167                            new_text.push_str(delimiter);
 3168                        }
 3169                        if insert_extra_newline {
 3170                            new_text = new_text.repeat(2);
 3171                        }
 3172
 3173                        let anchor = buffer.anchor_after(end);
 3174                        let new_selection = selection.map(|_| anchor);
 3175                        (
 3176                            (start..end, new_text),
 3177                            (insert_extra_newline, new_selection),
 3178                        )
 3179                    })
 3180                    .unzip()
 3181            };
 3182
 3183            this.edit_with_autoindent(edits, cx);
 3184            let buffer = this.buffer.read(cx).snapshot(cx);
 3185            let new_selections = selection_fixup_info
 3186                .into_iter()
 3187                .map(|(extra_newline_inserted, new_selection)| {
 3188                    let mut cursor = new_selection.end.to_point(&buffer);
 3189                    if extra_newline_inserted {
 3190                        cursor.row -= 1;
 3191                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3192                    }
 3193                    new_selection.map(|_| cursor)
 3194                })
 3195                .collect();
 3196
 3197            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3198                s.select(new_selections)
 3199            });
 3200            this.refresh_inline_completion(true, false, window, cx);
 3201        });
 3202    }
 3203
 3204    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3205        let buffer = self.buffer.read(cx);
 3206        let snapshot = buffer.snapshot(cx);
 3207
 3208        let mut edits = Vec::new();
 3209        let mut rows = Vec::new();
 3210
 3211        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3212            let cursor = selection.head();
 3213            let row = cursor.row;
 3214
 3215            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3216
 3217            let newline = "\n".to_string();
 3218            edits.push((start_of_line..start_of_line, newline));
 3219
 3220            rows.push(row + rows_inserted as u32);
 3221        }
 3222
 3223        self.transact(window, cx, |editor, window, cx| {
 3224            editor.edit(edits, cx);
 3225
 3226            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3227                let mut index = 0;
 3228                s.move_cursors_with(|map, _, _| {
 3229                    let row = rows[index];
 3230                    index += 1;
 3231
 3232                    let point = Point::new(row, 0);
 3233                    let boundary = map.next_line_boundary(point).1;
 3234                    let clipped = map.clip_point(boundary, Bias::Left);
 3235
 3236                    (clipped, SelectionGoal::None)
 3237                });
 3238            });
 3239
 3240            let mut indent_edits = Vec::new();
 3241            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3242            for row in rows {
 3243                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3244                for (row, indent) in indents {
 3245                    if indent.len == 0 {
 3246                        continue;
 3247                    }
 3248
 3249                    let text = match indent.kind {
 3250                        IndentKind::Space => " ".repeat(indent.len as usize),
 3251                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3252                    };
 3253                    let point = Point::new(row.0, 0);
 3254                    indent_edits.push((point..point, text));
 3255                }
 3256            }
 3257            editor.edit(indent_edits, cx);
 3258        });
 3259    }
 3260
 3261    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3262        let buffer = self.buffer.read(cx);
 3263        let snapshot = buffer.snapshot(cx);
 3264
 3265        let mut edits = Vec::new();
 3266        let mut rows = Vec::new();
 3267        let mut rows_inserted = 0;
 3268
 3269        for selection in self.selections.all_adjusted(cx) {
 3270            let cursor = selection.head();
 3271            let row = cursor.row;
 3272
 3273            let point = Point::new(row + 1, 0);
 3274            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3275
 3276            let newline = "\n".to_string();
 3277            edits.push((start_of_line..start_of_line, newline));
 3278
 3279            rows_inserted += 1;
 3280            rows.push(row + rows_inserted);
 3281        }
 3282
 3283        self.transact(window, cx, |editor, window, cx| {
 3284            editor.edit(edits, cx);
 3285
 3286            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3287                let mut index = 0;
 3288                s.move_cursors_with(|map, _, _| {
 3289                    let row = rows[index];
 3290                    index += 1;
 3291
 3292                    let point = Point::new(row, 0);
 3293                    let boundary = map.next_line_boundary(point).1;
 3294                    let clipped = map.clip_point(boundary, Bias::Left);
 3295
 3296                    (clipped, SelectionGoal::None)
 3297                });
 3298            });
 3299
 3300            let mut indent_edits = Vec::new();
 3301            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3302            for row in rows {
 3303                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3304                for (row, indent) in indents {
 3305                    if indent.len == 0 {
 3306                        continue;
 3307                    }
 3308
 3309                    let text = match indent.kind {
 3310                        IndentKind::Space => " ".repeat(indent.len as usize),
 3311                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3312                    };
 3313                    let point = Point::new(row.0, 0);
 3314                    indent_edits.push((point..point, text));
 3315                }
 3316            }
 3317            editor.edit(indent_edits, cx);
 3318        });
 3319    }
 3320
 3321    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3322        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3323            original_indent_columns: Vec::new(),
 3324        });
 3325        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3326    }
 3327
 3328    fn insert_with_autoindent_mode(
 3329        &mut self,
 3330        text: &str,
 3331        autoindent_mode: Option<AutoindentMode>,
 3332        window: &mut Window,
 3333        cx: &mut Context<Self>,
 3334    ) {
 3335        if self.read_only(cx) {
 3336            return;
 3337        }
 3338
 3339        let text: Arc<str> = text.into();
 3340        self.transact(window, cx, |this, window, cx| {
 3341            let old_selections = this.selections.all_adjusted(cx);
 3342            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3343                let anchors = {
 3344                    let snapshot = buffer.read(cx);
 3345                    old_selections
 3346                        .iter()
 3347                        .map(|s| {
 3348                            let anchor = snapshot.anchor_after(s.head());
 3349                            s.map(|_| anchor)
 3350                        })
 3351                        .collect::<Vec<_>>()
 3352                };
 3353                buffer.edit(
 3354                    old_selections
 3355                        .iter()
 3356                        .map(|s| (s.start..s.end, text.clone())),
 3357                    autoindent_mode,
 3358                    cx,
 3359                );
 3360                anchors
 3361            });
 3362
 3363            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3364                s.select_anchors(selection_anchors);
 3365            });
 3366
 3367            cx.notify();
 3368        });
 3369    }
 3370
 3371    fn trigger_completion_on_input(
 3372        &mut self,
 3373        text: &str,
 3374        trigger_in_words: bool,
 3375        window: &mut Window,
 3376        cx: &mut Context<Self>,
 3377    ) {
 3378        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3379            self.show_completions(
 3380                &ShowCompletions {
 3381                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3382                },
 3383                window,
 3384                cx,
 3385            );
 3386        } else {
 3387            self.hide_context_menu(window, cx);
 3388        }
 3389    }
 3390
 3391    fn is_completion_trigger(
 3392        &self,
 3393        text: &str,
 3394        trigger_in_words: bool,
 3395        cx: &mut Context<Self>,
 3396    ) -> bool {
 3397        let position = self.selections.newest_anchor().head();
 3398        let multibuffer = self.buffer.read(cx);
 3399        let Some(buffer) = position
 3400            .buffer_id
 3401            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3402        else {
 3403            return false;
 3404        };
 3405
 3406        if let Some(completion_provider) = &self.completion_provider {
 3407            completion_provider.is_completion_trigger(
 3408                &buffer,
 3409                position.text_anchor,
 3410                text,
 3411                trigger_in_words,
 3412                cx,
 3413            )
 3414        } else {
 3415            false
 3416        }
 3417    }
 3418
 3419    /// If any empty selections is touching the start of its innermost containing autoclose
 3420    /// region, expand it to select the brackets.
 3421    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3422        let selections = self.selections.all::<usize>(cx);
 3423        let buffer = self.buffer.read(cx).read(cx);
 3424        let new_selections = self
 3425            .selections_with_autoclose_regions(selections, &buffer)
 3426            .map(|(mut selection, region)| {
 3427                if !selection.is_empty() {
 3428                    return selection;
 3429                }
 3430
 3431                if let Some(region) = region {
 3432                    let mut range = region.range.to_offset(&buffer);
 3433                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3434                        range.start -= region.pair.start.len();
 3435                        if buffer.contains_str_at(range.start, &region.pair.start)
 3436                            && buffer.contains_str_at(range.end, &region.pair.end)
 3437                        {
 3438                            range.end += region.pair.end.len();
 3439                            selection.start = range.start;
 3440                            selection.end = range.end;
 3441
 3442                            return selection;
 3443                        }
 3444                    }
 3445                }
 3446
 3447                let always_treat_brackets_as_autoclosed = buffer
 3448                    .settings_at(selection.start, cx)
 3449                    .always_treat_brackets_as_autoclosed;
 3450
 3451                if !always_treat_brackets_as_autoclosed {
 3452                    return selection;
 3453                }
 3454
 3455                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3456                    for (pair, enabled) in scope.brackets() {
 3457                        if !enabled || !pair.close {
 3458                            continue;
 3459                        }
 3460
 3461                        if buffer.contains_str_at(selection.start, &pair.end) {
 3462                            let pair_start_len = pair.start.len();
 3463                            if buffer.contains_str_at(
 3464                                selection.start.saturating_sub(pair_start_len),
 3465                                &pair.start,
 3466                            ) {
 3467                                selection.start -= pair_start_len;
 3468                                selection.end += pair.end.len();
 3469
 3470                                return selection;
 3471                            }
 3472                        }
 3473                    }
 3474                }
 3475
 3476                selection
 3477            })
 3478            .collect();
 3479
 3480        drop(buffer);
 3481        self.change_selections(None, window, cx, |selections| {
 3482            selections.select(new_selections)
 3483        });
 3484    }
 3485
 3486    /// Iterate the given selections, and for each one, find the smallest surrounding
 3487    /// autoclose region. This uses the ordering of the selections and the autoclose
 3488    /// regions to avoid repeated comparisons.
 3489    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3490        &'a self,
 3491        selections: impl IntoIterator<Item = Selection<D>>,
 3492        buffer: &'a MultiBufferSnapshot,
 3493    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3494        let mut i = 0;
 3495        let mut regions = self.autoclose_regions.as_slice();
 3496        selections.into_iter().map(move |selection| {
 3497            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3498
 3499            let mut enclosing = None;
 3500            while let Some(pair_state) = regions.get(i) {
 3501                if pair_state.range.end.to_offset(buffer) < range.start {
 3502                    regions = &regions[i + 1..];
 3503                    i = 0;
 3504                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3505                    break;
 3506                } else {
 3507                    if pair_state.selection_id == selection.id {
 3508                        enclosing = Some(pair_state);
 3509                    }
 3510                    i += 1;
 3511                }
 3512            }
 3513
 3514            (selection, enclosing)
 3515        })
 3516    }
 3517
 3518    /// Remove any autoclose regions that no longer contain their selection.
 3519    fn invalidate_autoclose_regions(
 3520        &mut self,
 3521        mut selections: &[Selection<Anchor>],
 3522        buffer: &MultiBufferSnapshot,
 3523    ) {
 3524        self.autoclose_regions.retain(|state| {
 3525            let mut i = 0;
 3526            while let Some(selection) = selections.get(i) {
 3527                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3528                    selections = &selections[1..];
 3529                    continue;
 3530                }
 3531                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3532                    break;
 3533                }
 3534                if selection.id == state.selection_id {
 3535                    return true;
 3536                } else {
 3537                    i += 1;
 3538                }
 3539            }
 3540            false
 3541        });
 3542    }
 3543
 3544    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3545        let offset = position.to_offset(buffer);
 3546        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3547        if offset > word_range.start && kind == Some(CharKind::Word) {
 3548            Some(
 3549                buffer
 3550                    .text_for_range(word_range.start..offset)
 3551                    .collect::<String>(),
 3552            )
 3553        } else {
 3554            None
 3555        }
 3556    }
 3557
 3558    pub fn toggle_inlay_hints(
 3559        &mut self,
 3560        _: &ToggleInlayHints,
 3561        _: &mut Window,
 3562        cx: &mut Context<Self>,
 3563    ) {
 3564        self.refresh_inlay_hints(
 3565            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3566            cx,
 3567        );
 3568    }
 3569
 3570    pub fn inlay_hints_enabled(&self) -> bool {
 3571        self.inlay_hint_cache.enabled
 3572    }
 3573
 3574    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3575        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3576            return;
 3577        }
 3578
 3579        let reason_description = reason.description();
 3580        let ignore_debounce = matches!(
 3581            reason,
 3582            InlayHintRefreshReason::SettingsChange(_)
 3583                | InlayHintRefreshReason::Toggle(_)
 3584                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3585        );
 3586        let (invalidate_cache, required_languages) = match reason {
 3587            InlayHintRefreshReason::Toggle(enabled) => {
 3588                self.inlay_hint_cache.enabled = enabled;
 3589                if enabled {
 3590                    (InvalidationStrategy::RefreshRequested, None)
 3591                } else {
 3592                    self.inlay_hint_cache.clear();
 3593                    self.splice_inlays(
 3594                        &self
 3595                            .visible_inlay_hints(cx)
 3596                            .iter()
 3597                            .map(|inlay| inlay.id)
 3598                            .collect::<Vec<InlayId>>(),
 3599                        Vec::new(),
 3600                        cx,
 3601                    );
 3602                    return;
 3603                }
 3604            }
 3605            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3606                match self.inlay_hint_cache.update_settings(
 3607                    &self.buffer,
 3608                    new_settings,
 3609                    self.visible_inlay_hints(cx),
 3610                    cx,
 3611                ) {
 3612                    ControlFlow::Break(Some(InlaySplice {
 3613                        to_remove,
 3614                        to_insert,
 3615                    })) => {
 3616                        self.splice_inlays(&to_remove, to_insert, cx);
 3617                        return;
 3618                    }
 3619                    ControlFlow::Break(None) => return,
 3620                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3621                }
 3622            }
 3623            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3624                if let Some(InlaySplice {
 3625                    to_remove,
 3626                    to_insert,
 3627                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3628                {
 3629                    self.splice_inlays(&to_remove, to_insert, cx);
 3630                }
 3631                return;
 3632            }
 3633            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3634            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3635                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3636            }
 3637            InlayHintRefreshReason::RefreshRequested => {
 3638                (InvalidationStrategy::RefreshRequested, None)
 3639            }
 3640        };
 3641
 3642        if let Some(InlaySplice {
 3643            to_remove,
 3644            to_insert,
 3645        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3646            reason_description,
 3647            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3648            invalidate_cache,
 3649            ignore_debounce,
 3650            cx,
 3651        ) {
 3652            self.splice_inlays(&to_remove, to_insert, cx);
 3653        }
 3654    }
 3655
 3656    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3657        self.display_map
 3658            .read(cx)
 3659            .current_inlays()
 3660            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3661            .cloned()
 3662            .collect()
 3663    }
 3664
 3665    pub fn excerpts_for_inlay_hints_query(
 3666        &self,
 3667        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3668        cx: &mut Context<Editor>,
 3669    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3670        let Some(project) = self.project.as_ref() else {
 3671            return HashMap::default();
 3672        };
 3673        let project = project.read(cx);
 3674        let multi_buffer = self.buffer().read(cx);
 3675        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3676        let multi_buffer_visible_start = self
 3677            .scroll_manager
 3678            .anchor()
 3679            .anchor
 3680            .to_point(&multi_buffer_snapshot);
 3681        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3682            multi_buffer_visible_start
 3683                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3684            Bias::Left,
 3685        );
 3686        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3687        multi_buffer_snapshot
 3688            .range_to_buffer_ranges(multi_buffer_visible_range)
 3689            .into_iter()
 3690            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3691            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3692                let buffer_file = project::File::from_dyn(buffer.file())?;
 3693                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3694                let worktree_entry = buffer_worktree
 3695                    .read(cx)
 3696                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3697                if worktree_entry.is_ignored {
 3698                    return None;
 3699                }
 3700
 3701                let language = buffer.language()?;
 3702                if let Some(restrict_to_languages) = restrict_to_languages {
 3703                    if !restrict_to_languages.contains(language) {
 3704                        return None;
 3705                    }
 3706                }
 3707                Some((
 3708                    excerpt_id,
 3709                    (
 3710                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3711                        buffer.version().clone(),
 3712                        excerpt_visible_range,
 3713                    ),
 3714                ))
 3715            })
 3716            .collect()
 3717    }
 3718
 3719    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3720        TextLayoutDetails {
 3721            text_system: window.text_system().clone(),
 3722            editor_style: self.style.clone().unwrap(),
 3723            rem_size: window.rem_size(),
 3724            scroll_anchor: self.scroll_manager.anchor(),
 3725            visible_rows: self.visible_line_count(),
 3726            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3727        }
 3728    }
 3729
 3730    pub fn splice_inlays(
 3731        &self,
 3732        to_remove: &[InlayId],
 3733        to_insert: Vec<Inlay>,
 3734        cx: &mut Context<Self>,
 3735    ) {
 3736        self.display_map.update(cx, |display_map, cx| {
 3737            display_map.splice_inlays(to_remove, to_insert, cx)
 3738        });
 3739        cx.notify();
 3740    }
 3741
 3742    fn trigger_on_type_formatting(
 3743        &self,
 3744        input: String,
 3745        window: &mut Window,
 3746        cx: &mut Context<Self>,
 3747    ) -> Option<Task<Result<()>>> {
 3748        if input.len() != 1 {
 3749            return None;
 3750        }
 3751
 3752        let project = self.project.as_ref()?;
 3753        let position = self.selections.newest_anchor().head();
 3754        let (buffer, buffer_position) = self
 3755            .buffer
 3756            .read(cx)
 3757            .text_anchor_for_position(position, cx)?;
 3758
 3759        let settings = language_settings::language_settings(
 3760            buffer
 3761                .read(cx)
 3762                .language_at(buffer_position)
 3763                .map(|l| l.name()),
 3764            buffer.read(cx).file(),
 3765            cx,
 3766        );
 3767        if !settings.use_on_type_format {
 3768            return None;
 3769        }
 3770
 3771        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3772        // hence we do LSP request & edit on host side only — add formats to host's history.
 3773        let push_to_lsp_host_history = true;
 3774        // If this is not the host, append its history with new edits.
 3775        let push_to_client_history = project.read(cx).is_via_collab();
 3776
 3777        let on_type_formatting = project.update(cx, |project, cx| {
 3778            project.on_type_format(
 3779                buffer.clone(),
 3780                buffer_position,
 3781                input,
 3782                push_to_lsp_host_history,
 3783                cx,
 3784            )
 3785        });
 3786        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3787            if let Some(transaction) = on_type_formatting.await? {
 3788                if push_to_client_history {
 3789                    buffer
 3790                        .update(&mut cx, |buffer, _| {
 3791                            buffer.push_transaction(transaction, Instant::now());
 3792                        })
 3793                        .ok();
 3794                }
 3795                editor.update(&mut cx, |editor, cx| {
 3796                    editor.refresh_document_highlights(cx);
 3797                })?;
 3798            }
 3799            Ok(())
 3800        }))
 3801    }
 3802
 3803    pub fn show_completions(
 3804        &mut self,
 3805        options: &ShowCompletions,
 3806        window: &mut Window,
 3807        cx: &mut Context<Self>,
 3808    ) {
 3809        if self.pending_rename.is_some() {
 3810            return;
 3811        }
 3812
 3813        let Some(provider) = self.completion_provider.as_ref() else {
 3814            return;
 3815        };
 3816
 3817        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3818            return;
 3819        }
 3820
 3821        let position = self.selections.newest_anchor().head();
 3822        if position.diff_base_anchor.is_some() {
 3823            return;
 3824        }
 3825        let (buffer, buffer_position) =
 3826            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3827                output
 3828            } else {
 3829                return;
 3830            };
 3831        let show_completion_documentation = buffer
 3832            .read(cx)
 3833            .snapshot()
 3834            .settings_at(buffer_position, cx)
 3835            .show_completion_documentation;
 3836
 3837        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3838
 3839        let trigger_kind = match &options.trigger {
 3840            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3841                CompletionTriggerKind::TRIGGER_CHARACTER
 3842            }
 3843            _ => CompletionTriggerKind::INVOKED,
 3844        };
 3845        let completion_context = CompletionContext {
 3846            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3847                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3848                    Some(String::from(trigger))
 3849                } else {
 3850                    None
 3851                }
 3852            }),
 3853            trigger_kind,
 3854        };
 3855        let completions =
 3856            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3857        let sort_completions = provider.sort_completions();
 3858
 3859        let id = post_inc(&mut self.next_completion_id);
 3860        let task = cx.spawn_in(window, |editor, mut cx| {
 3861            async move {
 3862                editor.update(&mut cx, |this, _| {
 3863                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3864                })?;
 3865                let completions = completions.await.log_err();
 3866                let menu = if let Some(completions) = completions {
 3867                    let mut menu = CompletionsMenu::new(
 3868                        id,
 3869                        sort_completions,
 3870                        show_completion_documentation,
 3871                        position,
 3872                        buffer.clone(),
 3873                        completions.into(),
 3874                    );
 3875
 3876                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3877                        .await;
 3878
 3879                    menu.visible().then_some(menu)
 3880                } else {
 3881                    None
 3882                };
 3883
 3884                editor.update_in(&mut cx, |editor, window, cx| {
 3885                    match editor.context_menu.borrow().as_ref() {
 3886                        None => {}
 3887                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3888                            if prev_menu.id > id {
 3889                                return;
 3890                            }
 3891                        }
 3892                        _ => return,
 3893                    }
 3894
 3895                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3896                        let mut menu = menu.unwrap();
 3897                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3898
 3899                        *editor.context_menu.borrow_mut() =
 3900                            Some(CodeContextMenu::Completions(menu));
 3901
 3902                        if editor.show_inline_completions_in_menu(cx) {
 3903                            editor.update_visible_inline_completion(window, cx);
 3904                        } else {
 3905                            editor.discard_inline_completion(false, cx);
 3906                        }
 3907
 3908                        cx.notify();
 3909                    } else if editor.completion_tasks.len() <= 1 {
 3910                        // If there are no more completion tasks and the last menu was
 3911                        // empty, we should hide it.
 3912                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3913                        // If it was already hidden and we don't show inline
 3914                        // completions in the menu, we should also show the
 3915                        // inline-completion when available.
 3916                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3917                            editor.update_visible_inline_completion(window, cx);
 3918                        }
 3919                    }
 3920                })?;
 3921
 3922                Ok::<_, anyhow::Error>(())
 3923            }
 3924            .log_err()
 3925        });
 3926
 3927        self.completion_tasks.push((id, task));
 3928    }
 3929
 3930    pub fn confirm_completion(
 3931        &mut self,
 3932        action: &ConfirmCompletion,
 3933        window: &mut Window,
 3934        cx: &mut Context<Self>,
 3935    ) -> Option<Task<Result<()>>> {
 3936        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3937    }
 3938
 3939    pub fn compose_completion(
 3940        &mut self,
 3941        action: &ComposeCompletion,
 3942        window: &mut Window,
 3943        cx: &mut Context<Self>,
 3944    ) -> Option<Task<Result<()>>> {
 3945        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3946    }
 3947
 3948    fn do_completion(
 3949        &mut self,
 3950        item_ix: Option<usize>,
 3951        intent: CompletionIntent,
 3952        window: &mut Window,
 3953        cx: &mut Context<Editor>,
 3954    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3955        use language::ToOffset as _;
 3956
 3957        let completions_menu =
 3958            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3959                menu
 3960            } else {
 3961                return None;
 3962            };
 3963
 3964        let entries = completions_menu.entries.borrow();
 3965        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3966        if self.show_inline_completions_in_menu(cx) {
 3967            self.discard_inline_completion(true, cx);
 3968        }
 3969        let candidate_id = mat.candidate_id;
 3970        drop(entries);
 3971
 3972        let buffer_handle = completions_menu.buffer;
 3973        let completion = completions_menu
 3974            .completions
 3975            .borrow()
 3976            .get(candidate_id)?
 3977            .clone();
 3978        cx.stop_propagation();
 3979
 3980        let snippet;
 3981        let text;
 3982
 3983        if completion.is_snippet() {
 3984            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3985            text = snippet.as_ref().unwrap().text.clone();
 3986        } else {
 3987            snippet = None;
 3988            text = completion.new_text.clone();
 3989        };
 3990        let selections = self.selections.all::<usize>(cx);
 3991        let buffer = buffer_handle.read(cx);
 3992        let old_range = completion.old_range.to_offset(buffer);
 3993        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3994
 3995        let newest_selection = self.selections.newest_anchor();
 3996        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3997            return None;
 3998        }
 3999
 4000        let lookbehind = newest_selection
 4001            .start
 4002            .text_anchor
 4003            .to_offset(buffer)
 4004            .saturating_sub(old_range.start);
 4005        let lookahead = old_range
 4006            .end
 4007            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4008        let mut common_prefix_len = old_text
 4009            .bytes()
 4010            .zip(text.bytes())
 4011            .take_while(|(a, b)| a == b)
 4012            .count();
 4013
 4014        let snapshot = self.buffer.read(cx).snapshot(cx);
 4015        let mut range_to_replace: Option<Range<isize>> = None;
 4016        let mut ranges = Vec::new();
 4017        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4018        for selection in &selections {
 4019            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4020                let start = selection.start.saturating_sub(lookbehind);
 4021                let end = selection.end + lookahead;
 4022                if selection.id == newest_selection.id {
 4023                    range_to_replace = Some(
 4024                        ((start + common_prefix_len) as isize - selection.start as isize)
 4025                            ..(end as isize - selection.start as isize),
 4026                    );
 4027                }
 4028                ranges.push(start + common_prefix_len..end);
 4029            } else {
 4030                common_prefix_len = 0;
 4031                ranges.clear();
 4032                ranges.extend(selections.iter().map(|s| {
 4033                    if s.id == newest_selection.id {
 4034                        range_to_replace = Some(
 4035                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4036                                - selection.start as isize
 4037                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4038                                    - selection.start as isize,
 4039                        );
 4040                        old_range.clone()
 4041                    } else {
 4042                        s.start..s.end
 4043                    }
 4044                }));
 4045                break;
 4046            }
 4047            if !self.linked_edit_ranges.is_empty() {
 4048                let start_anchor = snapshot.anchor_before(selection.head());
 4049                let end_anchor = snapshot.anchor_after(selection.tail());
 4050                if let Some(ranges) = self
 4051                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4052                {
 4053                    for (buffer, edits) in ranges {
 4054                        linked_edits.entry(buffer.clone()).or_default().extend(
 4055                            edits
 4056                                .into_iter()
 4057                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4058                        );
 4059                    }
 4060                }
 4061            }
 4062        }
 4063        let text = &text[common_prefix_len..];
 4064
 4065        cx.emit(EditorEvent::InputHandled {
 4066            utf16_range_to_replace: range_to_replace,
 4067            text: text.into(),
 4068        });
 4069
 4070        self.transact(window, cx, |this, window, cx| {
 4071            if let Some(mut snippet) = snippet {
 4072                snippet.text = text.to_string();
 4073                for tabstop in snippet
 4074                    .tabstops
 4075                    .iter_mut()
 4076                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4077                {
 4078                    tabstop.start -= common_prefix_len as isize;
 4079                    tabstop.end -= common_prefix_len as isize;
 4080                }
 4081
 4082                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4083            } else {
 4084                this.buffer.update(cx, |buffer, cx| {
 4085                    buffer.edit(
 4086                        ranges.iter().map(|range| (range.clone(), text)),
 4087                        this.autoindent_mode.clone(),
 4088                        cx,
 4089                    );
 4090                });
 4091            }
 4092            for (buffer, edits) in linked_edits {
 4093                buffer.update(cx, |buffer, cx| {
 4094                    let snapshot = buffer.snapshot();
 4095                    let edits = edits
 4096                        .into_iter()
 4097                        .map(|(range, text)| {
 4098                            use text::ToPoint as TP;
 4099                            let end_point = TP::to_point(&range.end, &snapshot);
 4100                            let start_point = TP::to_point(&range.start, &snapshot);
 4101                            (start_point..end_point, text)
 4102                        })
 4103                        .sorted_by_key(|(range, _)| range.start)
 4104                        .collect::<Vec<_>>();
 4105                    buffer.edit(edits, None, cx);
 4106                })
 4107            }
 4108
 4109            this.refresh_inline_completion(true, false, window, cx);
 4110        });
 4111
 4112        let show_new_completions_on_confirm = completion
 4113            .confirm
 4114            .as_ref()
 4115            .map_or(false, |confirm| confirm(intent, window, cx));
 4116        if show_new_completions_on_confirm {
 4117            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4118        }
 4119
 4120        let provider = self.completion_provider.as_ref()?;
 4121        drop(completion);
 4122        let apply_edits = provider.apply_additional_edits_for_completion(
 4123            buffer_handle,
 4124            completions_menu.completions.clone(),
 4125            candidate_id,
 4126            true,
 4127            cx,
 4128        );
 4129
 4130        let editor_settings = EditorSettings::get_global(cx);
 4131        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4132            // After the code completion is finished, users often want to know what signatures are needed.
 4133            // so we should automatically call signature_help
 4134            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4135        }
 4136
 4137        Some(cx.foreground_executor().spawn(async move {
 4138            apply_edits.await?;
 4139            Ok(())
 4140        }))
 4141    }
 4142
 4143    pub fn toggle_code_actions(
 4144        &mut self,
 4145        action: &ToggleCodeActions,
 4146        window: &mut Window,
 4147        cx: &mut Context<Self>,
 4148    ) {
 4149        let mut context_menu = self.context_menu.borrow_mut();
 4150        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4151            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4152                // Toggle if we're selecting the same one
 4153                *context_menu = None;
 4154                cx.notify();
 4155                return;
 4156            } else {
 4157                // Otherwise, clear it and start a new one
 4158                *context_menu = None;
 4159                cx.notify();
 4160            }
 4161        }
 4162        drop(context_menu);
 4163        let snapshot = self.snapshot(window, cx);
 4164        let deployed_from_indicator = action.deployed_from_indicator;
 4165        let mut task = self.code_actions_task.take();
 4166        let action = action.clone();
 4167        cx.spawn_in(window, |editor, mut cx| async move {
 4168            while let Some(prev_task) = task {
 4169                prev_task.await.log_err();
 4170                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4171            }
 4172
 4173            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4174                if editor.focus_handle.is_focused(window) {
 4175                    let multibuffer_point = action
 4176                        .deployed_from_indicator
 4177                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4178                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4179                    let (buffer, buffer_row) = snapshot
 4180                        .buffer_snapshot
 4181                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4182                        .and_then(|(buffer_snapshot, range)| {
 4183                            editor
 4184                                .buffer
 4185                                .read(cx)
 4186                                .buffer(buffer_snapshot.remote_id())
 4187                                .map(|buffer| (buffer, range.start.row))
 4188                        })?;
 4189                    let (_, code_actions) = editor
 4190                        .available_code_actions
 4191                        .clone()
 4192                        .and_then(|(location, code_actions)| {
 4193                            let snapshot = location.buffer.read(cx).snapshot();
 4194                            let point_range = location.range.to_point(&snapshot);
 4195                            let point_range = point_range.start.row..=point_range.end.row;
 4196                            if point_range.contains(&buffer_row) {
 4197                                Some((location, code_actions))
 4198                            } else {
 4199                                None
 4200                            }
 4201                        })
 4202                        .unzip();
 4203                    let buffer_id = buffer.read(cx).remote_id();
 4204                    let tasks = editor
 4205                        .tasks
 4206                        .get(&(buffer_id, buffer_row))
 4207                        .map(|t| Arc::new(t.to_owned()));
 4208                    if tasks.is_none() && code_actions.is_none() {
 4209                        return None;
 4210                    }
 4211
 4212                    editor.completion_tasks.clear();
 4213                    editor.discard_inline_completion(false, cx);
 4214                    let task_context =
 4215                        tasks
 4216                            .as_ref()
 4217                            .zip(editor.project.clone())
 4218                            .map(|(tasks, project)| {
 4219                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4220                            });
 4221
 4222                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4223                        let task_context = match task_context {
 4224                            Some(task_context) => task_context.await,
 4225                            None => None,
 4226                        };
 4227                        let resolved_tasks =
 4228                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4229                                Rc::new(ResolvedTasks {
 4230                                    templates: tasks.resolve(&task_context).collect(),
 4231                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4232                                        multibuffer_point.row,
 4233                                        tasks.column,
 4234                                    )),
 4235                                })
 4236                            });
 4237                        let spawn_straight_away = resolved_tasks
 4238                            .as_ref()
 4239                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4240                            && code_actions
 4241                                .as_ref()
 4242                                .map_or(true, |actions| actions.is_empty());
 4243                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4244                            *editor.context_menu.borrow_mut() =
 4245                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4246                                    buffer,
 4247                                    actions: CodeActionContents {
 4248                                        tasks: resolved_tasks,
 4249                                        actions: code_actions,
 4250                                    },
 4251                                    selected_item: Default::default(),
 4252                                    scroll_handle: UniformListScrollHandle::default(),
 4253                                    deployed_from_indicator,
 4254                                }));
 4255                            if spawn_straight_away {
 4256                                if let Some(task) = editor.confirm_code_action(
 4257                                    &ConfirmCodeAction { item_ix: Some(0) },
 4258                                    window,
 4259                                    cx,
 4260                                ) {
 4261                                    cx.notify();
 4262                                    return task;
 4263                                }
 4264                            }
 4265                            cx.notify();
 4266                            Task::ready(Ok(()))
 4267                        }) {
 4268                            task.await
 4269                        } else {
 4270                            Ok(())
 4271                        }
 4272                    }))
 4273                } else {
 4274                    Some(Task::ready(Ok(())))
 4275                }
 4276            })?;
 4277            if let Some(task) = spawned_test_task {
 4278                task.await?;
 4279            }
 4280
 4281            Ok::<_, anyhow::Error>(())
 4282        })
 4283        .detach_and_log_err(cx);
 4284    }
 4285
 4286    pub fn confirm_code_action(
 4287        &mut self,
 4288        action: &ConfirmCodeAction,
 4289        window: &mut Window,
 4290        cx: &mut Context<Self>,
 4291    ) -> Option<Task<Result<()>>> {
 4292        let actions_menu =
 4293            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4294                menu
 4295            } else {
 4296                return None;
 4297            };
 4298        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4299        let action = actions_menu.actions.get(action_ix)?;
 4300        let title = action.label();
 4301        let buffer = actions_menu.buffer;
 4302        let workspace = self.workspace()?;
 4303
 4304        match action {
 4305            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4306                workspace.update(cx, |workspace, cx| {
 4307                    workspace::tasks::schedule_resolved_task(
 4308                        workspace,
 4309                        task_source_kind,
 4310                        resolved_task,
 4311                        false,
 4312                        cx,
 4313                    );
 4314
 4315                    Some(Task::ready(Ok(())))
 4316                })
 4317            }
 4318            CodeActionsItem::CodeAction {
 4319                excerpt_id,
 4320                action,
 4321                provider,
 4322            } => {
 4323                let apply_code_action =
 4324                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4325                let workspace = workspace.downgrade();
 4326                Some(cx.spawn_in(window, |editor, cx| async move {
 4327                    let project_transaction = apply_code_action.await?;
 4328                    Self::open_project_transaction(
 4329                        &editor,
 4330                        workspace,
 4331                        project_transaction,
 4332                        title,
 4333                        cx,
 4334                    )
 4335                    .await
 4336                }))
 4337            }
 4338        }
 4339    }
 4340
 4341    pub async fn open_project_transaction(
 4342        this: &WeakEntity<Editor>,
 4343        workspace: WeakEntity<Workspace>,
 4344        transaction: ProjectTransaction,
 4345        title: String,
 4346        mut cx: AsyncWindowContext,
 4347    ) -> Result<()> {
 4348        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4349        cx.update(|_, cx| {
 4350            entries.sort_unstable_by_key(|(buffer, _)| {
 4351                buffer.read(cx).file().map(|f| f.path().clone())
 4352            });
 4353        })?;
 4354
 4355        // If the project transaction's edits are all contained within this editor, then
 4356        // avoid opening a new editor to display them.
 4357
 4358        if let Some((buffer, transaction)) = entries.first() {
 4359            if entries.len() == 1 {
 4360                let excerpt = this.update(&mut cx, |editor, cx| {
 4361                    editor
 4362                        .buffer()
 4363                        .read(cx)
 4364                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4365                })?;
 4366                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4367                    if excerpted_buffer == *buffer {
 4368                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4369                            let excerpt_range = excerpt_range.to_offset(buffer);
 4370                            buffer
 4371                                .edited_ranges_for_transaction::<usize>(transaction)
 4372                                .all(|range| {
 4373                                    excerpt_range.start <= range.start
 4374                                        && excerpt_range.end >= range.end
 4375                                })
 4376                        })?;
 4377
 4378                        if all_edits_within_excerpt {
 4379                            return Ok(());
 4380                        }
 4381                    }
 4382                }
 4383            }
 4384        } else {
 4385            return Ok(());
 4386        }
 4387
 4388        let mut ranges_to_highlight = Vec::new();
 4389        let excerpt_buffer = cx.new(|cx| {
 4390            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4391            for (buffer_handle, transaction) in &entries {
 4392                let buffer = buffer_handle.read(cx);
 4393                ranges_to_highlight.extend(
 4394                    multibuffer.push_excerpts_with_context_lines(
 4395                        buffer_handle.clone(),
 4396                        buffer
 4397                            .edited_ranges_for_transaction::<usize>(transaction)
 4398                            .collect(),
 4399                        DEFAULT_MULTIBUFFER_CONTEXT,
 4400                        cx,
 4401                    ),
 4402                );
 4403            }
 4404            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4405            multibuffer
 4406        })?;
 4407
 4408        workspace.update_in(&mut cx, |workspace, window, cx| {
 4409            let project = workspace.project().clone();
 4410            let editor = cx
 4411                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4412            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4413            editor.update(cx, |editor, cx| {
 4414                editor.highlight_background::<Self>(
 4415                    &ranges_to_highlight,
 4416                    |theme| theme.editor_highlighted_line_background,
 4417                    cx,
 4418                );
 4419            });
 4420        })?;
 4421
 4422        Ok(())
 4423    }
 4424
 4425    pub fn clear_code_action_providers(&mut self) {
 4426        self.code_action_providers.clear();
 4427        self.available_code_actions.take();
 4428    }
 4429
 4430    pub fn add_code_action_provider(
 4431        &mut self,
 4432        provider: Rc<dyn CodeActionProvider>,
 4433        window: &mut Window,
 4434        cx: &mut Context<Self>,
 4435    ) {
 4436        if self
 4437            .code_action_providers
 4438            .iter()
 4439            .any(|existing_provider| existing_provider.id() == provider.id())
 4440        {
 4441            return;
 4442        }
 4443
 4444        self.code_action_providers.push(provider);
 4445        self.refresh_code_actions(window, cx);
 4446    }
 4447
 4448    pub fn remove_code_action_provider(
 4449        &mut self,
 4450        id: Arc<str>,
 4451        window: &mut Window,
 4452        cx: &mut Context<Self>,
 4453    ) {
 4454        self.code_action_providers
 4455            .retain(|provider| provider.id() != id);
 4456        self.refresh_code_actions(window, cx);
 4457    }
 4458
 4459    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4460        let buffer = self.buffer.read(cx);
 4461        let newest_selection = self.selections.newest_anchor().clone();
 4462        if newest_selection.head().diff_base_anchor.is_some() {
 4463            return None;
 4464        }
 4465        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4466        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4467        if start_buffer != end_buffer {
 4468            return None;
 4469        }
 4470
 4471        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4472            cx.background_executor()
 4473                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4474                .await;
 4475
 4476            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4477                let providers = this.code_action_providers.clone();
 4478                let tasks = this
 4479                    .code_action_providers
 4480                    .iter()
 4481                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4482                    .collect::<Vec<_>>();
 4483                (providers, tasks)
 4484            })?;
 4485
 4486            let mut actions = Vec::new();
 4487            for (provider, provider_actions) in
 4488                providers.into_iter().zip(future::join_all(tasks).await)
 4489            {
 4490                if let Some(provider_actions) = provider_actions.log_err() {
 4491                    actions.extend(provider_actions.into_iter().map(|action| {
 4492                        AvailableCodeAction {
 4493                            excerpt_id: newest_selection.start.excerpt_id,
 4494                            action,
 4495                            provider: provider.clone(),
 4496                        }
 4497                    }));
 4498                }
 4499            }
 4500
 4501            this.update(&mut cx, |this, cx| {
 4502                this.available_code_actions = if actions.is_empty() {
 4503                    None
 4504                } else {
 4505                    Some((
 4506                        Location {
 4507                            buffer: start_buffer,
 4508                            range: start..end,
 4509                        },
 4510                        actions.into(),
 4511                    ))
 4512                };
 4513                cx.notify();
 4514            })
 4515        }));
 4516        None
 4517    }
 4518
 4519    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4520        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4521            self.show_git_blame_inline = false;
 4522
 4523            self.show_git_blame_inline_delay_task =
 4524                Some(cx.spawn_in(window, |this, mut cx| async move {
 4525                    cx.background_executor().timer(delay).await;
 4526
 4527                    this.update(&mut cx, |this, cx| {
 4528                        this.show_git_blame_inline = true;
 4529                        cx.notify();
 4530                    })
 4531                    .log_err();
 4532                }));
 4533        }
 4534    }
 4535
 4536    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4537        if self.pending_rename.is_some() {
 4538            return None;
 4539        }
 4540
 4541        let provider = self.semantics_provider.clone()?;
 4542        let buffer = self.buffer.read(cx);
 4543        let newest_selection = self.selections.newest_anchor().clone();
 4544        let cursor_position = newest_selection.head();
 4545        let (cursor_buffer, cursor_buffer_position) =
 4546            buffer.text_anchor_for_position(cursor_position, cx)?;
 4547        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4548        if cursor_buffer != tail_buffer {
 4549            return None;
 4550        }
 4551        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4552        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4553            cx.background_executor()
 4554                .timer(Duration::from_millis(debounce))
 4555                .await;
 4556
 4557            let highlights = if let Some(highlights) = cx
 4558                .update(|cx| {
 4559                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4560                })
 4561                .ok()
 4562                .flatten()
 4563            {
 4564                highlights.await.log_err()
 4565            } else {
 4566                None
 4567            };
 4568
 4569            if let Some(highlights) = highlights {
 4570                this.update(&mut cx, |this, cx| {
 4571                    if this.pending_rename.is_some() {
 4572                        return;
 4573                    }
 4574
 4575                    let buffer_id = cursor_position.buffer_id;
 4576                    let buffer = this.buffer.read(cx);
 4577                    if !buffer
 4578                        .text_anchor_for_position(cursor_position, cx)
 4579                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4580                    {
 4581                        return;
 4582                    }
 4583
 4584                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4585                    let mut write_ranges = Vec::new();
 4586                    let mut read_ranges = Vec::new();
 4587                    for highlight in highlights {
 4588                        for (excerpt_id, excerpt_range) in
 4589                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4590                        {
 4591                            let start = highlight
 4592                                .range
 4593                                .start
 4594                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4595                            let end = highlight
 4596                                .range
 4597                                .end
 4598                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4599                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4600                                continue;
 4601                            }
 4602
 4603                            let range = Anchor {
 4604                                buffer_id,
 4605                                excerpt_id,
 4606                                text_anchor: start,
 4607                                diff_base_anchor: None,
 4608                            }..Anchor {
 4609                                buffer_id,
 4610                                excerpt_id,
 4611                                text_anchor: end,
 4612                                diff_base_anchor: None,
 4613                            };
 4614                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4615                                write_ranges.push(range);
 4616                            } else {
 4617                                read_ranges.push(range);
 4618                            }
 4619                        }
 4620                    }
 4621
 4622                    this.highlight_background::<DocumentHighlightRead>(
 4623                        &read_ranges,
 4624                        |theme| theme.editor_document_highlight_read_background,
 4625                        cx,
 4626                    );
 4627                    this.highlight_background::<DocumentHighlightWrite>(
 4628                        &write_ranges,
 4629                        |theme| theme.editor_document_highlight_write_background,
 4630                        cx,
 4631                    );
 4632                    cx.notify();
 4633                })
 4634                .log_err();
 4635            }
 4636        }));
 4637        None
 4638    }
 4639
 4640    pub fn refresh_inline_completion(
 4641        &mut self,
 4642        debounce: bool,
 4643        user_requested: bool,
 4644        window: &mut Window,
 4645        cx: &mut Context<Self>,
 4646    ) -> Option<()> {
 4647        let provider = self.inline_completion_provider()?;
 4648        let cursor = self.selections.newest_anchor().head();
 4649        let (buffer, cursor_buffer_position) =
 4650            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4651
 4652        if !user_requested
 4653            && (!self.enable_inline_completions
 4654                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4655                || !self.is_focused(window)
 4656                || buffer.read(cx).is_empty())
 4657        {
 4658            self.discard_inline_completion(false, cx);
 4659            return None;
 4660        }
 4661
 4662        self.update_visible_inline_completion(window, cx);
 4663        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4664        Some(())
 4665    }
 4666
 4667    fn cycle_inline_completion(
 4668        &mut self,
 4669        direction: Direction,
 4670        window: &mut Window,
 4671        cx: &mut Context<Self>,
 4672    ) -> Option<()> {
 4673        let provider = self.inline_completion_provider()?;
 4674        let cursor = self.selections.newest_anchor().head();
 4675        let (buffer, cursor_buffer_position) =
 4676            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4677        if !self.enable_inline_completions
 4678            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4679        {
 4680            return None;
 4681        }
 4682
 4683        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4684        self.update_visible_inline_completion(window, cx);
 4685
 4686        Some(())
 4687    }
 4688
 4689    pub fn show_inline_completion(
 4690        &mut self,
 4691        _: &ShowInlineCompletion,
 4692        window: &mut Window,
 4693        cx: &mut Context<Self>,
 4694    ) {
 4695        if !self.has_active_inline_completion() {
 4696            self.refresh_inline_completion(false, true, window, cx);
 4697            return;
 4698        }
 4699
 4700        self.update_visible_inline_completion(window, cx);
 4701    }
 4702
 4703    pub fn display_cursor_names(
 4704        &mut self,
 4705        _: &DisplayCursorNames,
 4706        window: &mut Window,
 4707        cx: &mut Context<Self>,
 4708    ) {
 4709        self.show_cursor_names(window, cx);
 4710    }
 4711
 4712    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4713        self.show_cursor_names = true;
 4714        cx.notify();
 4715        cx.spawn_in(window, |this, mut cx| async move {
 4716            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4717            this.update(&mut cx, |this, cx| {
 4718                this.show_cursor_names = false;
 4719                cx.notify()
 4720            })
 4721            .ok()
 4722        })
 4723        .detach();
 4724    }
 4725
 4726    pub fn next_inline_completion(
 4727        &mut self,
 4728        _: &NextInlineCompletion,
 4729        window: &mut Window,
 4730        cx: &mut Context<Self>,
 4731    ) {
 4732        if self.has_active_inline_completion() {
 4733            self.cycle_inline_completion(Direction::Next, window, cx);
 4734        } else {
 4735            let is_copilot_disabled = self
 4736                .refresh_inline_completion(false, true, window, cx)
 4737                .is_none();
 4738            if is_copilot_disabled {
 4739                cx.propagate();
 4740            }
 4741        }
 4742    }
 4743
 4744    pub fn previous_inline_completion(
 4745        &mut self,
 4746        _: &PreviousInlineCompletion,
 4747        window: &mut Window,
 4748        cx: &mut Context<Self>,
 4749    ) {
 4750        if self.has_active_inline_completion() {
 4751            self.cycle_inline_completion(Direction::Prev, window, cx);
 4752        } else {
 4753            let is_copilot_disabled = self
 4754                .refresh_inline_completion(false, true, window, cx)
 4755                .is_none();
 4756            if is_copilot_disabled {
 4757                cx.propagate();
 4758            }
 4759        }
 4760    }
 4761
 4762    pub fn accept_inline_completion(
 4763        &mut self,
 4764        _: &AcceptInlineCompletion,
 4765        window: &mut Window,
 4766        cx: &mut Context<Self>,
 4767    ) {
 4768        let buffer = self.buffer.read(cx);
 4769        let snapshot = buffer.snapshot(cx);
 4770        let selection = self.selections.newest_adjusted(cx);
 4771        let cursor = selection.head();
 4772        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4773        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4774        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4775        {
 4776            if cursor.column < suggested_indent.len
 4777                && cursor.column <= current_indent.len
 4778                && current_indent.len <= suggested_indent.len
 4779            {
 4780                self.tab(&Default::default(), window, cx);
 4781                return;
 4782            }
 4783        }
 4784
 4785        if self.show_inline_completions_in_menu(cx) {
 4786            self.hide_context_menu(window, cx);
 4787        }
 4788
 4789        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4790            return;
 4791        };
 4792
 4793        self.report_inline_completion_event(true, cx);
 4794
 4795        match &active_inline_completion.completion {
 4796            InlineCompletion::Move { target, .. } => {
 4797                let target = *target;
 4798                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4799                    selections.select_anchor_ranges([target..target]);
 4800                });
 4801            }
 4802            InlineCompletion::Edit { edits, .. } => {
 4803                if let Some(provider) = self.inline_completion_provider() {
 4804                    provider.accept(cx);
 4805                }
 4806
 4807                let snapshot = self.buffer.read(cx).snapshot(cx);
 4808                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4809
 4810                self.buffer.update(cx, |buffer, cx| {
 4811                    buffer.edit(edits.iter().cloned(), None, cx)
 4812                });
 4813
 4814                self.change_selections(None, window, cx, |s| {
 4815                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4816                });
 4817
 4818                self.update_visible_inline_completion(window, cx);
 4819                if self.active_inline_completion.is_none() {
 4820                    self.refresh_inline_completion(true, true, window, cx);
 4821                }
 4822
 4823                cx.notify();
 4824            }
 4825        }
 4826    }
 4827
 4828    pub fn accept_partial_inline_completion(
 4829        &mut self,
 4830        _: &AcceptPartialInlineCompletion,
 4831        window: &mut Window,
 4832        cx: &mut Context<Self>,
 4833    ) {
 4834        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4835            return;
 4836        };
 4837        if self.selections.count() != 1 {
 4838            return;
 4839        }
 4840
 4841        self.report_inline_completion_event(true, cx);
 4842
 4843        match &active_inline_completion.completion {
 4844            InlineCompletion::Move { target, .. } => {
 4845                let target = *target;
 4846                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4847                    selections.select_anchor_ranges([target..target]);
 4848                });
 4849            }
 4850            InlineCompletion::Edit { edits, .. } => {
 4851                // Find an insertion that starts at the cursor position.
 4852                let snapshot = self.buffer.read(cx).snapshot(cx);
 4853                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4854                let insertion = edits.iter().find_map(|(range, text)| {
 4855                    let range = range.to_offset(&snapshot);
 4856                    if range.is_empty() && range.start == cursor_offset {
 4857                        Some(text)
 4858                    } else {
 4859                        None
 4860                    }
 4861                });
 4862
 4863                if let Some(text) = insertion {
 4864                    let mut partial_completion = text
 4865                        .chars()
 4866                        .by_ref()
 4867                        .take_while(|c| c.is_alphabetic())
 4868                        .collect::<String>();
 4869                    if partial_completion.is_empty() {
 4870                        partial_completion = text
 4871                            .chars()
 4872                            .by_ref()
 4873                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4874                            .collect::<String>();
 4875                    }
 4876
 4877                    cx.emit(EditorEvent::InputHandled {
 4878                        utf16_range_to_replace: None,
 4879                        text: partial_completion.clone().into(),
 4880                    });
 4881
 4882                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4883
 4884                    self.refresh_inline_completion(true, true, window, cx);
 4885                    cx.notify();
 4886                } else {
 4887                    self.accept_inline_completion(&Default::default(), window, cx);
 4888                }
 4889            }
 4890        }
 4891    }
 4892
 4893    fn discard_inline_completion(
 4894        &mut self,
 4895        should_report_inline_completion_event: bool,
 4896        cx: &mut Context<Self>,
 4897    ) -> bool {
 4898        if should_report_inline_completion_event {
 4899            self.report_inline_completion_event(false, cx);
 4900        }
 4901
 4902        if let Some(provider) = self.inline_completion_provider() {
 4903            provider.discard(cx);
 4904        }
 4905
 4906        self.take_active_inline_completion(cx)
 4907    }
 4908
 4909    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4910        let Some(provider) = self.inline_completion_provider() else {
 4911            return;
 4912        };
 4913
 4914        let Some((_, buffer, _)) = self
 4915            .buffer
 4916            .read(cx)
 4917            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4918        else {
 4919            return;
 4920        };
 4921
 4922        let extension = buffer
 4923            .read(cx)
 4924            .file()
 4925            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4926
 4927        let event_type = match accepted {
 4928            true => "Edit Prediction Accepted",
 4929            false => "Edit Prediction Discarded",
 4930        };
 4931        telemetry::event!(
 4932            event_type,
 4933            provider = provider.name(),
 4934            suggestion_accepted = accepted,
 4935            file_extension = extension,
 4936        );
 4937    }
 4938
 4939    pub fn has_active_inline_completion(&self) -> bool {
 4940        self.active_inline_completion.is_some()
 4941    }
 4942
 4943    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 4944        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 4945            return false;
 4946        };
 4947
 4948        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 4949        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4950        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 4951        true
 4952    }
 4953
 4954    pub fn is_previewing_inline_completion(&self) -> bool {
 4955        matches!(
 4956            self.context_menu.borrow().as_ref(),
 4957            Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
 4958        )
 4959    }
 4960
 4961    fn update_inline_completion_preview(
 4962        &mut self,
 4963        modifiers: &Modifiers,
 4964        window: &mut Window,
 4965        cx: &mut Context<Self>,
 4966    ) {
 4967        // Moves jump directly with a preview step
 4968
 4969        if self
 4970            .active_inline_completion
 4971            .as_ref()
 4972            .map_or(true, |c| c.is_move())
 4973        {
 4974            cx.notify();
 4975            return;
 4976        }
 4977
 4978        if !self.show_inline_completions_in_menu(cx) {
 4979            return;
 4980        }
 4981
 4982        let mut menu_borrow = self.context_menu.borrow_mut();
 4983
 4984        let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
 4985            return;
 4986        };
 4987
 4988        if completions_menu.is_empty()
 4989            || completions_menu.previewing_inline_completion == modifiers.alt
 4990        {
 4991            return;
 4992        }
 4993
 4994        completions_menu.set_previewing_inline_completion(modifiers.alt);
 4995        drop(menu_borrow);
 4996        self.update_visible_inline_completion(window, cx);
 4997    }
 4998
 4999    fn update_visible_inline_completion(
 5000        &mut self,
 5001        _window: &mut Window,
 5002        cx: &mut Context<Self>,
 5003    ) -> Option<()> {
 5004        let selection = self.selections.newest_anchor();
 5005        let cursor = selection.head();
 5006        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5007        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5008        let excerpt_id = cursor.excerpt_id;
 5009
 5010        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5011        let completions_menu_has_precedence = !show_in_menu
 5012            && (self.context_menu.borrow().is_some()
 5013                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5014        if completions_menu_has_precedence
 5015            || !offset_selection.is_empty()
 5016            || !self.enable_inline_completions
 5017            || self
 5018                .active_inline_completion
 5019                .as_ref()
 5020                .map_or(false, |completion| {
 5021                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5022                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5023                    !invalidation_range.contains(&offset_selection.head())
 5024                })
 5025        {
 5026            self.discard_inline_completion(false, cx);
 5027            return None;
 5028        }
 5029
 5030        self.take_active_inline_completion(cx);
 5031        let provider = self.inline_completion_provider()?;
 5032
 5033        let (buffer, cursor_buffer_position) =
 5034            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5035
 5036        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5037        let edits = inline_completion
 5038            .edits
 5039            .into_iter()
 5040            .flat_map(|(range, new_text)| {
 5041                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5042                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5043                Some((start..end, new_text))
 5044            })
 5045            .collect::<Vec<_>>();
 5046        if edits.is_empty() {
 5047            return None;
 5048        }
 5049
 5050        let first_edit_start = edits.first().unwrap().0.start;
 5051        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5052        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5053
 5054        let last_edit_end = edits.last().unwrap().0.end;
 5055        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5056        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5057
 5058        let cursor_row = cursor.to_point(&multibuffer).row;
 5059
 5060        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5061
 5062        let mut inlay_ids = Vec::new();
 5063        let invalidation_row_range;
 5064        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5065            Some(cursor_row..edit_end_row)
 5066        } else if cursor_row > edit_end_row {
 5067            Some(edit_start_row..cursor_row)
 5068        } else {
 5069            None
 5070        };
 5071        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5072            invalidation_row_range = move_invalidation_row_range;
 5073            let target = first_edit_start;
 5074            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5075            // TODO: Base this off of TreeSitter or word boundaries?
 5076            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5077                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5078                Bias::Left,
 5079            ));
 5080            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5081                Point::new(target_point.row, target_point.column + 20),
 5082                Bias::Right,
 5083            ));
 5084            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5085            InlineCompletion::Move {
 5086                target,
 5087                range_around_target,
 5088                snapshot,
 5089            }
 5090        } else {
 5091            if !show_in_menu || !self.has_active_completions_menu() {
 5092                if edits
 5093                    .iter()
 5094                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5095                {
 5096                    let mut inlays = Vec::new();
 5097                    for (range, new_text) in &edits {
 5098                        let inlay = Inlay::inline_completion(
 5099                            post_inc(&mut self.next_inlay_id),
 5100                            range.start,
 5101                            new_text.as_str(),
 5102                        );
 5103                        inlay_ids.push(inlay.id);
 5104                        inlays.push(inlay);
 5105                    }
 5106
 5107                    self.splice_inlays(&[], inlays, cx);
 5108                } else {
 5109                    let background_color = cx.theme().status().deleted_background;
 5110                    self.highlight_text::<InlineCompletionHighlight>(
 5111                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5112                        HighlightStyle {
 5113                            background_color: Some(background_color),
 5114                            ..Default::default()
 5115                        },
 5116                        cx,
 5117                    );
 5118                }
 5119            }
 5120
 5121            invalidation_row_range = edit_start_row..edit_end_row;
 5122
 5123            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5124                if provider.show_tab_accept_marker() {
 5125                    EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
 5126                } else {
 5127                    EditDisplayMode::Inline
 5128                }
 5129            } else {
 5130                EditDisplayMode::DiffPopover
 5131            };
 5132
 5133            InlineCompletion::Edit {
 5134                edits,
 5135                edit_preview: inline_completion.edit_preview,
 5136                display_mode,
 5137                snapshot,
 5138            }
 5139        };
 5140
 5141        let invalidation_range = multibuffer
 5142            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5143            ..multibuffer.anchor_after(Point::new(
 5144                invalidation_row_range.end,
 5145                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5146            ));
 5147
 5148        self.stale_inline_completion_in_menu = None;
 5149        self.active_inline_completion = Some(InlineCompletionState {
 5150            inlay_ids,
 5151            completion,
 5152            invalidation_range,
 5153        });
 5154
 5155        cx.notify();
 5156
 5157        Some(())
 5158    }
 5159
 5160    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5161        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5162    }
 5163
 5164    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5165        let by_provider = matches!(
 5166            self.menu_inline_completions_policy,
 5167            MenuInlineCompletionsPolicy::ByProvider
 5168        );
 5169
 5170        by_provider
 5171            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5172            && self
 5173                .inline_completion_provider()
 5174                .map_or(false, |provider| provider.show_completions_in_menu())
 5175    }
 5176
 5177    fn render_code_actions_indicator(
 5178        &self,
 5179        _style: &EditorStyle,
 5180        row: DisplayRow,
 5181        is_active: bool,
 5182        cx: &mut Context<Self>,
 5183    ) -> Option<IconButton> {
 5184        if self.available_code_actions.is_some() {
 5185            Some(
 5186                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5187                    .shape(ui::IconButtonShape::Square)
 5188                    .icon_size(IconSize::XSmall)
 5189                    .icon_color(Color::Muted)
 5190                    .toggle_state(is_active)
 5191                    .tooltip({
 5192                        let focus_handle = self.focus_handle.clone();
 5193                        move |window, cx| {
 5194                            Tooltip::for_action_in(
 5195                                "Toggle Code Actions",
 5196                                &ToggleCodeActions {
 5197                                    deployed_from_indicator: None,
 5198                                },
 5199                                &focus_handle,
 5200                                window,
 5201                                cx,
 5202                            )
 5203                        }
 5204                    })
 5205                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5206                        window.focus(&editor.focus_handle(cx));
 5207                        editor.toggle_code_actions(
 5208                            &ToggleCodeActions {
 5209                                deployed_from_indicator: Some(row),
 5210                            },
 5211                            window,
 5212                            cx,
 5213                        );
 5214                    })),
 5215            )
 5216        } else {
 5217            None
 5218        }
 5219    }
 5220
 5221    fn clear_tasks(&mut self) {
 5222        self.tasks.clear()
 5223    }
 5224
 5225    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5226        if self.tasks.insert(key, value).is_some() {
 5227            // This case should hopefully be rare, but just in case...
 5228            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5229        }
 5230    }
 5231
 5232    fn build_tasks_context(
 5233        project: &Entity<Project>,
 5234        buffer: &Entity<Buffer>,
 5235        buffer_row: u32,
 5236        tasks: &Arc<RunnableTasks>,
 5237        cx: &mut Context<Self>,
 5238    ) -> Task<Option<task::TaskContext>> {
 5239        let position = Point::new(buffer_row, tasks.column);
 5240        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5241        let location = Location {
 5242            buffer: buffer.clone(),
 5243            range: range_start..range_start,
 5244        };
 5245        // Fill in the environmental variables from the tree-sitter captures
 5246        let mut captured_task_variables = TaskVariables::default();
 5247        for (capture_name, value) in tasks.extra_variables.clone() {
 5248            captured_task_variables.insert(
 5249                task::VariableName::Custom(capture_name.into()),
 5250                value.clone(),
 5251            );
 5252        }
 5253        project.update(cx, |project, cx| {
 5254            project.task_store().update(cx, |task_store, cx| {
 5255                task_store.task_context_for_location(captured_task_variables, location, cx)
 5256            })
 5257        })
 5258    }
 5259
 5260    pub fn spawn_nearest_task(
 5261        &mut self,
 5262        action: &SpawnNearestTask,
 5263        window: &mut Window,
 5264        cx: &mut Context<Self>,
 5265    ) {
 5266        let Some((workspace, _)) = self.workspace.clone() else {
 5267            return;
 5268        };
 5269        let Some(project) = self.project.clone() else {
 5270            return;
 5271        };
 5272
 5273        // Try to find a closest, enclosing node using tree-sitter that has a
 5274        // task
 5275        let Some((buffer, buffer_row, tasks)) = self
 5276            .find_enclosing_node_task(cx)
 5277            // Or find the task that's closest in row-distance.
 5278            .or_else(|| self.find_closest_task(cx))
 5279        else {
 5280            return;
 5281        };
 5282
 5283        let reveal_strategy = action.reveal;
 5284        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5285        cx.spawn_in(window, |_, mut cx| async move {
 5286            let context = task_context.await?;
 5287            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5288
 5289            let resolved = resolved_task.resolved.as_mut()?;
 5290            resolved.reveal = reveal_strategy;
 5291
 5292            workspace
 5293                .update(&mut cx, |workspace, cx| {
 5294                    workspace::tasks::schedule_resolved_task(
 5295                        workspace,
 5296                        task_source_kind,
 5297                        resolved_task,
 5298                        false,
 5299                        cx,
 5300                    );
 5301                })
 5302                .ok()
 5303        })
 5304        .detach();
 5305    }
 5306
 5307    fn find_closest_task(
 5308        &mut self,
 5309        cx: &mut Context<Self>,
 5310    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5311        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5312
 5313        let ((buffer_id, row), tasks) = self
 5314            .tasks
 5315            .iter()
 5316            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5317
 5318        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5319        let tasks = Arc::new(tasks.to_owned());
 5320        Some((buffer, *row, tasks))
 5321    }
 5322
 5323    fn find_enclosing_node_task(
 5324        &mut self,
 5325        cx: &mut Context<Self>,
 5326    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5327        let snapshot = self.buffer.read(cx).snapshot(cx);
 5328        let offset = self.selections.newest::<usize>(cx).head();
 5329        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5330        let buffer_id = excerpt.buffer().remote_id();
 5331
 5332        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5333        let mut cursor = layer.node().walk();
 5334
 5335        while cursor.goto_first_child_for_byte(offset).is_some() {
 5336            if cursor.node().end_byte() == offset {
 5337                cursor.goto_next_sibling();
 5338            }
 5339        }
 5340
 5341        // Ascend to the smallest ancestor that contains the range and has a task.
 5342        loop {
 5343            let node = cursor.node();
 5344            let node_range = node.byte_range();
 5345            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5346
 5347            // Check if this node contains our offset
 5348            if node_range.start <= offset && node_range.end >= offset {
 5349                // If it contains offset, check for task
 5350                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5351                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5352                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5353                }
 5354            }
 5355
 5356            if !cursor.goto_parent() {
 5357                break;
 5358            }
 5359        }
 5360        None
 5361    }
 5362
 5363    fn render_run_indicator(
 5364        &self,
 5365        _style: &EditorStyle,
 5366        is_active: bool,
 5367        row: DisplayRow,
 5368        cx: &mut Context<Self>,
 5369    ) -> IconButton {
 5370        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5371            .shape(ui::IconButtonShape::Square)
 5372            .icon_size(IconSize::XSmall)
 5373            .icon_color(Color::Muted)
 5374            .toggle_state(is_active)
 5375            .on_click(cx.listener(move |editor, _e, window, cx| {
 5376                window.focus(&editor.focus_handle(cx));
 5377                editor.toggle_code_actions(
 5378                    &ToggleCodeActions {
 5379                        deployed_from_indicator: Some(row),
 5380                    },
 5381                    window,
 5382                    cx,
 5383                );
 5384            }))
 5385    }
 5386
 5387    pub fn context_menu_visible(&self) -> bool {
 5388        self.context_menu
 5389            .borrow()
 5390            .as_ref()
 5391            .map_or(false, |menu| menu.visible())
 5392    }
 5393
 5394    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5395        self.context_menu
 5396            .borrow()
 5397            .as_ref()
 5398            .map(|menu| menu.origin())
 5399    }
 5400
 5401    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5402        px(32.)
 5403    }
 5404
 5405    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5406        if self.read_only(cx) {
 5407            cx.theme().players().read_only()
 5408        } else {
 5409            self.style.as_ref().unwrap().local_player
 5410        }
 5411    }
 5412
 5413    #[allow(clippy::too_many_arguments)]
 5414    fn render_edit_prediction_cursor_popover(
 5415        &self,
 5416        min_width: Pixels,
 5417        max_width: Pixels,
 5418        cursor_point: Point,
 5419        start_row: DisplayRow,
 5420        line_layouts: &[LineWithInvisibles],
 5421        style: &EditorStyle,
 5422        accept_keystroke: &gpui::Keystroke,
 5423        window: &Window,
 5424        cx: &mut Context<Editor>,
 5425    ) -> Option<AnyElement> {
 5426        let provider = self.inline_completion_provider.as_ref()?;
 5427
 5428        if provider.provider.needs_terms_acceptance(cx) {
 5429            return Some(
 5430                h_flex()
 5431                    .h(self.edit_prediction_cursor_popover_height())
 5432                    .min_w(min_width)
 5433                    .flex_1()
 5434                    .px_2()
 5435                    .gap_3()
 5436                    .elevation_2(cx)
 5437                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5438                    .id("accept-terms")
 5439                    .cursor_pointer()
 5440                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5441                    .on_click(cx.listener(|this, _event, window, cx| {
 5442                        cx.stop_propagation();
 5443                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5444                        window.dispatch_action(
 5445                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5446                            cx,
 5447                        );
 5448                    }))
 5449                    .child(
 5450                        h_flex()
 5451                            .w_full()
 5452                            .gap_2()
 5453                            .child(Icon::new(IconName::ZedPredict))
 5454                            .child(Label::new("Accept Terms of Service"))
 5455                            .child(div().w_full())
 5456                            .child(Icon::new(IconName::ArrowUpRight))
 5457                            .into_any_element(),
 5458                    )
 5459                    .into_any(),
 5460            );
 5461        }
 5462
 5463        let is_refreshing = provider.provider.is_refreshing(cx);
 5464
 5465        fn pending_completion_container() -> Div {
 5466            h_flex()
 5467                .flex_1()
 5468                .gap_3()
 5469                .child(Icon::new(IconName::ZedPredict))
 5470        }
 5471
 5472        let completion = match &self.active_inline_completion {
 5473            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5474                completion,
 5475                cursor_point,
 5476                start_row,
 5477                line_layouts,
 5478                style,
 5479                cx,
 5480            )?,
 5481
 5482            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5483                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5484                    stale_completion,
 5485                    cursor_point,
 5486                    start_row,
 5487                    line_layouts,
 5488                    style,
 5489                    cx,
 5490                )?,
 5491
 5492                None => {
 5493                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5494                }
 5495            },
 5496
 5497            None => pending_completion_container().child(Label::new("No Prediction")),
 5498        };
 5499
 5500        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5501        let completion = completion.font(buffer_font.clone());
 5502
 5503        let completion = if is_refreshing {
 5504            completion
 5505                .with_animation(
 5506                    "loading-completion",
 5507                    Animation::new(Duration::from_secs(2))
 5508                        .repeat()
 5509                        .with_easing(pulsating_between(0.4, 0.8)),
 5510                    |label, delta| label.opacity(delta),
 5511                )
 5512                .into_any_element()
 5513        } else {
 5514            completion.into_any_element()
 5515        };
 5516
 5517        let has_completion = self.active_inline_completion.is_some();
 5518
 5519        let is_move = self
 5520            .active_inline_completion
 5521            .as_ref()
 5522            .map_or(false, |c| c.is_move());
 5523
 5524        Some(
 5525            h_flex()
 5526                .h(self.edit_prediction_cursor_popover_height())
 5527                .min_w(min_width)
 5528                .max_w(max_width)
 5529                .flex_1()
 5530                .px_2()
 5531                .gap_3()
 5532                .elevation_2(cx)
 5533                .child(completion)
 5534                .child(
 5535                    h_flex()
 5536                        .border_l_1()
 5537                        .border_color(cx.theme().colors().border_variant)
 5538                        .pl_2()
 5539                        .child(
 5540                            h_flex()
 5541                                .font(buffer_font.clone())
 5542                                .p_1()
 5543                                .rounded_sm()
 5544                                .children(ui::render_modifiers(
 5545                                    &accept_keystroke.modifiers,
 5546                                    PlatformStyle::platform(),
 5547                                    if window.modifiers() == accept_keystroke.modifiers {
 5548                                        Some(Color::Accent)
 5549                                    } else {
 5550                                        None
 5551                                    },
 5552                                    !is_move,
 5553                                )),
 5554                        )
 5555                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5556                        .child(if is_move {
 5557                            div()
 5558                                .child(ui::Key::new(&accept_keystroke.key, None))
 5559                                .font(buffer_font.clone())
 5560                                .into_any()
 5561                        } else {
 5562                            Label::new("Preview").color(Color::Muted).into_any_element()
 5563                        }),
 5564                )
 5565                .into_any(),
 5566        )
 5567    }
 5568
 5569    fn render_edit_prediction_cursor_popover_preview(
 5570        &self,
 5571        completion: &InlineCompletionState,
 5572        cursor_point: Point,
 5573        start_row: DisplayRow,
 5574        line_layouts: &[LineWithInvisibles],
 5575        style: &EditorStyle,
 5576        cx: &mut Context<Editor>,
 5577    ) -> Option<Div> {
 5578        use text::ToPoint as _;
 5579
 5580        fn render_relative_row_jump(
 5581            prefix: impl Into<String>,
 5582            current_row: u32,
 5583            target_row: u32,
 5584        ) -> Div {
 5585            let (row_diff, arrow) = if target_row < current_row {
 5586                (current_row - target_row, IconName::ArrowUp)
 5587            } else {
 5588                (target_row - current_row, IconName::ArrowDown)
 5589            };
 5590
 5591            h_flex()
 5592                .child(
 5593                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5594                        .color(Color::Muted)
 5595                        .size(LabelSize::Small),
 5596                )
 5597                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5598        }
 5599
 5600        match &completion.completion {
 5601            InlineCompletion::Edit {
 5602                edits,
 5603                edit_preview,
 5604                snapshot,
 5605                display_mode: _,
 5606            } => {
 5607                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5608
 5609                let highlighted_edits = crate::inline_completion_edit_text(
 5610                    &snapshot,
 5611                    &edits,
 5612                    edit_preview.as_ref()?,
 5613                    true,
 5614                    cx,
 5615                );
 5616
 5617                let len_total = highlighted_edits.text.len();
 5618                let first_line = &highlighted_edits.text
 5619                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5620                let first_line_len = first_line.len();
 5621
 5622                let first_highlight_start = highlighted_edits
 5623                    .highlights
 5624                    .first()
 5625                    .map_or(0, |(range, _)| range.start);
 5626                let drop_prefix_len = first_line
 5627                    .char_indices()
 5628                    .find(|(_, c)| !c.is_whitespace())
 5629                    .map_or(first_highlight_start, |(ix, _)| {
 5630                        ix.min(first_highlight_start)
 5631                    });
 5632
 5633                let preview_text = &first_line[drop_prefix_len..];
 5634                let preview_len = preview_text.len();
 5635                let highlights = highlighted_edits
 5636                    .highlights
 5637                    .into_iter()
 5638                    .take_until(|(range, _)| range.start > first_line_len)
 5639                    .map(|(range, style)| {
 5640                        (
 5641                            range.start - drop_prefix_len
 5642                                ..(range.end - drop_prefix_len).min(preview_len),
 5643                            style,
 5644                        )
 5645                    });
 5646
 5647                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5648                    .with_highlights(&style.text, highlights);
 5649
 5650                let preview = h_flex()
 5651                    .gap_1()
 5652                    .child(styled_text)
 5653                    .when(len_total > first_line_len, |parent| parent.child(""));
 5654
 5655                let left = if first_edit_row != cursor_point.row {
 5656                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5657                        .into_any_element()
 5658                } else {
 5659                    Icon::new(IconName::ZedPredict).into_any_element()
 5660                };
 5661
 5662                Some(h_flex().flex_1().gap_3().child(left).child(preview))
 5663            }
 5664
 5665            InlineCompletion::Move {
 5666                target,
 5667                range_around_target,
 5668                snapshot,
 5669            } => {
 5670                let highlighted_text = snapshot.highlighted_text_for_range(
 5671                    range_around_target.clone(),
 5672                    None,
 5673                    &style.syntax,
 5674                );
 5675                let cursor_color = self.current_user_player_color(cx).cursor;
 5676
 5677                let start_point = range_around_target.start.to_point(&snapshot);
 5678                let end_point = range_around_target.end.to_point(&snapshot);
 5679                let target_point = target.text_anchor.to_point(&snapshot);
 5680
 5681                let cursor_relative_position = line_layouts
 5682                    .get(start_point.row.saturating_sub(start_row.0) as usize)
 5683                    .map(|line| {
 5684                        let start_column_x = line.x_for_index(start_point.column as usize);
 5685                        let target_column_x = line.x_for_index(target_point.column as usize);
 5686                        target_column_x - start_column_x
 5687                    });
 5688
 5689                let fade_before = start_point.column > 0;
 5690                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5691
 5692                let background = cx.theme().colors().elevated_surface_background;
 5693
 5694                Some(
 5695                    h_flex()
 5696                        .gap_3()
 5697                        .flex_1()
 5698                        .child(render_relative_row_jump(
 5699                            "Jump ",
 5700                            cursor_point.row,
 5701                            target.text_anchor.to_point(&snapshot).row,
 5702                        ))
 5703                        .when(!highlighted_text.text.is_empty(), |parent| {
 5704                            parent.child(
 5705                                h_flex()
 5706                                    .relative()
 5707                                    .child(highlighted_text.to_styled_text(&style.text))
 5708                                    .when(fade_before, |parent| {
 5709                                        parent.child(
 5710                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5711                                                linear_gradient(
 5712                                                    90.,
 5713                                                    linear_color_stop(background, 0.),
 5714                                                    linear_color_stop(background.opacity(0.), 1.),
 5715                                                ),
 5716                                            ),
 5717                                        )
 5718                                    })
 5719                                    .when(fade_after, |parent| {
 5720                                        parent.child(
 5721                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5722                                                linear_gradient(
 5723                                                    -90.,
 5724                                                    linear_color_stop(background, 0.),
 5725                                                    linear_color_stop(background.opacity(0.), 1.),
 5726                                                ),
 5727                                            ),
 5728                                        )
 5729                                    })
 5730                                    .when_some(cursor_relative_position, |parent, position| {
 5731                                        parent.child(
 5732                                            div()
 5733                                                .w(px(2.))
 5734                                                .h_full()
 5735                                                .bg(cursor_color)
 5736                                                .absolute()
 5737                                                .top_0()
 5738                                                .left(position),
 5739                                        )
 5740                                    }),
 5741                            )
 5742                        }),
 5743                )
 5744            }
 5745        }
 5746    }
 5747
 5748    fn render_context_menu(
 5749        &self,
 5750        style: &EditorStyle,
 5751        max_height_in_lines: u32,
 5752        y_flipped: bool,
 5753        window: &mut Window,
 5754        cx: &mut Context<Editor>,
 5755    ) -> Option<AnyElement> {
 5756        let menu = self.context_menu.borrow();
 5757        let menu = menu.as_ref()?;
 5758        if !menu.visible() {
 5759            return None;
 5760        };
 5761        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5762    }
 5763
 5764    fn render_context_menu_aside(
 5765        &self,
 5766        style: &EditorStyle,
 5767        max_size: Size<Pixels>,
 5768        cx: &mut Context<Editor>,
 5769    ) -> Option<AnyElement> {
 5770        self.context_menu.borrow().as_ref().and_then(|menu| {
 5771            if menu.visible() {
 5772                menu.render_aside(
 5773                    style,
 5774                    max_size,
 5775                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5776                    cx,
 5777                )
 5778            } else {
 5779                None
 5780            }
 5781        })
 5782    }
 5783
 5784    fn hide_context_menu(
 5785        &mut self,
 5786        window: &mut Window,
 5787        cx: &mut Context<Self>,
 5788    ) -> Option<CodeContextMenu> {
 5789        cx.notify();
 5790        self.completion_tasks.clear();
 5791        let context_menu = self.context_menu.borrow_mut().take();
 5792        self.stale_inline_completion_in_menu.take();
 5793        if context_menu.is_some() {
 5794            self.update_visible_inline_completion(window, cx);
 5795        }
 5796        context_menu
 5797    }
 5798
 5799    fn show_snippet_choices(
 5800        &mut self,
 5801        choices: &Vec<String>,
 5802        selection: Range<Anchor>,
 5803        cx: &mut Context<Self>,
 5804    ) {
 5805        if selection.start.buffer_id.is_none() {
 5806            return;
 5807        }
 5808        let buffer_id = selection.start.buffer_id.unwrap();
 5809        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5810        let id = post_inc(&mut self.next_completion_id);
 5811
 5812        if let Some(buffer) = buffer {
 5813            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5814                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5815            ));
 5816        }
 5817    }
 5818
 5819    pub fn insert_snippet(
 5820        &mut self,
 5821        insertion_ranges: &[Range<usize>],
 5822        snippet: Snippet,
 5823        window: &mut Window,
 5824        cx: &mut Context<Self>,
 5825    ) -> Result<()> {
 5826        struct Tabstop<T> {
 5827            is_end_tabstop: bool,
 5828            ranges: Vec<Range<T>>,
 5829            choices: Option<Vec<String>>,
 5830        }
 5831
 5832        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5833            let snippet_text: Arc<str> = snippet.text.clone().into();
 5834            buffer.edit(
 5835                insertion_ranges
 5836                    .iter()
 5837                    .cloned()
 5838                    .map(|range| (range, snippet_text.clone())),
 5839                Some(AutoindentMode::EachLine),
 5840                cx,
 5841            );
 5842
 5843            let snapshot = &*buffer.read(cx);
 5844            let snippet = &snippet;
 5845            snippet
 5846                .tabstops
 5847                .iter()
 5848                .map(|tabstop| {
 5849                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5850                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5851                    });
 5852                    let mut tabstop_ranges = tabstop
 5853                        .ranges
 5854                        .iter()
 5855                        .flat_map(|tabstop_range| {
 5856                            let mut delta = 0_isize;
 5857                            insertion_ranges.iter().map(move |insertion_range| {
 5858                                let insertion_start = insertion_range.start as isize + delta;
 5859                                delta +=
 5860                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5861
 5862                                let start = ((insertion_start + tabstop_range.start) as usize)
 5863                                    .min(snapshot.len());
 5864                                let end = ((insertion_start + tabstop_range.end) as usize)
 5865                                    .min(snapshot.len());
 5866                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5867                            })
 5868                        })
 5869                        .collect::<Vec<_>>();
 5870                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5871
 5872                    Tabstop {
 5873                        is_end_tabstop,
 5874                        ranges: tabstop_ranges,
 5875                        choices: tabstop.choices.clone(),
 5876                    }
 5877                })
 5878                .collect::<Vec<_>>()
 5879        });
 5880        if let Some(tabstop) = tabstops.first() {
 5881            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5882                s.select_ranges(tabstop.ranges.iter().cloned());
 5883            });
 5884
 5885            if let Some(choices) = &tabstop.choices {
 5886                if let Some(selection) = tabstop.ranges.first() {
 5887                    self.show_snippet_choices(choices, selection.clone(), cx)
 5888                }
 5889            }
 5890
 5891            // If we're already at the last tabstop and it's at the end of the snippet,
 5892            // we're done, we don't need to keep the state around.
 5893            if !tabstop.is_end_tabstop {
 5894                let choices = tabstops
 5895                    .iter()
 5896                    .map(|tabstop| tabstop.choices.clone())
 5897                    .collect();
 5898
 5899                let ranges = tabstops
 5900                    .into_iter()
 5901                    .map(|tabstop| tabstop.ranges)
 5902                    .collect::<Vec<_>>();
 5903
 5904                self.snippet_stack.push(SnippetState {
 5905                    active_index: 0,
 5906                    ranges,
 5907                    choices,
 5908                });
 5909            }
 5910
 5911            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5912            if self.autoclose_regions.is_empty() {
 5913                let snapshot = self.buffer.read(cx).snapshot(cx);
 5914                for selection in &mut self.selections.all::<Point>(cx) {
 5915                    let selection_head = selection.head();
 5916                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5917                        continue;
 5918                    };
 5919
 5920                    let mut bracket_pair = None;
 5921                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5922                    let prev_chars = snapshot
 5923                        .reversed_chars_at(selection_head)
 5924                        .collect::<String>();
 5925                    for (pair, enabled) in scope.brackets() {
 5926                        if enabled
 5927                            && pair.close
 5928                            && prev_chars.starts_with(pair.start.as_str())
 5929                            && next_chars.starts_with(pair.end.as_str())
 5930                        {
 5931                            bracket_pair = Some(pair.clone());
 5932                            break;
 5933                        }
 5934                    }
 5935                    if let Some(pair) = bracket_pair {
 5936                        let start = snapshot.anchor_after(selection_head);
 5937                        let end = snapshot.anchor_after(selection_head);
 5938                        self.autoclose_regions.push(AutocloseRegion {
 5939                            selection_id: selection.id,
 5940                            range: start..end,
 5941                            pair,
 5942                        });
 5943                    }
 5944                }
 5945            }
 5946        }
 5947        Ok(())
 5948    }
 5949
 5950    pub fn move_to_next_snippet_tabstop(
 5951        &mut self,
 5952        window: &mut Window,
 5953        cx: &mut Context<Self>,
 5954    ) -> bool {
 5955        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5956    }
 5957
 5958    pub fn move_to_prev_snippet_tabstop(
 5959        &mut self,
 5960        window: &mut Window,
 5961        cx: &mut Context<Self>,
 5962    ) -> bool {
 5963        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5964    }
 5965
 5966    pub fn move_to_snippet_tabstop(
 5967        &mut self,
 5968        bias: Bias,
 5969        window: &mut Window,
 5970        cx: &mut Context<Self>,
 5971    ) -> bool {
 5972        if let Some(mut snippet) = self.snippet_stack.pop() {
 5973            match bias {
 5974                Bias::Left => {
 5975                    if snippet.active_index > 0 {
 5976                        snippet.active_index -= 1;
 5977                    } else {
 5978                        self.snippet_stack.push(snippet);
 5979                        return false;
 5980                    }
 5981                }
 5982                Bias::Right => {
 5983                    if snippet.active_index + 1 < snippet.ranges.len() {
 5984                        snippet.active_index += 1;
 5985                    } else {
 5986                        self.snippet_stack.push(snippet);
 5987                        return false;
 5988                    }
 5989                }
 5990            }
 5991            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5992                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5993                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5994                });
 5995
 5996                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5997                    if let Some(selection) = current_ranges.first() {
 5998                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5999                    }
 6000                }
 6001
 6002                // If snippet state is not at the last tabstop, push it back on the stack
 6003                if snippet.active_index + 1 < snippet.ranges.len() {
 6004                    self.snippet_stack.push(snippet);
 6005                }
 6006                return true;
 6007            }
 6008        }
 6009
 6010        false
 6011    }
 6012
 6013    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6014        self.transact(window, cx, |this, window, cx| {
 6015            this.select_all(&SelectAll, window, cx);
 6016            this.insert("", window, cx);
 6017        });
 6018    }
 6019
 6020    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6021        self.transact(window, cx, |this, window, cx| {
 6022            this.select_autoclose_pair(window, cx);
 6023            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6024            if !this.linked_edit_ranges.is_empty() {
 6025                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6026                let snapshot = this.buffer.read(cx).snapshot(cx);
 6027
 6028                for selection in selections.iter() {
 6029                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6030                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6031                    if selection_start.buffer_id != selection_end.buffer_id {
 6032                        continue;
 6033                    }
 6034                    if let Some(ranges) =
 6035                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6036                    {
 6037                        for (buffer, entries) in ranges {
 6038                            linked_ranges.entry(buffer).or_default().extend(entries);
 6039                        }
 6040                    }
 6041                }
 6042            }
 6043
 6044            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6045            if !this.selections.line_mode {
 6046                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6047                for selection in &mut selections {
 6048                    if selection.is_empty() {
 6049                        let old_head = selection.head();
 6050                        let mut new_head =
 6051                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6052                                .to_point(&display_map);
 6053                        if let Some((buffer, line_buffer_range)) = display_map
 6054                            .buffer_snapshot
 6055                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6056                        {
 6057                            let indent_size =
 6058                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6059                            let indent_len = match indent_size.kind {
 6060                                IndentKind::Space => {
 6061                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6062                                }
 6063                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6064                            };
 6065                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6066                                let indent_len = indent_len.get();
 6067                                new_head = cmp::min(
 6068                                    new_head,
 6069                                    MultiBufferPoint::new(
 6070                                        old_head.row,
 6071                                        ((old_head.column - 1) / indent_len) * indent_len,
 6072                                    ),
 6073                                );
 6074                            }
 6075                        }
 6076
 6077                        selection.set_head(new_head, SelectionGoal::None);
 6078                    }
 6079                }
 6080            }
 6081
 6082            this.signature_help_state.set_backspace_pressed(true);
 6083            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6084                s.select(selections)
 6085            });
 6086            this.insert("", window, cx);
 6087            let empty_str: Arc<str> = Arc::from("");
 6088            for (buffer, edits) in linked_ranges {
 6089                let snapshot = buffer.read(cx).snapshot();
 6090                use text::ToPoint as TP;
 6091
 6092                let edits = edits
 6093                    .into_iter()
 6094                    .map(|range| {
 6095                        let end_point = TP::to_point(&range.end, &snapshot);
 6096                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6097
 6098                        if end_point == start_point {
 6099                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6100                                .saturating_sub(1);
 6101                            start_point =
 6102                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6103                        };
 6104
 6105                        (start_point..end_point, empty_str.clone())
 6106                    })
 6107                    .sorted_by_key(|(range, _)| range.start)
 6108                    .collect::<Vec<_>>();
 6109                buffer.update(cx, |this, cx| {
 6110                    this.edit(edits, None, cx);
 6111                })
 6112            }
 6113            this.refresh_inline_completion(true, false, window, cx);
 6114            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6115        });
 6116    }
 6117
 6118    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6119        self.transact(window, cx, |this, window, cx| {
 6120            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6121                let line_mode = s.line_mode;
 6122                s.move_with(|map, selection| {
 6123                    if selection.is_empty() && !line_mode {
 6124                        let cursor = movement::right(map, selection.head());
 6125                        selection.end = cursor;
 6126                        selection.reversed = true;
 6127                        selection.goal = SelectionGoal::None;
 6128                    }
 6129                })
 6130            });
 6131            this.insert("", window, cx);
 6132            this.refresh_inline_completion(true, false, window, cx);
 6133        });
 6134    }
 6135
 6136    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6137        if self.move_to_prev_snippet_tabstop(window, cx) {
 6138            return;
 6139        }
 6140
 6141        self.outdent(&Outdent, window, cx);
 6142    }
 6143
 6144    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6145        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6146            return;
 6147        }
 6148
 6149        let mut selections = self.selections.all_adjusted(cx);
 6150        let buffer = self.buffer.read(cx);
 6151        let snapshot = buffer.snapshot(cx);
 6152        let rows_iter = selections.iter().map(|s| s.head().row);
 6153        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6154
 6155        let mut edits = Vec::new();
 6156        let mut prev_edited_row = 0;
 6157        let mut row_delta = 0;
 6158        for selection in &mut selections {
 6159            if selection.start.row != prev_edited_row {
 6160                row_delta = 0;
 6161            }
 6162            prev_edited_row = selection.end.row;
 6163
 6164            // If the selection is non-empty, then increase the indentation of the selected lines.
 6165            if !selection.is_empty() {
 6166                row_delta =
 6167                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6168                continue;
 6169            }
 6170
 6171            // If the selection is empty and the cursor is in the leading whitespace before the
 6172            // suggested indentation, then auto-indent the line.
 6173            let cursor = selection.head();
 6174            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6175            if let Some(suggested_indent) =
 6176                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6177            {
 6178                if cursor.column < suggested_indent.len
 6179                    && cursor.column <= current_indent.len
 6180                    && current_indent.len <= suggested_indent.len
 6181                {
 6182                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6183                    selection.end = selection.start;
 6184                    if row_delta == 0 {
 6185                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6186                            cursor.row,
 6187                            current_indent,
 6188                            suggested_indent,
 6189                        ));
 6190                        row_delta = suggested_indent.len - current_indent.len;
 6191                    }
 6192                    continue;
 6193                }
 6194            }
 6195
 6196            // Otherwise, insert a hard or soft tab.
 6197            let settings = buffer.settings_at(cursor, cx);
 6198            let tab_size = if settings.hard_tabs {
 6199                IndentSize::tab()
 6200            } else {
 6201                let tab_size = settings.tab_size.get();
 6202                let char_column = snapshot
 6203                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6204                    .flat_map(str::chars)
 6205                    .count()
 6206                    + row_delta as usize;
 6207                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6208                IndentSize::spaces(chars_to_next_tab_stop)
 6209            };
 6210            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6211            selection.end = selection.start;
 6212            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6213            row_delta += tab_size.len;
 6214        }
 6215
 6216        self.transact(window, cx, |this, window, cx| {
 6217            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6218            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6219                s.select(selections)
 6220            });
 6221            this.refresh_inline_completion(true, false, window, cx);
 6222        });
 6223    }
 6224
 6225    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6226        if self.read_only(cx) {
 6227            return;
 6228        }
 6229        let mut selections = self.selections.all::<Point>(cx);
 6230        let mut prev_edited_row = 0;
 6231        let mut row_delta = 0;
 6232        let mut edits = Vec::new();
 6233        let buffer = self.buffer.read(cx);
 6234        let snapshot = buffer.snapshot(cx);
 6235        for selection in &mut selections {
 6236            if selection.start.row != prev_edited_row {
 6237                row_delta = 0;
 6238            }
 6239            prev_edited_row = selection.end.row;
 6240
 6241            row_delta =
 6242                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6243        }
 6244
 6245        self.transact(window, cx, |this, window, cx| {
 6246            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6247            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6248                s.select(selections)
 6249            });
 6250        });
 6251    }
 6252
 6253    fn indent_selection(
 6254        buffer: &MultiBuffer,
 6255        snapshot: &MultiBufferSnapshot,
 6256        selection: &mut Selection<Point>,
 6257        edits: &mut Vec<(Range<Point>, String)>,
 6258        delta_for_start_row: u32,
 6259        cx: &App,
 6260    ) -> u32 {
 6261        let settings = buffer.settings_at(selection.start, cx);
 6262        let tab_size = settings.tab_size.get();
 6263        let indent_kind = if settings.hard_tabs {
 6264            IndentKind::Tab
 6265        } else {
 6266            IndentKind::Space
 6267        };
 6268        let mut start_row = selection.start.row;
 6269        let mut end_row = selection.end.row + 1;
 6270
 6271        // If a selection ends at the beginning of a line, don't indent
 6272        // that last line.
 6273        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6274            end_row -= 1;
 6275        }
 6276
 6277        // Avoid re-indenting a row that has already been indented by a
 6278        // previous selection, but still update this selection's column
 6279        // to reflect that indentation.
 6280        if delta_for_start_row > 0 {
 6281            start_row += 1;
 6282            selection.start.column += delta_for_start_row;
 6283            if selection.end.row == selection.start.row {
 6284                selection.end.column += delta_for_start_row;
 6285            }
 6286        }
 6287
 6288        let mut delta_for_end_row = 0;
 6289        let has_multiple_rows = start_row + 1 != end_row;
 6290        for row in start_row..end_row {
 6291            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6292            let indent_delta = match (current_indent.kind, indent_kind) {
 6293                (IndentKind::Space, IndentKind::Space) => {
 6294                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6295                    IndentSize::spaces(columns_to_next_tab_stop)
 6296                }
 6297                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6298                (_, IndentKind::Tab) => IndentSize::tab(),
 6299            };
 6300
 6301            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6302                0
 6303            } else {
 6304                selection.start.column
 6305            };
 6306            let row_start = Point::new(row, start);
 6307            edits.push((
 6308                row_start..row_start,
 6309                indent_delta.chars().collect::<String>(),
 6310            ));
 6311
 6312            // Update this selection's endpoints to reflect the indentation.
 6313            if row == selection.start.row {
 6314                selection.start.column += indent_delta.len;
 6315            }
 6316            if row == selection.end.row {
 6317                selection.end.column += indent_delta.len;
 6318                delta_for_end_row = indent_delta.len;
 6319            }
 6320        }
 6321
 6322        if selection.start.row == selection.end.row {
 6323            delta_for_start_row + delta_for_end_row
 6324        } else {
 6325            delta_for_end_row
 6326        }
 6327    }
 6328
 6329    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6330        if self.read_only(cx) {
 6331            return;
 6332        }
 6333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6334        let selections = self.selections.all::<Point>(cx);
 6335        let mut deletion_ranges = Vec::new();
 6336        let mut last_outdent = None;
 6337        {
 6338            let buffer = self.buffer.read(cx);
 6339            let snapshot = buffer.snapshot(cx);
 6340            for selection in &selections {
 6341                let settings = buffer.settings_at(selection.start, cx);
 6342                let tab_size = settings.tab_size.get();
 6343                let mut rows = selection.spanned_rows(false, &display_map);
 6344
 6345                // Avoid re-outdenting a row that has already been outdented by a
 6346                // previous selection.
 6347                if let Some(last_row) = last_outdent {
 6348                    if last_row == rows.start {
 6349                        rows.start = rows.start.next_row();
 6350                    }
 6351                }
 6352                let has_multiple_rows = rows.len() > 1;
 6353                for row in rows.iter_rows() {
 6354                    let indent_size = snapshot.indent_size_for_line(row);
 6355                    if indent_size.len > 0 {
 6356                        let deletion_len = match indent_size.kind {
 6357                            IndentKind::Space => {
 6358                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6359                                if columns_to_prev_tab_stop == 0 {
 6360                                    tab_size
 6361                                } else {
 6362                                    columns_to_prev_tab_stop
 6363                                }
 6364                            }
 6365                            IndentKind::Tab => 1,
 6366                        };
 6367                        let start = if has_multiple_rows
 6368                            || deletion_len > selection.start.column
 6369                            || indent_size.len < selection.start.column
 6370                        {
 6371                            0
 6372                        } else {
 6373                            selection.start.column - deletion_len
 6374                        };
 6375                        deletion_ranges.push(
 6376                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6377                        );
 6378                        last_outdent = Some(row);
 6379                    }
 6380                }
 6381            }
 6382        }
 6383
 6384        self.transact(window, cx, |this, window, cx| {
 6385            this.buffer.update(cx, |buffer, cx| {
 6386                let empty_str: Arc<str> = Arc::default();
 6387                buffer.edit(
 6388                    deletion_ranges
 6389                        .into_iter()
 6390                        .map(|range| (range, empty_str.clone())),
 6391                    None,
 6392                    cx,
 6393                );
 6394            });
 6395            let selections = this.selections.all::<usize>(cx);
 6396            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6397                s.select(selections)
 6398            });
 6399        });
 6400    }
 6401
 6402    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6403        if self.read_only(cx) {
 6404            return;
 6405        }
 6406        let selections = self
 6407            .selections
 6408            .all::<usize>(cx)
 6409            .into_iter()
 6410            .map(|s| s.range());
 6411
 6412        self.transact(window, cx, |this, window, cx| {
 6413            this.buffer.update(cx, |buffer, cx| {
 6414                buffer.autoindent_ranges(selections, cx);
 6415            });
 6416            let selections = this.selections.all::<usize>(cx);
 6417            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6418                s.select(selections)
 6419            });
 6420        });
 6421    }
 6422
 6423    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6424        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6425        let selections = self.selections.all::<Point>(cx);
 6426
 6427        let mut new_cursors = Vec::new();
 6428        let mut edit_ranges = Vec::new();
 6429        let mut selections = selections.iter().peekable();
 6430        while let Some(selection) = selections.next() {
 6431            let mut rows = selection.spanned_rows(false, &display_map);
 6432            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6433
 6434            // Accumulate contiguous regions of rows that we want to delete.
 6435            while let Some(next_selection) = selections.peek() {
 6436                let next_rows = next_selection.spanned_rows(false, &display_map);
 6437                if next_rows.start <= rows.end {
 6438                    rows.end = next_rows.end;
 6439                    selections.next().unwrap();
 6440                } else {
 6441                    break;
 6442                }
 6443            }
 6444
 6445            let buffer = &display_map.buffer_snapshot;
 6446            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6447            let edit_end;
 6448            let cursor_buffer_row;
 6449            if buffer.max_point().row >= rows.end.0 {
 6450                // If there's a line after the range, delete the \n from the end of the row range
 6451                // and position the cursor on the next line.
 6452                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6453                cursor_buffer_row = rows.end;
 6454            } else {
 6455                // If there isn't a line after the range, delete the \n from the line before the
 6456                // start of the row range and position the cursor there.
 6457                edit_start = edit_start.saturating_sub(1);
 6458                edit_end = buffer.len();
 6459                cursor_buffer_row = rows.start.previous_row();
 6460            }
 6461
 6462            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6463            *cursor.column_mut() =
 6464                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6465
 6466            new_cursors.push((
 6467                selection.id,
 6468                buffer.anchor_after(cursor.to_point(&display_map)),
 6469            ));
 6470            edit_ranges.push(edit_start..edit_end);
 6471        }
 6472
 6473        self.transact(window, cx, |this, window, cx| {
 6474            let buffer = this.buffer.update(cx, |buffer, cx| {
 6475                let empty_str: Arc<str> = Arc::default();
 6476                buffer.edit(
 6477                    edit_ranges
 6478                        .into_iter()
 6479                        .map(|range| (range, empty_str.clone())),
 6480                    None,
 6481                    cx,
 6482                );
 6483                buffer.snapshot(cx)
 6484            });
 6485            let new_selections = new_cursors
 6486                .into_iter()
 6487                .map(|(id, cursor)| {
 6488                    let cursor = cursor.to_point(&buffer);
 6489                    Selection {
 6490                        id,
 6491                        start: cursor,
 6492                        end: cursor,
 6493                        reversed: false,
 6494                        goal: SelectionGoal::None,
 6495                    }
 6496                })
 6497                .collect();
 6498
 6499            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6500                s.select(new_selections);
 6501            });
 6502        });
 6503    }
 6504
 6505    pub fn join_lines_impl(
 6506        &mut self,
 6507        insert_whitespace: bool,
 6508        window: &mut Window,
 6509        cx: &mut Context<Self>,
 6510    ) {
 6511        if self.read_only(cx) {
 6512            return;
 6513        }
 6514        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6515        for selection in self.selections.all::<Point>(cx) {
 6516            let start = MultiBufferRow(selection.start.row);
 6517            // Treat single line selections as if they include the next line. Otherwise this action
 6518            // would do nothing for single line selections individual cursors.
 6519            let end = if selection.start.row == selection.end.row {
 6520                MultiBufferRow(selection.start.row + 1)
 6521            } else {
 6522                MultiBufferRow(selection.end.row)
 6523            };
 6524
 6525            if let Some(last_row_range) = row_ranges.last_mut() {
 6526                if start <= last_row_range.end {
 6527                    last_row_range.end = end;
 6528                    continue;
 6529                }
 6530            }
 6531            row_ranges.push(start..end);
 6532        }
 6533
 6534        let snapshot = self.buffer.read(cx).snapshot(cx);
 6535        let mut cursor_positions = Vec::new();
 6536        for row_range in &row_ranges {
 6537            let anchor = snapshot.anchor_before(Point::new(
 6538                row_range.end.previous_row().0,
 6539                snapshot.line_len(row_range.end.previous_row()),
 6540            ));
 6541            cursor_positions.push(anchor..anchor);
 6542        }
 6543
 6544        self.transact(window, cx, |this, window, cx| {
 6545            for row_range in row_ranges.into_iter().rev() {
 6546                for row in row_range.iter_rows().rev() {
 6547                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6548                    let next_line_row = row.next_row();
 6549                    let indent = snapshot.indent_size_for_line(next_line_row);
 6550                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6551
 6552                    let replace =
 6553                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6554                            " "
 6555                        } else {
 6556                            ""
 6557                        };
 6558
 6559                    this.buffer.update(cx, |buffer, cx| {
 6560                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6561                    });
 6562                }
 6563            }
 6564
 6565            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6566                s.select_anchor_ranges(cursor_positions)
 6567            });
 6568        });
 6569    }
 6570
 6571    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6572        self.join_lines_impl(true, window, cx);
 6573    }
 6574
 6575    pub fn sort_lines_case_sensitive(
 6576        &mut self,
 6577        _: &SortLinesCaseSensitive,
 6578        window: &mut Window,
 6579        cx: &mut Context<Self>,
 6580    ) {
 6581        self.manipulate_lines(window, cx, |lines| lines.sort())
 6582    }
 6583
 6584    pub fn sort_lines_case_insensitive(
 6585        &mut self,
 6586        _: &SortLinesCaseInsensitive,
 6587        window: &mut Window,
 6588        cx: &mut Context<Self>,
 6589    ) {
 6590        self.manipulate_lines(window, cx, |lines| {
 6591            lines.sort_by_key(|line| line.to_lowercase())
 6592        })
 6593    }
 6594
 6595    pub fn unique_lines_case_insensitive(
 6596        &mut self,
 6597        _: &UniqueLinesCaseInsensitive,
 6598        window: &mut Window,
 6599        cx: &mut Context<Self>,
 6600    ) {
 6601        self.manipulate_lines(window, cx, |lines| {
 6602            let mut seen = HashSet::default();
 6603            lines.retain(|line| seen.insert(line.to_lowercase()));
 6604        })
 6605    }
 6606
 6607    pub fn unique_lines_case_sensitive(
 6608        &mut self,
 6609        _: &UniqueLinesCaseSensitive,
 6610        window: &mut Window,
 6611        cx: &mut Context<Self>,
 6612    ) {
 6613        self.manipulate_lines(window, cx, |lines| {
 6614            let mut seen = HashSet::default();
 6615            lines.retain(|line| seen.insert(*line));
 6616        })
 6617    }
 6618
 6619    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6620        let mut revert_changes = HashMap::default();
 6621        let snapshot = self.snapshot(window, cx);
 6622        for hunk in snapshot
 6623            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6624        {
 6625            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6626        }
 6627        if !revert_changes.is_empty() {
 6628            self.transact(window, cx, |editor, window, cx| {
 6629                editor.revert(revert_changes, window, cx);
 6630            });
 6631        }
 6632    }
 6633
 6634    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6635        let Some(project) = self.project.clone() else {
 6636            return;
 6637        };
 6638        self.reload(project, window, cx)
 6639            .detach_and_notify_err(window, cx);
 6640    }
 6641
 6642    pub fn revert_selected_hunks(
 6643        &mut self,
 6644        _: &RevertSelectedHunks,
 6645        window: &mut Window,
 6646        cx: &mut Context<Self>,
 6647    ) {
 6648        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6649        self.revert_hunks_in_ranges(selections, window, cx);
 6650    }
 6651
 6652    fn revert_hunks_in_ranges(
 6653        &mut self,
 6654        ranges: impl Iterator<Item = Range<Point>>,
 6655        window: &mut Window,
 6656        cx: &mut Context<Editor>,
 6657    ) {
 6658        let mut revert_changes = HashMap::default();
 6659        let snapshot = self.snapshot(window, cx);
 6660        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6661            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6662        }
 6663        if !revert_changes.is_empty() {
 6664            self.transact(window, cx, |editor, window, cx| {
 6665                editor.revert(revert_changes, window, cx);
 6666            });
 6667        }
 6668    }
 6669
 6670    pub fn open_active_item_in_terminal(
 6671        &mut self,
 6672        _: &OpenInTerminal,
 6673        window: &mut Window,
 6674        cx: &mut Context<Self>,
 6675    ) {
 6676        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6677            let project_path = buffer.read(cx).project_path(cx)?;
 6678            let project = self.project.as_ref()?.read(cx);
 6679            let entry = project.entry_for_path(&project_path, cx)?;
 6680            let parent = match &entry.canonical_path {
 6681                Some(canonical_path) => canonical_path.to_path_buf(),
 6682                None => project.absolute_path(&project_path, cx)?,
 6683            }
 6684            .parent()?
 6685            .to_path_buf();
 6686            Some(parent)
 6687        }) {
 6688            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6689        }
 6690    }
 6691
 6692    pub fn prepare_revert_change(
 6693        &self,
 6694        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6695        hunk: &MultiBufferDiffHunk,
 6696        cx: &mut App,
 6697    ) -> Option<()> {
 6698        let buffer = self.buffer.read(cx);
 6699        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6700        let buffer = buffer.buffer(hunk.buffer_id)?;
 6701        let buffer = buffer.read(cx);
 6702        let original_text = change_set
 6703            .read(cx)
 6704            .base_text
 6705            .as_ref()?
 6706            .as_rope()
 6707            .slice(hunk.diff_base_byte_range.clone());
 6708        let buffer_snapshot = buffer.snapshot();
 6709        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6710        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6711            probe
 6712                .0
 6713                .start
 6714                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6715                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6716        }) {
 6717            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6718            Some(())
 6719        } else {
 6720            None
 6721        }
 6722    }
 6723
 6724    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6725        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6726    }
 6727
 6728    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6729        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6730    }
 6731
 6732    fn manipulate_lines<Fn>(
 6733        &mut self,
 6734        window: &mut Window,
 6735        cx: &mut Context<Self>,
 6736        mut callback: Fn,
 6737    ) where
 6738        Fn: FnMut(&mut Vec<&str>),
 6739    {
 6740        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6741        let buffer = self.buffer.read(cx).snapshot(cx);
 6742
 6743        let mut edits = Vec::new();
 6744
 6745        let selections = self.selections.all::<Point>(cx);
 6746        let mut selections = selections.iter().peekable();
 6747        let mut contiguous_row_selections = Vec::new();
 6748        let mut new_selections = Vec::new();
 6749        let mut added_lines = 0;
 6750        let mut removed_lines = 0;
 6751
 6752        while let Some(selection) = selections.next() {
 6753            let (start_row, end_row) = consume_contiguous_rows(
 6754                &mut contiguous_row_selections,
 6755                selection,
 6756                &display_map,
 6757                &mut selections,
 6758            );
 6759
 6760            let start_point = Point::new(start_row.0, 0);
 6761            let end_point = Point::new(
 6762                end_row.previous_row().0,
 6763                buffer.line_len(end_row.previous_row()),
 6764            );
 6765            let text = buffer
 6766                .text_for_range(start_point..end_point)
 6767                .collect::<String>();
 6768
 6769            let mut lines = text.split('\n').collect_vec();
 6770
 6771            let lines_before = lines.len();
 6772            callback(&mut lines);
 6773            let lines_after = lines.len();
 6774
 6775            edits.push((start_point..end_point, lines.join("\n")));
 6776
 6777            // Selections must change based on added and removed line count
 6778            let start_row =
 6779                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6780            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6781            new_selections.push(Selection {
 6782                id: selection.id,
 6783                start: start_row,
 6784                end: end_row,
 6785                goal: SelectionGoal::None,
 6786                reversed: selection.reversed,
 6787            });
 6788
 6789            if lines_after > lines_before {
 6790                added_lines += lines_after - lines_before;
 6791            } else if lines_before > lines_after {
 6792                removed_lines += lines_before - lines_after;
 6793            }
 6794        }
 6795
 6796        self.transact(window, cx, |this, window, cx| {
 6797            let buffer = this.buffer.update(cx, |buffer, cx| {
 6798                buffer.edit(edits, None, cx);
 6799                buffer.snapshot(cx)
 6800            });
 6801
 6802            // Recalculate offsets on newly edited buffer
 6803            let new_selections = new_selections
 6804                .iter()
 6805                .map(|s| {
 6806                    let start_point = Point::new(s.start.0, 0);
 6807                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6808                    Selection {
 6809                        id: s.id,
 6810                        start: buffer.point_to_offset(start_point),
 6811                        end: buffer.point_to_offset(end_point),
 6812                        goal: s.goal,
 6813                        reversed: s.reversed,
 6814                    }
 6815                })
 6816                .collect();
 6817
 6818            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6819                s.select(new_selections);
 6820            });
 6821
 6822            this.request_autoscroll(Autoscroll::fit(), cx);
 6823        });
 6824    }
 6825
 6826    pub fn convert_to_upper_case(
 6827        &mut self,
 6828        _: &ConvertToUpperCase,
 6829        window: &mut Window,
 6830        cx: &mut Context<Self>,
 6831    ) {
 6832        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6833    }
 6834
 6835    pub fn convert_to_lower_case(
 6836        &mut self,
 6837        _: &ConvertToLowerCase,
 6838        window: &mut Window,
 6839        cx: &mut Context<Self>,
 6840    ) {
 6841        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6842    }
 6843
 6844    pub fn convert_to_title_case(
 6845        &mut self,
 6846        _: &ConvertToTitleCase,
 6847        window: &mut Window,
 6848        cx: &mut Context<Self>,
 6849    ) {
 6850        self.manipulate_text(window, cx, |text| {
 6851            text.split('\n')
 6852                .map(|line| line.to_case(Case::Title))
 6853                .join("\n")
 6854        })
 6855    }
 6856
 6857    pub fn convert_to_snake_case(
 6858        &mut self,
 6859        _: &ConvertToSnakeCase,
 6860        window: &mut Window,
 6861        cx: &mut Context<Self>,
 6862    ) {
 6863        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6864    }
 6865
 6866    pub fn convert_to_kebab_case(
 6867        &mut self,
 6868        _: &ConvertToKebabCase,
 6869        window: &mut Window,
 6870        cx: &mut Context<Self>,
 6871    ) {
 6872        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6873    }
 6874
 6875    pub fn convert_to_upper_camel_case(
 6876        &mut self,
 6877        _: &ConvertToUpperCamelCase,
 6878        window: &mut Window,
 6879        cx: &mut Context<Self>,
 6880    ) {
 6881        self.manipulate_text(window, cx, |text| {
 6882            text.split('\n')
 6883                .map(|line| line.to_case(Case::UpperCamel))
 6884                .join("\n")
 6885        })
 6886    }
 6887
 6888    pub fn convert_to_lower_camel_case(
 6889        &mut self,
 6890        _: &ConvertToLowerCamelCase,
 6891        window: &mut Window,
 6892        cx: &mut Context<Self>,
 6893    ) {
 6894        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6895    }
 6896
 6897    pub fn convert_to_opposite_case(
 6898        &mut self,
 6899        _: &ConvertToOppositeCase,
 6900        window: &mut Window,
 6901        cx: &mut Context<Self>,
 6902    ) {
 6903        self.manipulate_text(window, cx, |text| {
 6904            text.chars()
 6905                .fold(String::with_capacity(text.len()), |mut t, c| {
 6906                    if c.is_uppercase() {
 6907                        t.extend(c.to_lowercase());
 6908                    } else {
 6909                        t.extend(c.to_uppercase());
 6910                    }
 6911                    t
 6912                })
 6913        })
 6914    }
 6915
 6916    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6917    where
 6918        Fn: FnMut(&str) -> String,
 6919    {
 6920        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6921        let buffer = self.buffer.read(cx).snapshot(cx);
 6922
 6923        let mut new_selections = Vec::new();
 6924        let mut edits = Vec::new();
 6925        let mut selection_adjustment = 0i32;
 6926
 6927        for selection in self.selections.all::<usize>(cx) {
 6928            let selection_is_empty = selection.is_empty();
 6929
 6930            let (start, end) = if selection_is_empty {
 6931                let word_range = movement::surrounding_word(
 6932                    &display_map,
 6933                    selection.start.to_display_point(&display_map),
 6934                );
 6935                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6936                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6937                (start, end)
 6938            } else {
 6939                (selection.start, selection.end)
 6940            };
 6941
 6942            let text = buffer.text_for_range(start..end).collect::<String>();
 6943            let old_length = text.len() as i32;
 6944            let text = callback(&text);
 6945
 6946            new_selections.push(Selection {
 6947                start: (start as i32 - selection_adjustment) as usize,
 6948                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6949                goal: SelectionGoal::None,
 6950                ..selection
 6951            });
 6952
 6953            selection_adjustment += old_length - text.len() as i32;
 6954
 6955            edits.push((start..end, text));
 6956        }
 6957
 6958        self.transact(window, cx, |this, window, cx| {
 6959            this.buffer.update(cx, |buffer, cx| {
 6960                buffer.edit(edits, None, cx);
 6961            });
 6962
 6963            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6964                s.select(new_selections);
 6965            });
 6966
 6967            this.request_autoscroll(Autoscroll::fit(), cx);
 6968        });
 6969    }
 6970
 6971    pub fn duplicate(
 6972        &mut self,
 6973        upwards: bool,
 6974        whole_lines: bool,
 6975        window: &mut Window,
 6976        cx: &mut Context<Self>,
 6977    ) {
 6978        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6979        let buffer = &display_map.buffer_snapshot;
 6980        let selections = self.selections.all::<Point>(cx);
 6981
 6982        let mut edits = Vec::new();
 6983        let mut selections_iter = selections.iter().peekable();
 6984        while let Some(selection) = selections_iter.next() {
 6985            let mut rows = selection.spanned_rows(false, &display_map);
 6986            // duplicate line-wise
 6987            if whole_lines || selection.start == selection.end {
 6988                // Avoid duplicating the same lines twice.
 6989                while let Some(next_selection) = selections_iter.peek() {
 6990                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6991                    if next_rows.start < rows.end {
 6992                        rows.end = next_rows.end;
 6993                        selections_iter.next().unwrap();
 6994                    } else {
 6995                        break;
 6996                    }
 6997                }
 6998
 6999                // Copy the text from the selected row region and splice it either at the start
 7000                // or end of the region.
 7001                let start = Point::new(rows.start.0, 0);
 7002                let end = Point::new(
 7003                    rows.end.previous_row().0,
 7004                    buffer.line_len(rows.end.previous_row()),
 7005                );
 7006                let text = buffer
 7007                    .text_for_range(start..end)
 7008                    .chain(Some("\n"))
 7009                    .collect::<String>();
 7010                let insert_location = if upwards {
 7011                    Point::new(rows.end.0, 0)
 7012                } else {
 7013                    start
 7014                };
 7015                edits.push((insert_location..insert_location, text));
 7016            } else {
 7017                // duplicate character-wise
 7018                let start = selection.start;
 7019                let end = selection.end;
 7020                let text = buffer.text_for_range(start..end).collect::<String>();
 7021                edits.push((selection.end..selection.end, text));
 7022            }
 7023        }
 7024
 7025        self.transact(window, cx, |this, _, cx| {
 7026            this.buffer.update(cx, |buffer, cx| {
 7027                buffer.edit(edits, None, cx);
 7028            });
 7029
 7030            this.request_autoscroll(Autoscroll::fit(), cx);
 7031        });
 7032    }
 7033
 7034    pub fn duplicate_line_up(
 7035        &mut self,
 7036        _: &DuplicateLineUp,
 7037        window: &mut Window,
 7038        cx: &mut Context<Self>,
 7039    ) {
 7040        self.duplicate(true, true, window, cx);
 7041    }
 7042
 7043    pub fn duplicate_line_down(
 7044        &mut self,
 7045        _: &DuplicateLineDown,
 7046        window: &mut Window,
 7047        cx: &mut Context<Self>,
 7048    ) {
 7049        self.duplicate(false, true, window, cx);
 7050    }
 7051
 7052    pub fn duplicate_selection(
 7053        &mut self,
 7054        _: &DuplicateSelection,
 7055        window: &mut Window,
 7056        cx: &mut Context<Self>,
 7057    ) {
 7058        self.duplicate(false, false, window, cx);
 7059    }
 7060
 7061    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7063        let buffer = self.buffer.read(cx).snapshot(cx);
 7064
 7065        let mut edits = Vec::new();
 7066        let mut unfold_ranges = Vec::new();
 7067        let mut refold_creases = Vec::new();
 7068
 7069        let selections = self.selections.all::<Point>(cx);
 7070        let mut selections = selections.iter().peekable();
 7071        let mut contiguous_row_selections = Vec::new();
 7072        let mut new_selections = Vec::new();
 7073
 7074        while let Some(selection) = selections.next() {
 7075            // Find all the selections that span a contiguous row range
 7076            let (start_row, end_row) = consume_contiguous_rows(
 7077                &mut contiguous_row_selections,
 7078                selection,
 7079                &display_map,
 7080                &mut selections,
 7081            );
 7082
 7083            // Move the text spanned by the row range to be before the line preceding the row range
 7084            if start_row.0 > 0 {
 7085                let range_to_move = Point::new(
 7086                    start_row.previous_row().0,
 7087                    buffer.line_len(start_row.previous_row()),
 7088                )
 7089                    ..Point::new(
 7090                        end_row.previous_row().0,
 7091                        buffer.line_len(end_row.previous_row()),
 7092                    );
 7093                let insertion_point = display_map
 7094                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7095                    .0;
 7096
 7097                // Don't move lines across excerpts
 7098                if buffer
 7099                    .excerpt_containing(insertion_point..range_to_move.end)
 7100                    .is_some()
 7101                {
 7102                    let text = buffer
 7103                        .text_for_range(range_to_move.clone())
 7104                        .flat_map(|s| s.chars())
 7105                        .skip(1)
 7106                        .chain(['\n'])
 7107                        .collect::<String>();
 7108
 7109                    edits.push((
 7110                        buffer.anchor_after(range_to_move.start)
 7111                            ..buffer.anchor_before(range_to_move.end),
 7112                        String::new(),
 7113                    ));
 7114                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7115                    edits.push((insertion_anchor..insertion_anchor, text));
 7116
 7117                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7118
 7119                    // Move selections up
 7120                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7121                        |mut selection| {
 7122                            selection.start.row -= row_delta;
 7123                            selection.end.row -= row_delta;
 7124                            selection
 7125                        },
 7126                    ));
 7127
 7128                    // Move folds up
 7129                    unfold_ranges.push(range_to_move.clone());
 7130                    for fold in display_map.folds_in_range(
 7131                        buffer.anchor_before(range_to_move.start)
 7132                            ..buffer.anchor_after(range_to_move.end),
 7133                    ) {
 7134                        let mut start = fold.range.start.to_point(&buffer);
 7135                        let mut end = fold.range.end.to_point(&buffer);
 7136                        start.row -= row_delta;
 7137                        end.row -= row_delta;
 7138                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7139                    }
 7140                }
 7141            }
 7142
 7143            // If we didn't move line(s), preserve the existing selections
 7144            new_selections.append(&mut contiguous_row_selections);
 7145        }
 7146
 7147        self.transact(window, cx, |this, window, cx| {
 7148            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7149            this.buffer.update(cx, |buffer, cx| {
 7150                for (range, text) in edits {
 7151                    buffer.edit([(range, text)], None, cx);
 7152                }
 7153            });
 7154            this.fold_creases(refold_creases, true, window, cx);
 7155            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7156                s.select(new_selections);
 7157            })
 7158        });
 7159    }
 7160
 7161    pub fn move_line_down(
 7162        &mut self,
 7163        _: &MoveLineDown,
 7164        window: &mut Window,
 7165        cx: &mut Context<Self>,
 7166    ) {
 7167        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7168        let buffer = self.buffer.read(cx).snapshot(cx);
 7169
 7170        let mut edits = Vec::new();
 7171        let mut unfold_ranges = Vec::new();
 7172        let mut refold_creases = Vec::new();
 7173
 7174        let selections = self.selections.all::<Point>(cx);
 7175        let mut selections = selections.iter().peekable();
 7176        let mut contiguous_row_selections = Vec::new();
 7177        let mut new_selections = Vec::new();
 7178
 7179        while let Some(selection) = selections.next() {
 7180            // Find all the selections that span a contiguous row range
 7181            let (start_row, end_row) = consume_contiguous_rows(
 7182                &mut contiguous_row_selections,
 7183                selection,
 7184                &display_map,
 7185                &mut selections,
 7186            );
 7187
 7188            // Move the text spanned by the row range to be after the last line of the row range
 7189            if end_row.0 <= buffer.max_point().row {
 7190                let range_to_move =
 7191                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7192                let insertion_point = display_map
 7193                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7194                    .0;
 7195
 7196                // Don't move lines across excerpt boundaries
 7197                if buffer
 7198                    .excerpt_containing(range_to_move.start..insertion_point)
 7199                    .is_some()
 7200                {
 7201                    let mut text = String::from("\n");
 7202                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7203                    text.pop(); // Drop trailing newline
 7204                    edits.push((
 7205                        buffer.anchor_after(range_to_move.start)
 7206                            ..buffer.anchor_before(range_to_move.end),
 7207                        String::new(),
 7208                    ));
 7209                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7210                    edits.push((insertion_anchor..insertion_anchor, text));
 7211
 7212                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7213
 7214                    // Move selections down
 7215                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7216                        |mut selection| {
 7217                            selection.start.row += row_delta;
 7218                            selection.end.row += row_delta;
 7219                            selection
 7220                        },
 7221                    ));
 7222
 7223                    // Move folds down
 7224                    unfold_ranges.push(range_to_move.clone());
 7225                    for fold in display_map.folds_in_range(
 7226                        buffer.anchor_before(range_to_move.start)
 7227                            ..buffer.anchor_after(range_to_move.end),
 7228                    ) {
 7229                        let mut start = fold.range.start.to_point(&buffer);
 7230                        let mut end = fold.range.end.to_point(&buffer);
 7231                        start.row += row_delta;
 7232                        end.row += row_delta;
 7233                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7234                    }
 7235                }
 7236            }
 7237
 7238            // If we didn't move line(s), preserve the existing selections
 7239            new_selections.append(&mut contiguous_row_selections);
 7240        }
 7241
 7242        self.transact(window, cx, |this, window, cx| {
 7243            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7244            this.buffer.update(cx, |buffer, cx| {
 7245                for (range, text) in edits {
 7246                    buffer.edit([(range, text)], None, cx);
 7247                }
 7248            });
 7249            this.fold_creases(refold_creases, true, window, cx);
 7250            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7251                s.select(new_selections)
 7252            });
 7253        });
 7254    }
 7255
 7256    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7257        let text_layout_details = &self.text_layout_details(window);
 7258        self.transact(window, cx, |this, window, cx| {
 7259            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7260                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7261                let line_mode = s.line_mode;
 7262                s.move_with(|display_map, selection| {
 7263                    if !selection.is_empty() || line_mode {
 7264                        return;
 7265                    }
 7266
 7267                    let mut head = selection.head();
 7268                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7269                    if head.column() == display_map.line_len(head.row()) {
 7270                        transpose_offset = display_map
 7271                            .buffer_snapshot
 7272                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7273                    }
 7274
 7275                    if transpose_offset == 0 {
 7276                        return;
 7277                    }
 7278
 7279                    *head.column_mut() += 1;
 7280                    head = display_map.clip_point(head, Bias::Right);
 7281                    let goal = SelectionGoal::HorizontalPosition(
 7282                        display_map
 7283                            .x_for_display_point(head, text_layout_details)
 7284                            .into(),
 7285                    );
 7286                    selection.collapse_to(head, goal);
 7287
 7288                    let transpose_start = display_map
 7289                        .buffer_snapshot
 7290                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7291                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7292                        let transpose_end = display_map
 7293                            .buffer_snapshot
 7294                            .clip_offset(transpose_offset + 1, Bias::Right);
 7295                        if let Some(ch) =
 7296                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7297                        {
 7298                            edits.push((transpose_start..transpose_offset, String::new()));
 7299                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7300                        }
 7301                    }
 7302                });
 7303                edits
 7304            });
 7305            this.buffer
 7306                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7307            let selections = this.selections.all::<usize>(cx);
 7308            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7309                s.select(selections);
 7310            });
 7311        });
 7312    }
 7313
 7314    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7315        self.rewrap_impl(IsVimMode::No, cx)
 7316    }
 7317
 7318    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7319        let buffer = self.buffer.read(cx).snapshot(cx);
 7320        let selections = self.selections.all::<Point>(cx);
 7321        let mut selections = selections.iter().peekable();
 7322
 7323        let mut edits = Vec::new();
 7324        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7325
 7326        while let Some(selection) = selections.next() {
 7327            let mut start_row = selection.start.row;
 7328            let mut end_row = selection.end.row;
 7329
 7330            // Skip selections that overlap with a range that has already been rewrapped.
 7331            let selection_range = start_row..end_row;
 7332            if rewrapped_row_ranges
 7333                .iter()
 7334                .any(|range| range.overlaps(&selection_range))
 7335            {
 7336                continue;
 7337            }
 7338
 7339            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7340
 7341            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7342                match language_scope.language_name().as_ref() {
 7343                    "Markdown" | "Plain Text" => {
 7344                        should_rewrap = true;
 7345                    }
 7346                    _ => {}
 7347                }
 7348            }
 7349
 7350            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7351
 7352            // Since not all lines in the selection may be at the same indent
 7353            // level, choose the indent size that is the most common between all
 7354            // of the lines.
 7355            //
 7356            // If there is a tie, we use the deepest indent.
 7357            let (indent_size, indent_end) = {
 7358                let mut indent_size_occurrences = HashMap::default();
 7359                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7360
 7361                for row in start_row..=end_row {
 7362                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7363                    rows_by_indent_size.entry(indent).or_default().push(row);
 7364                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7365                }
 7366
 7367                let indent_size = indent_size_occurrences
 7368                    .into_iter()
 7369                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7370                    .map(|(indent, _)| indent)
 7371                    .unwrap_or_default();
 7372                let row = rows_by_indent_size[&indent_size][0];
 7373                let indent_end = Point::new(row, indent_size.len);
 7374
 7375                (indent_size, indent_end)
 7376            };
 7377
 7378            let mut line_prefix = indent_size.chars().collect::<String>();
 7379
 7380            if let Some(comment_prefix) =
 7381                buffer
 7382                    .language_scope_at(selection.head())
 7383                    .and_then(|language| {
 7384                        language
 7385                            .line_comment_prefixes()
 7386                            .iter()
 7387                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7388                            .cloned()
 7389                    })
 7390            {
 7391                line_prefix.push_str(&comment_prefix);
 7392                should_rewrap = true;
 7393            }
 7394
 7395            if !should_rewrap {
 7396                continue;
 7397            }
 7398
 7399            if selection.is_empty() {
 7400                'expand_upwards: while start_row > 0 {
 7401                    let prev_row = start_row - 1;
 7402                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7403                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7404                    {
 7405                        start_row = prev_row;
 7406                    } else {
 7407                        break 'expand_upwards;
 7408                    }
 7409                }
 7410
 7411                'expand_downwards: while end_row < buffer.max_point().row {
 7412                    let next_row = end_row + 1;
 7413                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7414                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7415                    {
 7416                        end_row = next_row;
 7417                    } else {
 7418                        break 'expand_downwards;
 7419                    }
 7420                }
 7421            }
 7422
 7423            let start = Point::new(start_row, 0);
 7424            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7425            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7426            let Some(lines_without_prefixes) = selection_text
 7427                .lines()
 7428                .map(|line| {
 7429                    line.strip_prefix(&line_prefix)
 7430                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7431                        .ok_or_else(|| {
 7432                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7433                        })
 7434                })
 7435                .collect::<Result<Vec<_>, _>>()
 7436                .log_err()
 7437            else {
 7438                continue;
 7439            };
 7440
 7441            let wrap_column = buffer
 7442                .settings_at(Point::new(start_row, 0), cx)
 7443                .preferred_line_length as usize;
 7444            let wrapped_text = wrap_with_prefix(
 7445                line_prefix,
 7446                lines_without_prefixes.join(" "),
 7447                wrap_column,
 7448                tab_size,
 7449            );
 7450
 7451            // TODO: should always use char-based diff while still supporting cursor behavior that
 7452            // matches vim.
 7453            let diff = match is_vim_mode {
 7454                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7455                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7456            };
 7457            let mut offset = start.to_offset(&buffer);
 7458            let mut moved_since_edit = true;
 7459
 7460            for change in diff.iter_all_changes() {
 7461                let value = change.value();
 7462                match change.tag() {
 7463                    ChangeTag::Equal => {
 7464                        offset += value.len();
 7465                        moved_since_edit = true;
 7466                    }
 7467                    ChangeTag::Delete => {
 7468                        let start = buffer.anchor_after(offset);
 7469                        let end = buffer.anchor_before(offset + value.len());
 7470
 7471                        if moved_since_edit {
 7472                            edits.push((start..end, String::new()));
 7473                        } else {
 7474                            edits.last_mut().unwrap().0.end = end;
 7475                        }
 7476
 7477                        offset += value.len();
 7478                        moved_since_edit = false;
 7479                    }
 7480                    ChangeTag::Insert => {
 7481                        if moved_since_edit {
 7482                            let anchor = buffer.anchor_after(offset);
 7483                            edits.push((anchor..anchor, value.to_string()));
 7484                        } else {
 7485                            edits.last_mut().unwrap().1.push_str(value);
 7486                        }
 7487
 7488                        moved_since_edit = false;
 7489                    }
 7490                }
 7491            }
 7492
 7493            rewrapped_row_ranges.push(start_row..=end_row);
 7494        }
 7495
 7496        self.buffer
 7497            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7498    }
 7499
 7500    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7501        let mut text = String::new();
 7502        let buffer = self.buffer.read(cx).snapshot(cx);
 7503        let mut selections = self.selections.all::<Point>(cx);
 7504        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7505        {
 7506            let max_point = buffer.max_point();
 7507            let mut is_first = true;
 7508            for selection in &mut selections {
 7509                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7510                if is_entire_line {
 7511                    selection.start = Point::new(selection.start.row, 0);
 7512                    if !selection.is_empty() && selection.end.column == 0 {
 7513                        selection.end = cmp::min(max_point, selection.end);
 7514                    } else {
 7515                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7516                    }
 7517                    selection.goal = SelectionGoal::None;
 7518                }
 7519                if is_first {
 7520                    is_first = false;
 7521                } else {
 7522                    text += "\n";
 7523                }
 7524                let mut len = 0;
 7525                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7526                    text.push_str(chunk);
 7527                    len += chunk.len();
 7528                }
 7529                clipboard_selections.push(ClipboardSelection {
 7530                    len,
 7531                    is_entire_line,
 7532                    first_line_indent: buffer
 7533                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7534                        .len,
 7535                });
 7536            }
 7537        }
 7538
 7539        self.transact(window, cx, |this, window, cx| {
 7540            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7541                s.select(selections);
 7542            });
 7543            this.insert("", window, cx);
 7544        });
 7545        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7546    }
 7547
 7548    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7549        let item = self.cut_common(window, cx);
 7550        cx.write_to_clipboard(item);
 7551    }
 7552
 7553    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7554        self.change_selections(None, window, cx, |s| {
 7555            s.move_with(|snapshot, sel| {
 7556                if sel.is_empty() {
 7557                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7558                }
 7559            });
 7560        });
 7561        let item = self.cut_common(window, cx);
 7562        cx.set_global(KillRing(item))
 7563    }
 7564
 7565    pub fn kill_ring_yank(
 7566        &mut self,
 7567        _: &KillRingYank,
 7568        window: &mut Window,
 7569        cx: &mut Context<Self>,
 7570    ) {
 7571        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7572            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7573                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7574            } else {
 7575                return;
 7576            }
 7577        } else {
 7578            return;
 7579        };
 7580        self.do_paste(&text, metadata, false, window, cx);
 7581    }
 7582
 7583    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7584        let selections = self.selections.all::<Point>(cx);
 7585        let buffer = self.buffer.read(cx).read(cx);
 7586        let mut text = String::new();
 7587
 7588        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7589        {
 7590            let max_point = buffer.max_point();
 7591            let mut is_first = true;
 7592            for selection in selections.iter() {
 7593                let mut start = selection.start;
 7594                let mut end = selection.end;
 7595                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7596                if is_entire_line {
 7597                    start = Point::new(start.row, 0);
 7598                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7599                }
 7600                if is_first {
 7601                    is_first = false;
 7602                } else {
 7603                    text += "\n";
 7604                }
 7605                let mut len = 0;
 7606                for chunk in buffer.text_for_range(start..end) {
 7607                    text.push_str(chunk);
 7608                    len += chunk.len();
 7609                }
 7610                clipboard_selections.push(ClipboardSelection {
 7611                    len,
 7612                    is_entire_line,
 7613                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7614                });
 7615            }
 7616        }
 7617
 7618        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7619            text,
 7620            clipboard_selections,
 7621        ));
 7622    }
 7623
 7624    pub fn do_paste(
 7625        &mut self,
 7626        text: &String,
 7627        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7628        handle_entire_lines: bool,
 7629        window: &mut Window,
 7630        cx: &mut Context<Self>,
 7631    ) {
 7632        if self.read_only(cx) {
 7633            return;
 7634        }
 7635
 7636        let clipboard_text = Cow::Borrowed(text);
 7637
 7638        self.transact(window, cx, |this, window, cx| {
 7639            if let Some(mut clipboard_selections) = clipboard_selections {
 7640                let old_selections = this.selections.all::<usize>(cx);
 7641                let all_selections_were_entire_line =
 7642                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7643                let first_selection_indent_column =
 7644                    clipboard_selections.first().map(|s| s.first_line_indent);
 7645                if clipboard_selections.len() != old_selections.len() {
 7646                    clipboard_selections.drain(..);
 7647                }
 7648                let cursor_offset = this.selections.last::<usize>(cx).head();
 7649                let mut auto_indent_on_paste = true;
 7650
 7651                this.buffer.update(cx, |buffer, cx| {
 7652                    let snapshot = buffer.read(cx);
 7653                    auto_indent_on_paste =
 7654                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7655
 7656                    let mut start_offset = 0;
 7657                    let mut edits = Vec::new();
 7658                    let mut original_indent_columns = Vec::new();
 7659                    for (ix, selection) in old_selections.iter().enumerate() {
 7660                        let to_insert;
 7661                        let entire_line;
 7662                        let original_indent_column;
 7663                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7664                            let end_offset = start_offset + clipboard_selection.len;
 7665                            to_insert = &clipboard_text[start_offset..end_offset];
 7666                            entire_line = clipboard_selection.is_entire_line;
 7667                            start_offset = end_offset + 1;
 7668                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7669                        } else {
 7670                            to_insert = clipboard_text.as_str();
 7671                            entire_line = all_selections_were_entire_line;
 7672                            original_indent_column = first_selection_indent_column
 7673                        }
 7674
 7675                        // If the corresponding selection was empty when this slice of the
 7676                        // clipboard text was written, then the entire line containing the
 7677                        // selection was copied. If this selection is also currently empty,
 7678                        // then paste the line before the current line of the buffer.
 7679                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7680                            let column = selection.start.to_point(&snapshot).column as usize;
 7681                            let line_start = selection.start - column;
 7682                            line_start..line_start
 7683                        } else {
 7684                            selection.range()
 7685                        };
 7686
 7687                        edits.push((range, to_insert));
 7688                        original_indent_columns.extend(original_indent_column);
 7689                    }
 7690                    drop(snapshot);
 7691
 7692                    buffer.edit(
 7693                        edits,
 7694                        if auto_indent_on_paste {
 7695                            Some(AutoindentMode::Block {
 7696                                original_indent_columns,
 7697                            })
 7698                        } else {
 7699                            None
 7700                        },
 7701                        cx,
 7702                    );
 7703                });
 7704
 7705                let selections = this.selections.all::<usize>(cx);
 7706                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7707                    s.select(selections)
 7708                });
 7709            } else {
 7710                this.insert(&clipboard_text, window, cx);
 7711            }
 7712        });
 7713    }
 7714
 7715    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7716        if let Some(item) = cx.read_from_clipboard() {
 7717            let entries = item.entries();
 7718
 7719            match entries.first() {
 7720                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7721                // of all the pasted entries.
 7722                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7723                    .do_paste(
 7724                        clipboard_string.text(),
 7725                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7726                        true,
 7727                        window,
 7728                        cx,
 7729                    ),
 7730                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7731            }
 7732        }
 7733    }
 7734
 7735    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7736        if self.read_only(cx) {
 7737            return;
 7738        }
 7739
 7740        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7741            if let Some((selections, _)) =
 7742                self.selection_history.transaction(transaction_id).cloned()
 7743            {
 7744                self.change_selections(None, window, cx, |s| {
 7745                    s.select_anchors(selections.to_vec());
 7746                });
 7747            }
 7748            self.request_autoscroll(Autoscroll::fit(), cx);
 7749            self.unmark_text(window, cx);
 7750            self.refresh_inline_completion(true, false, window, cx);
 7751            cx.emit(EditorEvent::Edited { transaction_id });
 7752            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7753        }
 7754    }
 7755
 7756    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7757        if self.read_only(cx) {
 7758            return;
 7759        }
 7760
 7761        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7762            if let Some((_, Some(selections))) =
 7763                self.selection_history.transaction(transaction_id).cloned()
 7764            {
 7765                self.change_selections(None, window, cx, |s| {
 7766                    s.select_anchors(selections.to_vec());
 7767                });
 7768            }
 7769            self.request_autoscroll(Autoscroll::fit(), cx);
 7770            self.unmark_text(window, cx);
 7771            self.refresh_inline_completion(true, false, window, cx);
 7772            cx.emit(EditorEvent::Edited { transaction_id });
 7773        }
 7774    }
 7775
 7776    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7777        self.buffer
 7778            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7779    }
 7780
 7781    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7782        self.buffer
 7783            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7784    }
 7785
 7786    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7787        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7788            let line_mode = s.line_mode;
 7789            s.move_with(|map, selection| {
 7790                let cursor = if selection.is_empty() && !line_mode {
 7791                    movement::left(map, selection.start)
 7792                } else {
 7793                    selection.start
 7794                };
 7795                selection.collapse_to(cursor, SelectionGoal::None);
 7796            });
 7797        })
 7798    }
 7799
 7800    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7801        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7802            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7803        })
 7804    }
 7805
 7806    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7807        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7808            let line_mode = s.line_mode;
 7809            s.move_with(|map, selection| {
 7810                let cursor = if selection.is_empty() && !line_mode {
 7811                    movement::right(map, selection.end)
 7812                } else {
 7813                    selection.end
 7814                };
 7815                selection.collapse_to(cursor, SelectionGoal::None)
 7816            });
 7817        })
 7818    }
 7819
 7820    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7822            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7823        })
 7824    }
 7825
 7826    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7827        if self.take_rename(true, window, cx).is_some() {
 7828            return;
 7829        }
 7830
 7831        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7832            cx.propagate();
 7833            return;
 7834        }
 7835
 7836        let text_layout_details = &self.text_layout_details(window);
 7837        let selection_count = self.selections.count();
 7838        let first_selection = self.selections.first_anchor();
 7839
 7840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7841            let line_mode = s.line_mode;
 7842            s.move_with(|map, selection| {
 7843                if !selection.is_empty() && !line_mode {
 7844                    selection.goal = SelectionGoal::None;
 7845                }
 7846                let (cursor, goal) = movement::up(
 7847                    map,
 7848                    selection.start,
 7849                    selection.goal,
 7850                    false,
 7851                    text_layout_details,
 7852                );
 7853                selection.collapse_to(cursor, goal);
 7854            });
 7855        });
 7856
 7857        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7858        {
 7859            cx.propagate();
 7860        }
 7861    }
 7862
 7863    pub fn move_up_by_lines(
 7864        &mut self,
 7865        action: &MoveUpByLines,
 7866        window: &mut Window,
 7867        cx: &mut Context<Self>,
 7868    ) {
 7869        if self.take_rename(true, window, cx).is_some() {
 7870            return;
 7871        }
 7872
 7873        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7874            cx.propagate();
 7875            return;
 7876        }
 7877
 7878        let text_layout_details = &self.text_layout_details(window);
 7879
 7880        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7881            let line_mode = s.line_mode;
 7882            s.move_with(|map, selection| {
 7883                if !selection.is_empty() && !line_mode {
 7884                    selection.goal = SelectionGoal::None;
 7885                }
 7886                let (cursor, goal) = movement::up_by_rows(
 7887                    map,
 7888                    selection.start,
 7889                    action.lines,
 7890                    selection.goal,
 7891                    false,
 7892                    text_layout_details,
 7893                );
 7894                selection.collapse_to(cursor, goal);
 7895            });
 7896        })
 7897    }
 7898
 7899    pub fn move_down_by_lines(
 7900        &mut self,
 7901        action: &MoveDownByLines,
 7902        window: &mut Window,
 7903        cx: &mut Context<Self>,
 7904    ) {
 7905        if self.take_rename(true, window, cx).is_some() {
 7906            return;
 7907        }
 7908
 7909        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7910            cx.propagate();
 7911            return;
 7912        }
 7913
 7914        let text_layout_details = &self.text_layout_details(window);
 7915
 7916        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7917            let line_mode = s.line_mode;
 7918            s.move_with(|map, selection| {
 7919                if !selection.is_empty() && !line_mode {
 7920                    selection.goal = SelectionGoal::None;
 7921                }
 7922                let (cursor, goal) = movement::down_by_rows(
 7923                    map,
 7924                    selection.start,
 7925                    action.lines,
 7926                    selection.goal,
 7927                    false,
 7928                    text_layout_details,
 7929                );
 7930                selection.collapse_to(cursor, goal);
 7931            });
 7932        })
 7933    }
 7934
 7935    pub fn select_down_by_lines(
 7936        &mut self,
 7937        action: &SelectDownByLines,
 7938        window: &mut Window,
 7939        cx: &mut Context<Self>,
 7940    ) {
 7941        let text_layout_details = &self.text_layout_details(window);
 7942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7943            s.move_heads_with(|map, head, goal| {
 7944                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7945            })
 7946        })
 7947    }
 7948
 7949    pub fn select_up_by_lines(
 7950        &mut self,
 7951        action: &SelectUpByLines,
 7952        window: &mut Window,
 7953        cx: &mut Context<Self>,
 7954    ) {
 7955        let text_layout_details = &self.text_layout_details(window);
 7956        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7957            s.move_heads_with(|map, head, goal| {
 7958                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7959            })
 7960        })
 7961    }
 7962
 7963    pub fn select_page_up(
 7964        &mut self,
 7965        _: &SelectPageUp,
 7966        window: &mut Window,
 7967        cx: &mut Context<Self>,
 7968    ) {
 7969        let Some(row_count) = self.visible_row_count() else {
 7970            return;
 7971        };
 7972
 7973        let text_layout_details = &self.text_layout_details(window);
 7974
 7975        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7976            s.move_heads_with(|map, head, goal| {
 7977                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7978            })
 7979        })
 7980    }
 7981
 7982    pub fn move_page_up(
 7983        &mut self,
 7984        action: &MovePageUp,
 7985        window: &mut Window,
 7986        cx: &mut Context<Self>,
 7987    ) {
 7988        if self.take_rename(true, window, cx).is_some() {
 7989            return;
 7990        }
 7991
 7992        if self
 7993            .context_menu
 7994            .borrow_mut()
 7995            .as_mut()
 7996            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7997            .unwrap_or(false)
 7998        {
 7999            return;
 8000        }
 8001
 8002        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8003            cx.propagate();
 8004            return;
 8005        }
 8006
 8007        let Some(row_count) = self.visible_row_count() else {
 8008            return;
 8009        };
 8010
 8011        let autoscroll = if action.center_cursor {
 8012            Autoscroll::center()
 8013        } else {
 8014            Autoscroll::fit()
 8015        };
 8016
 8017        let text_layout_details = &self.text_layout_details(window);
 8018
 8019        self.change_selections(Some(autoscroll), window, cx, |s| {
 8020            let line_mode = s.line_mode;
 8021            s.move_with(|map, selection| {
 8022                if !selection.is_empty() && !line_mode {
 8023                    selection.goal = SelectionGoal::None;
 8024                }
 8025                let (cursor, goal) = movement::up_by_rows(
 8026                    map,
 8027                    selection.end,
 8028                    row_count,
 8029                    selection.goal,
 8030                    false,
 8031                    text_layout_details,
 8032                );
 8033                selection.collapse_to(cursor, goal);
 8034            });
 8035        });
 8036    }
 8037
 8038    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8039        let text_layout_details = &self.text_layout_details(window);
 8040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8041            s.move_heads_with(|map, head, goal| {
 8042                movement::up(map, head, goal, false, text_layout_details)
 8043            })
 8044        })
 8045    }
 8046
 8047    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8048        self.take_rename(true, window, cx);
 8049
 8050        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8051            cx.propagate();
 8052            return;
 8053        }
 8054
 8055        let text_layout_details = &self.text_layout_details(window);
 8056        let selection_count = self.selections.count();
 8057        let first_selection = self.selections.first_anchor();
 8058
 8059        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8060            let line_mode = s.line_mode;
 8061            s.move_with(|map, selection| {
 8062                if !selection.is_empty() && !line_mode {
 8063                    selection.goal = SelectionGoal::None;
 8064                }
 8065                let (cursor, goal) = movement::down(
 8066                    map,
 8067                    selection.end,
 8068                    selection.goal,
 8069                    false,
 8070                    text_layout_details,
 8071                );
 8072                selection.collapse_to(cursor, goal);
 8073            });
 8074        });
 8075
 8076        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8077        {
 8078            cx.propagate();
 8079        }
 8080    }
 8081
 8082    pub fn select_page_down(
 8083        &mut self,
 8084        _: &SelectPageDown,
 8085        window: &mut Window,
 8086        cx: &mut Context<Self>,
 8087    ) {
 8088        let Some(row_count) = self.visible_row_count() else {
 8089            return;
 8090        };
 8091
 8092        let text_layout_details = &self.text_layout_details(window);
 8093
 8094        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8095            s.move_heads_with(|map, head, goal| {
 8096                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8097            })
 8098        })
 8099    }
 8100
 8101    pub fn move_page_down(
 8102        &mut self,
 8103        action: &MovePageDown,
 8104        window: &mut Window,
 8105        cx: &mut Context<Self>,
 8106    ) {
 8107        if self.take_rename(true, window, cx).is_some() {
 8108            return;
 8109        }
 8110
 8111        if self
 8112            .context_menu
 8113            .borrow_mut()
 8114            .as_mut()
 8115            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8116            .unwrap_or(false)
 8117        {
 8118            return;
 8119        }
 8120
 8121        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8122            cx.propagate();
 8123            return;
 8124        }
 8125
 8126        let Some(row_count) = self.visible_row_count() else {
 8127            return;
 8128        };
 8129
 8130        let autoscroll = if action.center_cursor {
 8131            Autoscroll::center()
 8132        } else {
 8133            Autoscroll::fit()
 8134        };
 8135
 8136        let text_layout_details = &self.text_layout_details(window);
 8137        self.change_selections(Some(autoscroll), window, cx, |s| {
 8138            let line_mode = s.line_mode;
 8139            s.move_with(|map, selection| {
 8140                if !selection.is_empty() && !line_mode {
 8141                    selection.goal = SelectionGoal::None;
 8142                }
 8143                let (cursor, goal) = movement::down_by_rows(
 8144                    map,
 8145                    selection.end,
 8146                    row_count,
 8147                    selection.goal,
 8148                    false,
 8149                    text_layout_details,
 8150                );
 8151                selection.collapse_to(cursor, goal);
 8152            });
 8153        });
 8154    }
 8155
 8156    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8157        let text_layout_details = &self.text_layout_details(window);
 8158        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8159            s.move_heads_with(|map, head, goal| {
 8160                movement::down(map, head, goal, false, text_layout_details)
 8161            })
 8162        });
 8163    }
 8164
 8165    pub fn context_menu_first(
 8166        &mut self,
 8167        _: &ContextMenuFirst,
 8168        _window: &mut Window,
 8169        cx: &mut Context<Self>,
 8170    ) {
 8171        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8172            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8173        }
 8174    }
 8175
 8176    pub fn context_menu_prev(
 8177        &mut self,
 8178        _: &ContextMenuPrev,
 8179        _window: &mut Window,
 8180        cx: &mut Context<Self>,
 8181    ) {
 8182        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8183            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8184        }
 8185    }
 8186
 8187    pub fn context_menu_next(
 8188        &mut self,
 8189        _: &ContextMenuNext,
 8190        _window: &mut Window,
 8191        cx: &mut Context<Self>,
 8192    ) {
 8193        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8194            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8195        }
 8196    }
 8197
 8198    pub fn context_menu_last(
 8199        &mut self,
 8200        _: &ContextMenuLast,
 8201        _window: &mut Window,
 8202        cx: &mut Context<Self>,
 8203    ) {
 8204        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8205            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8206        }
 8207    }
 8208
 8209    pub fn move_to_previous_word_start(
 8210        &mut self,
 8211        _: &MoveToPreviousWordStart,
 8212        window: &mut Window,
 8213        cx: &mut Context<Self>,
 8214    ) {
 8215        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8216            s.move_cursors_with(|map, head, _| {
 8217                (
 8218                    movement::previous_word_start(map, head),
 8219                    SelectionGoal::None,
 8220                )
 8221            });
 8222        })
 8223    }
 8224
 8225    pub fn move_to_previous_subword_start(
 8226        &mut self,
 8227        _: &MoveToPreviousSubwordStart,
 8228        window: &mut Window,
 8229        cx: &mut Context<Self>,
 8230    ) {
 8231        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8232            s.move_cursors_with(|map, head, _| {
 8233                (
 8234                    movement::previous_subword_start(map, head),
 8235                    SelectionGoal::None,
 8236                )
 8237            });
 8238        })
 8239    }
 8240
 8241    pub fn select_to_previous_word_start(
 8242        &mut self,
 8243        _: &SelectToPreviousWordStart,
 8244        window: &mut Window,
 8245        cx: &mut Context<Self>,
 8246    ) {
 8247        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8248            s.move_heads_with(|map, head, _| {
 8249                (
 8250                    movement::previous_word_start(map, head),
 8251                    SelectionGoal::None,
 8252                )
 8253            });
 8254        })
 8255    }
 8256
 8257    pub fn select_to_previous_subword_start(
 8258        &mut self,
 8259        _: &SelectToPreviousSubwordStart,
 8260        window: &mut Window,
 8261        cx: &mut Context<Self>,
 8262    ) {
 8263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8264            s.move_heads_with(|map, head, _| {
 8265                (
 8266                    movement::previous_subword_start(map, head),
 8267                    SelectionGoal::None,
 8268                )
 8269            });
 8270        })
 8271    }
 8272
 8273    pub fn delete_to_previous_word_start(
 8274        &mut self,
 8275        action: &DeleteToPreviousWordStart,
 8276        window: &mut Window,
 8277        cx: &mut Context<Self>,
 8278    ) {
 8279        self.transact(window, cx, |this, window, cx| {
 8280            this.select_autoclose_pair(window, cx);
 8281            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8282                let line_mode = s.line_mode;
 8283                s.move_with(|map, selection| {
 8284                    if selection.is_empty() && !line_mode {
 8285                        let cursor = if action.ignore_newlines {
 8286                            movement::previous_word_start(map, selection.head())
 8287                        } else {
 8288                            movement::previous_word_start_or_newline(map, selection.head())
 8289                        };
 8290                        selection.set_head(cursor, SelectionGoal::None);
 8291                    }
 8292                });
 8293            });
 8294            this.insert("", window, cx);
 8295        });
 8296    }
 8297
 8298    pub fn delete_to_previous_subword_start(
 8299        &mut self,
 8300        _: &DeleteToPreviousSubwordStart,
 8301        window: &mut Window,
 8302        cx: &mut Context<Self>,
 8303    ) {
 8304        self.transact(window, cx, |this, window, cx| {
 8305            this.select_autoclose_pair(window, cx);
 8306            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8307                let line_mode = s.line_mode;
 8308                s.move_with(|map, selection| {
 8309                    if selection.is_empty() && !line_mode {
 8310                        let cursor = movement::previous_subword_start(map, selection.head());
 8311                        selection.set_head(cursor, SelectionGoal::None);
 8312                    }
 8313                });
 8314            });
 8315            this.insert("", window, cx);
 8316        });
 8317    }
 8318
 8319    pub fn move_to_next_word_end(
 8320        &mut self,
 8321        _: &MoveToNextWordEnd,
 8322        window: &mut Window,
 8323        cx: &mut Context<Self>,
 8324    ) {
 8325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8326            s.move_cursors_with(|map, head, _| {
 8327                (movement::next_word_end(map, head), SelectionGoal::None)
 8328            });
 8329        })
 8330    }
 8331
 8332    pub fn move_to_next_subword_end(
 8333        &mut self,
 8334        _: &MoveToNextSubwordEnd,
 8335        window: &mut Window,
 8336        cx: &mut Context<Self>,
 8337    ) {
 8338        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8339            s.move_cursors_with(|map, head, _| {
 8340                (movement::next_subword_end(map, head), SelectionGoal::None)
 8341            });
 8342        })
 8343    }
 8344
 8345    pub fn select_to_next_word_end(
 8346        &mut self,
 8347        _: &SelectToNextWordEnd,
 8348        window: &mut Window,
 8349        cx: &mut Context<Self>,
 8350    ) {
 8351        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8352            s.move_heads_with(|map, head, _| {
 8353                (movement::next_word_end(map, head), SelectionGoal::None)
 8354            });
 8355        })
 8356    }
 8357
 8358    pub fn select_to_next_subword_end(
 8359        &mut self,
 8360        _: &SelectToNextSubwordEnd,
 8361        window: &mut Window,
 8362        cx: &mut Context<Self>,
 8363    ) {
 8364        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8365            s.move_heads_with(|map, head, _| {
 8366                (movement::next_subword_end(map, head), SelectionGoal::None)
 8367            });
 8368        })
 8369    }
 8370
 8371    pub fn delete_to_next_word_end(
 8372        &mut self,
 8373        action: &DeleteToNextWordEnd,
 8374        window: &mut Window,
 8375        cx: &mut Context<Self>,
 8376    ) {
 8377        self.transact(window, cx, |this, window, cx| {
 8378            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8379                let line_mode = s.line_mode;
 8380                s.move_with(|map, selection| {
 8381                    if selection.is_empty() && !line_mode {
 8382                        let cursor = if action.ignore_newlines {
 8383                            movement::next_word_end(map, selection.head())
 8384                        } else {
 8385                            movement::next_word_end_or_newline(map, selection.head())
 8386                        };
 8387                        selection.set_head(cursor, SelectionGoal::None);
 8388                    }
 8389                });
 8390            });
 8391            this.insert("", window, cx);
 8392        });
 8393    }
 8394
 8395    pub fn delete_to_next_subword_end(
 8396        &mut self,
 8397        _: &DeleteToNextSubwordEnd,
 8398        window: &mut Window,
 8399        cx: &mut Context<Self>,
 8400    ) {
 8401        self.transact(window, cx, |this, window, cx| {
 8402            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8403                s.move_with(|map, selection| {
 8404                    if selection.is_empty() {
 8405                        let cursor = movement::next_subword_end(map, selection.head());
 8406                        selection.set_head(cursor, SelectionGoal::None);
 8407                    }
 8408                });
 8409            });
 8410            this.insert("", window, cx);
 8411        });
 8412    }
 8413
 8414    pub fn move_to_beginning_of_line(
 8415        &mut self,
 8416        action: &MoveToBeginningOfLine,
 8417        window: &mut Window,
 8418        cx: &mut Context<Self>,
 8419    ) {
 8420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421            s.move_cursors_with(|map, head, _| {
 8422                (
 8423                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8424                    SelectionGoal::None,
 8425                )
 8426            });
 8427        })
 8428    }
 8429
 8430    pub fn select_to_beginning_of_line(
 8431        &mut self,
 8432        action: &SelectToBeginningOfLine,
 8433        window: &mut Window,
 8434        cx: &mut Context<Self>,
 8435    ) {
 8436        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8437            s.move_heads_with(|map, head, _| {
 8438                (
 8439                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8440                    SelectionGoal::None,
 8441                )
 8442            });
 8443        });
 8444    }
 8445
 8446    pub fn delete_to_beginning_of_line(
 8447        &mut self,
 8448        _: &DeleteToBeginningOfLine,
 8449        window: &mut Window,
 8450        cx: &mut Context<Self>,
 8451    ) {
 8452        self.transact(window, cx, |this, window, cx| {
 8453            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8454                s.move_with(|_, selection| {
 8455                    selection.reversed = true;
 8456                });
 8457            });
 8458
 8459            this.select_to_beginning_of_line(
 8460                &SelectToBeginningOfLine {
 8461                    stop_at_soft_wraps: false,
 8462                },
 8463                window,
 8464                cx,
 8465            );
 8466            this.backspace(&Backspace, window, cx);
 8467        });
 8468    }
 8469
 8470    pub fn move_to_end_of_line(
 8471        &mut self,
 8472        action: &MoveToEndOfLine,
 8473        window: &mut Window,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8477            s.move_cursors_with(|map, head, _| {
 8478                (
 8479                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8480                    SelectionGoal::None,
 8481                )
 8482            });
 8483        })
 8484    }
 8485
 8486    pub fn select_to_end_of_line(
 8487        &mut self,
 8488        action: &SelectToEndOfLine,
 8489        window: &mut Window,
 8490        cx: &mut Context<Self>,
 8491    ) {
 8492        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8493            s.move_heads_with(|map, head, _| {
 8494                (
 8495                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8496                    SelectionGoal::None,
 8497                )
 8498            });
 8499        })
 8500    }
 8501
 8502    pub fn delete_to_end_of_line(
 8503        &mut self,
 8504        _: &DeleteToEndOfLine,
 8505        window: &mut Window,
 8506        cx: &mut Context<Self>,
 8507    ) {
 8508        self.transact(window, cx, |this, window, cx| {
 8509            this.select_to_end_of_line(
 8510                &SelectToEndOfLine {
 8511                    stop_at_soft_wraps: false,
 8512                },
 8513                window,
 8514                cx,
 8515            );
 8516            this.delete(&Delete, window, cx);
 8517        });
 8518    }
 8519
 8520    pub fn cut_to_end_of_line(
 8521        &mut self,
 8522        _: &CutToEndOfLine,
 8523        window: &mut Window,
 8524        cx: &mut Context<Self>,
 8525    ) {
 8526        self.transact(window, cx, |this, window, cx| {
 8527            this.select_to_end_of_line(
 8528                &SelectToEndOfLine {
 8529                    stop_at_soft_wraps: false,
 8530                },
 8531                window,
 8532                cx,
 8533            );
 8534            this.cut(&Cut, window, cx);
 8535        });
 8536    }
 8537
 8538    pub fn move_to_start_of_paragraph(
 8539        &mut self,
 8540        _: &MoveToStartOfParagraph,
 8541        window: &mut Window,
 8542        cx: &mut Context<Self>,
 8543    ) {
 8544        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8545            cx.propagate();
 8546            return;
 8547        }
 8548
 8549        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8550            s.move_with(|map, selection| {
 8551                selection.collapse_to(
 8552                    movement::start_of_paragraph(map, selection.head(), 1),
 8553                    SelectionGoal::None,
 8554                )
 8555            });
 8556        })
 8557    }
 8558
 8559    pub fn move_to_end_of_paragraph(
 8560        &mut self,
 8561        _: &MoveToEndOfParagraph,
 8562        window: &mut Window,
 8563        cx: &mut Context<Self>,
 8564    ) {
 8565        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8566            cx.propagate();
 8567            return;
 8568        }
 8569
 8570        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8571            s.move_with(|map, selection| {
 8572                selection.collapse_to(
 8573                    movement::end_of_paragraph(map, selection.head(), 1),
 8574                    SelectionGoal::None,
 8575                )
 8576            });
 8577        })
 8578    }
 8579
 8580    pub fn select_to_start_of_paragraph(
 8581        &mut self,
 8582        _: &SelectToStartOfParagraph,
 8583        window: &mut Window,
 8584        cx: &mut Context<Self>,
 8585    ) {
 8586        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8587            cx.propagate();
 8588            return;
 8589        }
 8590
 8591        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8592            s.move_heads_with(|map, head, _| {
 8593                (
 8594                    movement::start_of_paragraph(map, head, 1),
 8595                    SelectionGoal::None,
 8596                )
 8597            });
 8598        })
 8599    }
 8600
 8601    pub fn select_to_end_of_paragraph(
 8602        &mut self,
 8603        _: &SelectToEndOfParagraph,
 8604        window: &mut Window,
 8605        cx: &mut Context<Self>,
 8606    ) {
 8607        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8608            cx.propagate();
 8609            return;
 8610        }
 8611
 8612        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8613            s.move_heads_with(|map, head, _| {
 8614                (
 8615                    movement::end_of_paragraph(map, head, 1),
 8616                    SelectionGoal::None,
 8617                )
 8618            });
 8619        })
 8620    }
 8621
 8622    pub fn move_to_beginning(
 8623        &mut self,
 8624        _: &MoveToBeginning,
 8625        window: &mut Window,
 8626        cx: &mut Context<Self>,
 8627    ) {
 8628        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8629            cx.propagate();
 8630            return;
 8631        }
 8632
 8633        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8634            s.select_ranges(vec![0..0]);
 8635        });
 8636    }
 8637
 8638    pub fn select_to_beginning(
 8639        &mut self,
 8640        _: &SelectToBeginning,
 8641        window: &mut Window,
 8642        cx: &mut Context<Self>,
 8643    ) {
 8644        let mut selection = self.selections.last::<Point>(cx);
 8645        selection.set_head(Point::zero(), SelectionGoal::None);
 8646
 8647        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8648            s.select(vec![selection]);
 8649        });
 8650    }
 8651
 8652    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8653        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8654            cx.propagate();
 8655            return;
 8656        }
 8657
 8658        let cursor = self.buffer.read(cx).read(cx).len();
 8659        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8660            s.select_ranges(vec![cursor..cursor])
 8661        });
 8662    }
 8663
 8664    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8665        self.nav_history = nav_history;
 8666    }
 8667
 8668    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8669        self.nav_history.as_ref()
 8670    }
 8671
 8672    fn push_to_nav_history(
 8673        &mut self,
 8674        cursor_anchor: Anchor,
 8675        new_position: Option<Point>,
 8676        cx: &mut Context<Self>,
 8677    ) {
 8678        if let Some(nav_history) = self.nav_history.as_mut() {
 8679            let buffer = self.buffer.read(cx).read(cx);
 8680            let cursor_position = cursor_anchor.to_point(&buffer);
 8681            let scroll_state = self.scroll_manager.anchor();
 8682            let scroll_top_row = scroll_state.top_row(&buffer);
 8683            drop(buffer);
 8684
 8685            if let Some(new_position) = new_position {
 8686                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8687                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8688                    return;
 8689                }
 8690            }
 8691
 8692            nav_history.push(
 8693                Some(NavigationData {
 8694                    cursor_anchor,
 8695                    cursor_position,
 8696                    scroll_anchor: scroll_state,
 8697                    scroll_top_row,
 8698                }),
 8699                cx,
 8700            );
 8701        }
 8702    }
 8703
 8704    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8705        let buffer = self.buffer.read(cx).snapshot(cx);
 8706        let mut selection = self.selections.first::<usize>(cx);
 8707        selection.set_head(buffer.len(), SelectionGoal::None);
 8708        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8709            s.select(vec![selection]);
 8710        });
 8711    }
 8712
 8713    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8714        let end = self.buffer.read(cx).read(cx).len();
 8715        self.change_selections(None, window, cx, |s| {
 8716            s.select_ranges(vec![0..end]);
 8717        });
 8718    }
 8719
 8720    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8721        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8722        let mut selections = self.selections.all::<Point>(cx);
 8723        let max_point = display_map.buffer_snapshot.max_point();
 8724        for selection in &mut selections {
 8725            let rows = selection.spanned_rows(true, &display_map);
 8726            selection.start = Point::new(rows.start.0, 0);
 8727            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8728            selection.reversed = false;
 8729        }
 8730        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8731            s.select(selections);
 8732        });
 8733    }
 8734
 8735    pub fn split_selection_into_lines(
 8736        &mut self,
 8737        _: &SplitSelectionIntoLines,
 8738        window: &mut Window,
 8739        cx: &mut Context<Self>,
 8740    ) {
 8741        let mut to_unfold = Vec::new();
 8742        let mut new_selection_ranges = Vec::new();
 8743        {
 8744            let selections = self.selections.all::<Point>(cx);
 8745            let buffer = self.buffer.read(cx).read(cx);
 8746            for selection in selections {
 8747                for row in selection.start.row..selection.end.row {
 8748                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8749                    new_selection_ranges.push(cursor..cursor);
 8750                }
 8751                new_selection_ranges.push(selection.end..selection.end);
 8752                to_unfold.push(selection.start..selection.end);
 8753            }
 8754        }
 8755        self.unfold_ranges(&to_unfold, true, true, cx);
 8756        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8757            s.select_ranges(new_selection_ranges);
 8758        });
 8759    }
 8760
 8761    pub fn add_selection_above(
 8762        &mut self,
 8763        _: &AddSelectionAbove,
 8764        window: &mut Window,
 8765        cx: &mut Context<Self>,
 8766    ) {
 8767        self.add_selection(true, window, cx);
 8768    }
 8769
 8770    pub fn add_selection_below(
 8771        &mut self,
 8772        _: &AddSelectionBelow,
 8773        window: &mut Window,
 8774        cx: &mut Context<Self>,
 8775    ) {
 8776        self.add_selection(false, window, cx);
 8777    }
 8778
 8779    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8781        let mut selections = self.selections.all::<Point>(cx);
 8782        let text_layout_details = self.text_layout_details(window);
 8783        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8784            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8785            let range = oldest_selection.display_range(&display_map).sorted();
 8786
 8787            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8788            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8789            let positions = start_x.min(end_x)..start_x.max(end_x);
 8790
 8791            selections.clear();
 8792            let mut stack = Vec::new();
 8793            for row in range.start.row().0..=range.end.row().0 {
 8794                if let Some(selection) = self.selections.build_columnar_selection(
 8795                    &display_map,
 8796                    DisplayRow(row),
 8797                    &positions,
 8798                    oldest_selection.reversed,
 8799                    &text_layout_details,
 8800                ) {
 8801                    stack.push(selection.id);
 8802                    selections.push(selection);
 8803                }
 8804            }
 8805
 8806            if above {
 8807                stack.reverse();
 8808            }
 8809
 8810            AddSelectionsState { above, stack }
 8811        });
 8812
 8813        let last_added_selection = *state.stack.last().unwrap();
 8814        let mut new_selections = Vec::new();
 8815        if above == state.above {
 8816            let end_row = if above {
 8817                DisplayRow(0)
 8818            } else {
 8819                display_map.max_point().row()
 8820            };
 8821
 8822            'outer: for selection in selections {
 8823                if selection.id == last_added_selection {
 8824                    let range = selection.display_range(&display_map).sorted();
 8825                    debug_assert_eq!(range.start.row(), range.end.row());
 8826                    let mut row = range.start.row();
 8827                    let positions =
 8828                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8829                            px(start)..px(end)
 8830                        } else {
 8831                            let start_x =
 8832                                display_map.x_for_display_point(range.start, &text_layout_details);
 8833                            let end_x =
 8834                                display_map.x_for_display_point(range.end, &text_layout_details);
 8835                            start_x.min(end_x)..start_x.max(end_x)
 8836                        };
 8837
 8838                    while row != end_row {
 8839                        if above {
 8840                            row.0 -= 1;
 8841                        } else {
 8842                            row.0 += 1;
 8843                        }
 8844
 8845                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8846                            &display_map,
 8847                            row,
 8848                            &positions,
 8849                            selection.reversed,
 8850                            &text_layout_details,
 8851                        ) {
 8852                            state.stack.push(new_selection.id);
 8853                            if above {
 8854                                new_selections.push(new_selection);
 8855                                new_selections.push(selection);
 8856                            } else {
 8857                                new_selections.push(selection);
 8858                                new_selections.push(new_selection);
 8859                            }
 8860
 8861                            continue 'outer;
 8862                        }
 8863                    }
 8864                }
 8865
 8866                new_selections.push(selection);
 8867            }
 8868        } else {
 8869            new_selections = selections;
 8870            new_selections.retain(|s| s.id != last_added_selection);
 8871            state.stack.pop();
 8872        }
 8873
 8874        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8875            s.select(new_selections);
 8876        });
 8877        if state.stack.len() > 1 {
 8878            self.add_selections_state = Some(state);
 8879        }
 8880    }
 8881
 8882    pub fn select_next_match_internal(
 8883        &mut self,
 8884        display_map: &DisplaySnapshot,
 8885        replace_newest: bool,
 8886        autoscroll: Option<Autoscroll>,
 8887        window: &mut Window,
 8888        cx: &mut Context<Self>,
 8889    ) -> Result<()> {
 8890        fn select_next_match_ranges(
 8891            this: &mut Editor,
 8892            range: Range<usize>,
 8893            replace_newest: bool,
 8894            auto_scroll: Option<Autoscroll>,
 8895            window: &mut Window,
 8896            cx: &mut Context<Editor>,
 8897        ) {
 8898            this.unfold_ranges(&[range.clone()], false, true, cx);
 8899            this.change_selections(auto_scroll, window, cx, |s| {
 8900                if replace_newest {
 8901                    s.delete(s.newest_anchor().id);
 8902                }
 8903                s.insert_range(range.clone());
 8904            });
 8905        }
 8906
 8907        let buffer = &display_map.buffer_snapshot;
 8908        let mut selections = self.selections.all::<usize>(cx);
 8909        if let Some(mut select_next_state) = self.select_next_state.take() {
 8910            let query = &select_next_state.query;
 8911            if !select_next_state.done {
 8912                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8913                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8914                let mut next_selected_range = None;
 8915
 8916                let bytes_after_last_selection =
 8917                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8918                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8919                let query_matches = query
 8920                    .stream_find_iter(bytes_after_last_selection)
 8921                    .map(|result| (last_selection.end, result))
 8922                    .chain(
 8923                        query
 8924                            .stream_find_iter(bytes_before_first_selection)
 8925                            .map(|result| (0, result)),
 8926                    );
 8927
 8928                for (start_offset, query_match) in query_matches {
 8929                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8930                    let offset_range =
 8931                        start_offset + query_match.start()..start_offset + query_match.end();
 8932                    let display_range = offset_range.start.to_display_point(display_map)
 8933                        ..offset_range.end.to_display_point(display_map);
 8934
 8935                    if !select_next_state.wordwise
 8936                        || (!movement::is_inside_word(display_map, display_range.start)
 8937                            && !movement::is_inside_word(display_map, display_range.end))
 8938                    {
 8939                        // TODO: This is n^2, because we might check all the selections
 8940                        if !selections
 8941                            .iter()
 8942                            .any(|selection| selection.range().overlaps(&offset_range))
 8943                        {
 8944                            next_selected_range = Some(offset_range);
 8945                            break;
 8946                        }
 8947                    }
 8948                }
 8949
 8950                if let Some(next_selected_range) = next_selected_range {
 8951                    select_next_match_ranges(
 8952                        self,
 8953                        next_selected_range,
 8954                        replace_newest,
 8955                        autoscroll,
 8956                        window,
 8957                        cx,
 8958                    );
 8959                } else {
 8960                    select_next_state.done = true;
 8961                }
 8962            }
 8963
 8964            self.select_next_state = Some(select_next_state);
 8965        } else {
 8966            let mut only_carets = true;
 8967            let mut same_text_selected = true;
 8968            let mut selected_text = None;
 8969
 8970            let mut selections_iter = selections.iter().peekable();
 8971            while let Some(selection) = selections_iter.next() {
 8972                if selection.start != selection.end {
 8973                    only_carets = false;
 8974                }
 8975
 8976                if same_text_selected {
 8977                    if selected_text.is_none() {
 8978                        selected_text =
 8979                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8980                    }
 8981
 8982                    if let Some(next_selection) = selections_iter.peek() {
 8983                        if next_selection.range().len() == selection.range().len() {
 8984                            let next_selected_text = buffer
 8985                                .text_for_range(next_selection.range())
 8986                                .collect::<String>();
 8987                            if Some(next_selected_text) != selected_text {
 8988                                same_text_selected = false;
 8989                                selected_text = None;
 8990                            }
 8991                        } else {
 8992                            same_text_selected = false;
 8993                            selected_text = None;
 8994                        }
 8995                    }
 8996                }
 8997            }
 8998
 8999            if only_carets {
 9000                for selection in &mut selections {
 9001                    let word_range = movement::surrounding_word(
 9002                        display_map,
 9003                        selection.start.to_display_point(display_map),
 9004                    );
 9005                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9006                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9007                    selection.goal = SelectionGoal::None;
 9008                    selection.reversed = false;
 9009                    select_next_match_ranges(
 9010                        self,
 9011                        selection.start..selection.end,
 9012                        replace_newest,
 9013                        autoscroll,
 9014                        window,
 9015                        cx,
 9016                    );
 9017                }
 9018
 9019                if selections.len() == 1 {
 9020                    let selection = selections
 9021                        .last()
 9022                        .expect("ensured that there's only one selection");
 9023                    let query = buffer
 9024                        .text_for_range(selection.start..selection.end)
 9025                        .collect::<String>();
 9026                    let is_empty = query.is_empty();
 9027                    let select_state = SelectNextState {
 9028                        query: AhoCorasick::new(&[query])?,
 9029                        wordwise: true,
 9030                        done: is_empty,
 9031                    };
 9032                    self.select_next_state = Some(select_state);
 9033                } else {
 9034                    self.select_next_state = None;
 9035                }
 9036            } else if let Some(selected_text) = selected_text {
 9037                self.select_next_state = Some(SelectNextState {
 9038                    query: AhoCorasick::new(&[selected_text])?,
 9039                    wordwise: false,
 9040                    done: false,
 9041                });
 9042                self.select_next_match_internal(
 9043                    display_map,
 9044                    replace_newest,
 9045                    autoscroll,
 9046                    window,
 9047                    cx,
 9048                )?;
 9049            }
 9050        }
 9051        Ok(())
 9052    }
 9053
 9054    pub fn select_all_matches(
 9055        &mut self,
 9056        _action: &SelectAllMatches,
 9057        window: &mut Window,
 9058        cx: &mut Context<Self>,
 9059    ) -> Result<()> {
 9060        self.push_to_selection_history();
 9061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9062
 9063        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9064        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9065            return Ok(());
 9066        };
 9067        if select_next_state.done {
 9068            return Ok(());
 9069        }
 9070
 9071        let mut new_selections = self.selections.all::<usize>(cx);
 9072
 9073        let buffer = &display_map.buffer_snapshot;
 9074        let query_matches = select_next_state
 9075            .query
 9076            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9077
 9078        for query_match in query_matches {
 9079            let query_match = query_match.unwrap(); // can only fail due to I/O
 9080            let offset_range = query_match.start()..query_match.end();
 9081            let display_range = offset_range.start.to_display_point(&display_map)
 9082                ..offset_range.end.to_display_point(&display_map);
 9083
 9084            if !select_next_state.wordwise
 9085                || (!movement::is_inside_word(&display_map, display_range.start)
 9086                    && !movement::is_inside_word(&display_map, display_range.end))
 9087            {
 9088                self.selections.change_with(cx, |selections| {
 9089                    new_selections.push(Selection {
 9090                        id: selections.new_selection_id(),
 9091                        start: offset_range.start,
 9092                        end: offset_range.end,
 9093                        reversed: false,
 9094                        goal: SelectionGoal::None,
 9095                    });
 9096                });
 9097            }
 9098        }
 9099
 9100        new_selections.sort_by_key(|selection| selection.start);
 9101        let mut ix = 0;
 9102        while ix + 1 < new_selections.len() {
 9103            let current_selection = &new_selections[ix];
 9104            let next_selection = &new_selections[ix + 1];
 9105            if current_selection.range().overlaps(&next_selection.range()) {
 9106                if current_selection.id < next_selection.id {
 9107                    new_selections.remove(ix + 1);
 9108                } else {
 9109                    new_selections.remove(ix);
 9110                }
 9111            } else {
 9112                ix += 1;
 9113            }
 9114        }
 9115
 9116        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9117
 9118        for selection in new_selections.iter_mut() {
 9119            selection.reversed = reversed;
 9120        }
 9121
 9122        select_next_state.done = true;
 9123        self.unfold_ranges(
 9124            &new_selections
 9125                .iter()
 9126                .map(|selection| selection.range())
 9127                .collect::<Vec<_>>(),
 9128            false,
 9129            false,
 9130            cx,
 9131        );
 9132        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9133            selections.select(new_selections)
 9134        });
 9135
 9136        Ok(())
 9137    }
 9138
 9139    pub fn select_next(
 9140        &mut self,
 9141        action: &SelectNext,
 9142        window: &mut Window,
 9143        cx: &mut Context<Self>,
 9144    ) -> Result<()> {
 9145        self.push_to_selection_history();
 9146        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9147        self.select_next_match_internal(
 9148            &display_map,
 9149            action.replace_newest,
 9150            Some(Autoscroll::newest()),
 9151            window,
 9152            cx,
 9153        )?;
 9154        Ok(())
 9155    }
 9156
 9157    pub fn select_previous(
 9158        &mut self,
 9159        action: &SelectPrevious,
 9160        window: &mut Window,
 9161        cx: &mut Context<Self>,
 9162    ) -> Result<()> {
 9163        self.push_to_selection_history();
 9164        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9165        let buffer = &display_map.buffer_snapshot;
 9166        let mut selections = self.selections.all::<usize>(cx);
 9167        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9168            let query = &select_prev_state.query;
 9169            if !select_prev_state.done {
 9170                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9171                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9172                let mut next_selected_range = None;
 9173                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9174                let bytes_before_last_selection =
 9175                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9176                let bytes_after_first_selection =
 9177                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9178                let query_matches = query
 9179                    .stream_find_iter(bytes_before_last_selection)
 9180                    .map(|result| (last_selection.start, result))
 9181                    .chain(
 9182                        query
 9183                            .stream_find_iter(bytes_after_first_selection)
 9184                            .map(|result| (buffer.len(), result)),
 9185                    );
 9186                for (end_offset, query_match) in query_matches {
 9187                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9188                    let offset_range =
 9189                        end_offset - query_match.end()..end_offset - query_match.start();
 9190                    let display_range = offset_range.start.to_display_point(&display_map)
 9191                        ..offset_range.end.to_display_point(&display_map);
 9192
 9193                    if !select_prev_state.wordwise
 9194                        || (!movement::is_inside_word(&display_map, display_range.start)
 9195                            && !movement::is_inside_word(&display_map, display_range.end))
 9196                    {
 9197                        next_selected_range = Some(offset_range);
 9198                        break;
 9199                    }
 9200                }
 9201
 9202                if let Some(next_selected_range) = next_selected_range {
 9203                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9204                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9205                        if action.replace_newest {
 9206                            s.delete(s.newest_anchor().id);
 9207                        }
 9208                        s.insert_range(next_selected_range);
 9209                    });
 9210                } else {
 9211                    select_prev_state.done = true;
 9212                }
 9213            }
 9214
 9215            self.select_prev_state = Some(select_prev_state);
 9216        } else {
 9217            let mut only_carets = true;
 9218            let mut same_text_selected = true;
 9219            let mut selected_text = None;
 9220
 9221            let mut selections_iter = selections.iter().peekable();
 9222            while let Some(selection) = selections_iter.next() {
 9223                if selection.start != selection.end {
 9224                    only_carets = false;
 9225                }
 9226
 9227                if same_text_selected {
 9228                    if selected_text.is_none() {
 9229                        selected_text =
 9230                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9231                    }
 9232
 9233                    if let Some(next_selection) = selections_iter.peek() {
 9234                        if next_selection.range().len() == selection.range().len() {
 9235                            let next_selected_text = buffer
 9236                                .text_for_range(next_selection.range())
 9237                                .collect::<String>();
 9238                            if Some(next_selected_text) != selected_text {
 9239                                same_text_selected = false;
 9240                                selected_text = None;
 9241                            }
 9242                        } else {
 9243                            same_text_selected = false;
 9244                            selected_text = None;
 9245                        }
 9246                    }
 9247                }
 9248            }
 9249
 9250            if only_carets {
 9251                for selection in &mut selections {
 9252                    let word_range = movement::surrounding_word(
 9253                        &display_map,
 9254                        selection.start.to_display_point(&display_map),
 9255                    );
 9256                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9257                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9258                    selection.goal = SelectionGoal::None;
 9259                    selection.reversed = false;
 9260                }
 9261                if selections.len() == 1 {
 9262                    let selection = selections
 9263                        .last()
 9264                        .expect("ensured that there's only one selection");
 9265                    let query = buffer
 9266                        .text_for_range(selection.start..selection.end)
 9267                        .collect::<String>();
 9268                    let is_empty = query.is_empty();
 9269                    let select_state = SelectNextState {
 9270                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9271                        wordwise: true,
 9272                        done: is_empty,
 9273                    };
 9274                    self.select_prev_state = Some(select_state);
 9275                } else {
 9276                    self.select_prev_state = None;
 9277                }
 9278
 9279                self.unfold_ranges(
 9280                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9281                    false,
 9282                    true,
 9283                    cx,
 9284                );
 9285                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9286                    s.select(selections);
 9287                });
 9288            } else if let Some(selected_text) = selected_text {
 9289                self.select_prev_state = Some(SelectNextState {
 9290                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9291                    wordwise: false,
 9292                    done: false,
 9293                });
 9294                self.select_previous(action, window, cx)?;
 9295            }
 9296        }
 9297        Ok(())
 9298    }
 9299
 9300    pub fn toggle_comments(
 9301        &mut self,
 9302        action: &ToggleComments,
 9303        window: &mut Window,
 9304        cx: &mut Context<Self>,
 9305    ) {
 9306        if self.read_only(cx) {
 9307            return;
 9308        }
 9309        let text_layout_details = &self.text_layout_details(window);
 9310        self.transact(window, cx, |this, window, cx| {
 9311            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9312            let mut edits = Vec::new();
 9313            let mut selection_edit_ranges = Vec::new();
 9314            let mut last_toggled_row = None;
 9315            let snapshot = this.buffer.read(cx).read(cx);
 9316            let empty_str: Arc<str> = Arc::default();
 9317            let mut suffixes_inserted = Vec::new();
 9318            let ignore_indent = action.ignore_indent;
 9319
 9320            fn comment_prefix_range(
 9321                snapshot: &MultiBufferSnapshot,
 9322                row: MultiBufferRow,
 9323                comment_prefix: &str,
 9324                comment_prefix_whitespace: &str,
 9325                ignore_indent: bool,
 9326            ) -> Range<Point> {
 9327                let indent_size = if ignore_indent {
 9328                    0
 9329                } else {
 9330                    snapshot.indent_size_for_line(row).len
 9331                };
 9332
 9333                let start = Point::new(row.0, indent_size);
 9334
 9335                let mut line_bytes = snapshot
 9336                    .bytes_in_range(start..snapshot.max_point())
 9337                    .flatten()
 9338                    .copied();
 9339
 9340                // If this line currently begins with the line comment prefix, then record
 9341                // the range containing the prefix.
 9342                if line_bytes
 9343                    .by_ref()
 9344                    .take(comment_prefix.len())
 9345                    .eq(comment_prefix.bytes())
 9346                {
 9347                    // Include any whitespace that matches the comment prefix.
 9348                    let matching_whitespace_len = line_bytes
 9349                        .zip(comment_prefix_whitespace.bytes())
 9350                        .take_while(|(a, b)| a == b)
 9351                        .count() as u32;
 9352                    let end = Point::new(
 9353                        start.row,
 9354                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9355                    );
 9356                    start..end
 9357                } else {
 9358                    start..start
 9359                }
 9360            }
 9361
 9362            fn comment_suffix_range(
 9363                snapshot: &MultiBufferSnapshot,
 9364                row: MultiBufferRow,
 9365                comment_suffix: &str,
 9366                comment_suffix_has_leading_space: bool,
 9367            ) -> Range<Point> {
 9368                let end = Point::new(row.0, snapshot.line_len(row));
 9369                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9370
 9371                let mut line_end_bytes = snapshot
 9372                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9373                    .flatten()
 9374                    .copied();
 9375
 9376                let leading_space_len = if suffix_start_column > 0
 9377                    && line_end_bytes.next() == Some(b' ')
 9378                    && comment_suffix_has_leading_space
 9379                {
 9380                    1
 9381                } else {
 9382                    0
 9383                };
 9384
 9385                // If this line currently begins with the line comment prefix, then record
 9386                // the range containing the prefix.
 9387                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9388                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9389                    start..end
 9390                } else {
 9391                    end..end
 9392                }
 9393            }
 9394
 9395            // TODO: Handle selections that cross excerpts
 9396            for selection in &mut selections {
 9397                let start_column = snapshot
 9398                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9399                    .len;
 9400                let language = if let Some(language) =
 9401                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9402                {
 9403                    language
 9404                } else {
 9405                    continue;
 9406                };
 9407
 9408                selection_edit_ranges.clear();
 9409
 9410                // If multiple selections contain a given row, avoid processing that
 9411                // row more than once.
 9412                let mut start_row = MultiBufferRow(selection.start.row);
 9413                if last_toggled_row == Some(start_row) {
 9414                    start_row = start_row.next_row();
 9415                }
 9416                let end_row =
 9417                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9418                        MultiBufferRow(selection.end.row - 1)
 9419                    } else {
 9420                        MultiBufferRow(selection.end.row)
 9421                    };
 9422                last_toggled_row = Some(end_row);
 9423
 9424                if start_row > end_row {
 9425                    continue;
 9426                }
 9427
 9428                // If the language has line comments, toggle those.
 9429                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9430
 9431                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9432                if ignore_indent {
 9433                    full_comment_prefixes = full_comment_prefixes
 9434                        .into_iter()
 9435                        .map(|s| Arc::from(s.trim_end()))
 9436                        .collect();
 9437                }
 9438
 9439                if !full_comment_prefixes.is_empty() {
 9440                    let first_prefix = full_comment_prefixes
 9441                        .first()
 9442                        .expect("prefixes is non-empty");
 9443                    let prefix_trimmed_lengths = full_comment_prefixes
 9444                        .iter()
 9445                        .map(|p| p.trim_end_matches(' ').len())
 9446                        .collect::<SmallVec<[usize; 4]>>();
 9447
 9448                    let mut all_selection_lines_are_comments = true;
 9449
 9450                    for row in start_row.0..=end_row.0 {
 9451                        let row = MultiBufferRow(row);
 9452                        if start_row < end_row && snapshot.is_line_blank(row) {
 9453                            continue;
 9454                        }
 9455
 9456                        let prefix_range = full_comment_prefixes
 9457                            .iter()
 9458                            .zip(prefix_trimmed_lengths.iter().copied())
 9459                            .map(|(prefix, trimmed_prefix_len)| {
 9460                                comment_prefix_range(
 9461                                    snapshot.deref(),
 9462                                    row,
 9463                                    &prefix[..trimmed_prefix_len],
 9464                                    &prefix[trimmed_prefix_len..],
 9465                                    ignore_indent,
 9466                                )
 9467                            })
 9468                            .max_by_key(|range| range.end.column - range.start.column)
 9469                            .expect("prefixes is non-empty");
 9470
 9471                        if prefix_range.is_empty() {
 9472                            all_selection_lines_are_comments = false;
 9473                        }
 9474
 9475                        selection_edit_ranges.push(prefix_range);
 9476                    }
 9477
 9478                    if all_selection_lines_are_comments {
 9479                        edits.extend(
 9480                            selection_edit_ranges
 9481                                .iter()
 9482                                .cloned()
 9483                                .map(|range| (range, empty_str.clone())),
 9484                        );
 9485                    } else {
 9486                        let min_column = selection_edit_ranges
 9487                            .iter()
 9488                            .map(|range| range.start.column)
 9489                            .min()
 9490                            .unwrap_or(0);
 9491                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9492                            let position = Point::new(range.start.row, min_column);
 9493                            (position..position, first_prefix.clone())
 9494                        }));
 9495                    }
 9496                } else if let Some((full_comment_prefix, comment_suffix)) =
 9497                    language.block_comment_delimiters()
 9498                {
 9499                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9500                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9501                    let prefix_range = comment_prefix_range(
 9502                        snapshot.deref(),
 9503                        start_row,
 9504                        comment_prefix,
 9505                        comment_prefix_whitespace,
 9506                        ignore_indent,
 9507                    );
 9508                    let suffix_range = comment_suffix_range(
 9509                        snapshot.deref(),
 9510                        end_row,
 9511                        comment_suffix.trim_start_matches(' '),
 9512                        comment_suffix.starts_with(' '),
 9513                    );
 9514
 9515                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9516                        edits.push((
 9517                            prefix_range.start..prefix_range.start,
 9518                            full_comment_prefix.clone(),
 9519                        ));
 9520                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9521                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9522                    } else {
 9523                        edits.push((prefix_range, empty_str.clone()));
 9524                        edits.push((suffix_range, empty_str.clone()));
 9525                    }
 9526                } else {
 9527                    continue;
 9528                }
 9529            }
 9530
 9531            drop(snapshot);
 9532            this.buffer.update(cx, |buffer, cx| {
 9533                buffer.edit(edits, None, cx);
 9534            });
 9535
 9536            // Adjust selections so that they end before any comment suffixes that
 9537            // were inserted.
 9538            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9539            let mut selections = this.selections.all::<Point>(cx);
 9540            let snapshot = this.buffer.read(cx).read(cx);
 9541            for selection in &mut selections {
 9542                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9543                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9544                        Ordering::Less => {
 9545                            suffixes_inserted.next();
 9546                            continue;
 9547                        }
 9548                        Ordering::Greater => break,
 9549                        Ordering::Equal => {
 9550                            if selection.end.column == snapshot.line_len(row) {
 9551                                if selection.is_empty() {
 9552                                    selection.start.column -= suffix_len as u32;
 9553                                }
 9554                                selection.end.column -= suffix_len as u32;
 9555                            }
 9556                            break;
 9557                        }
 9558                    }
 9559                }
 9560            }
 9561
 9562            drop(snapshot);
 9563            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9564                s.select(selections)
 9565            });
 9566
 9567            let selections = this.selections.all::<Point>(cx);
 9568            let selections_on_single_row = selections.windows(2).all(|selections| {
 9569                selections[0].start.row == selections[1].start.row
 9570                    && selections[0].end.row == selections[1].end.row
 9571                    && selections[0].start.row == selections[0].end.row
 9572            });
 9573            let selections_selecting = selections
 9574                .iter()
 9575                .any(|selection| selection.start != selection.end);
 9576            let advance_downwards = action.advance_downwards
 9577                && selections_on_single_row
 9578                && !selections_selecting
 9579                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9580
 9581            if advance_downwards {
 9582                let snapshot = this.buffer.read(cx).snapshot(cx);
 9583
 9584                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9585                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9586                        let mut point = display_point.to_point(display_snapshot);
 9587                        point.row += 1;
 9588                        point = snapshot.clip_point(point, Bias::Left);
 9589                        let display_point = point.to_display_point(display_snapshot);
 9590                        let goal = SelectionGoal::HorizontalPosition(
 9591                            display_snapshot
 9592                                .x_for_display_point(display_point, text_layout_details)
 9593                                .into(),
 9594                        );
 9595                        (display_point, goal)
 9596                    })
 9597                });
 9598            }
 9599        });
 9600    }
 9601
 9602    pub fn select_enclosing_symbol(
 9603        &mut self,
 9604        _: &SelectEnclosingSymbol,
 9605        window: &mut Window,
 9606        cx: &mut Context<Self>,
 9607    ) {
 9608        let buffer = self.buffer.read(cx).snapshot(cx);
 9609        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9610
 9611        fn update_selection(
 9612            selection: &Selection<usize>,
 9613            buffer_snap: &MultiBufferSnapshot,
 9614        ) -> Option<Selection<usize>> {
 9615            let cursor = selection.head();
 9616            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9617            for symbol in symbols.iter().rev() {
 9618                let start = symbol.range.start.to_offset(buffer_snap);
 9619                let end = symbol.range.end.to_offset(buffer_snap);
 9620                let new_range = start..end;
 9621                if start < selection.start || end > selection.end {
 9622                    return Some(Selection {
 9623                        id: selection.id,
 9624                        start: new_range.start,
 9625                        end: new_range.end,
 9626                        goal: SelectionGoal::None,
 9627                        reversed: selection.reversed,
 9628                    });
 9629                }
 9630            }
 9631            None
 9632        }
 9633
 9634        let mut selected_larger_symbol = false;
 9635        let new_selections = old_selections
 9636            .iter()
 9637            .map(|selection| match update_selection(selection, &buffer) {
 9638                Some(new_selection) => {
 9639                    if new_selection.range() != selection.range() {
 9640                        selected_larger_symbol = true;
 9641                    }
 9642                    new_selection
 9643                }
 9644                None => selection.clone(),
 9645            })
 9646            .collect::<Vec<_>>();
 9647
 9648        if selected_larger_symbol {
 9649            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650                s.select(new_selections);
 9651            });
 9652        }
 9653    }
 9654
 9655    pub fn select_larger_syntax_node(
 9656        &mut self,
 9657        _: &SelectLargerSyntaxNode,
 9658        window: &mut Window,
 9659        cx: &mut Context<Self>,
 9660    ) {
 9661        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9662        let buffer = self.buffer.read(cx).snapshot(cx);
 9663        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9664
 9665        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9666        let mut selected_larger_node = false;
 9667        let new_selections = old_selections
 9668            .iter()
 9669            .map(|selection| {
 9670                let old_range = selection.start..selection.end;
 9671                let mut new_range = old_range.clone();
 9672                let mut new_node = None;
 9673                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9674                {
 9675                    new_node = Some(node);
 9676                    new_range = containing_range;
 9677                    if !display_map.intersects_fold(new_range.start)
 9678                        && !display_map.intersects_fold(new_range.end)
 9679                    {
 9680                        break;
 9681                    }
 9682                }
 9683
 9684                if let Some(node) = new_node {
 9685                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9686                    // nodes. Parent and grandparent are also logged because this operation will not
 9687                    // visit nodes that have the same range as their parent.
 9688                    log::info!("Node: {node:?}");
 9689                    let parent = node.parent();
 9690                    log::info!("Parent: {parent:?}");
 9691                    let grandparent = parent.and_then(|x| x.parent());
 9692                    log::info!("Grandparent: {grandparent:?}");
 9693                }
 9694
 9695                selected_larger_node |= new_range != old_range;
 9696                Selection {
 9697                    id: selection.id,
 9698                    start: new_range.start,
 9699                    end: new_range.end,
 9700                    goal: SelectionGoal::None,
 9701                    reversed: selection.reversed,
 9702                }
 9703            })
 9704            .collect::<Vec<_>>();
 9705
 9706        if selected_larger_node {
 9707            stack.push(old_selections);
 9708            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9709                s.select(new_selections);
 9710            });
 9711        }
 9712        self.select_larger_syntax_node_stack = stack;
 9713    }
 9714
 9715    pub fn select_smaller_syntax_node(
 9716        &mut self,
 9717        _: &SelectSmallerSyntaxNode,
 9718        window: &mut Window,
 9719        cx: &mut Context<Self>,
 9720    ) {
 9721        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9722        if let Some(selections) = stack.pop() {
 9723            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9724                s.select(selections.to_vec());
 9725            });
 9726        }
 9727        self.select_larger_syntax_node_stack = stack;
 9728    }
 9729
 9730    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9731        if !EditorSettings::get_global(cx).gutter.runnables {
 9732            self.clear_tasks();
 9733            return Task::ready(());
 9734        }
 9735        let project = self.project.as_ref().map(Entity::downgrade);
 9736        cx.spawn_in(window, |this, mut cx| async move {
 9737            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9738            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9739                return;
 9740            };
 9741            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9742                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9743            }) else {
 9744                return;
 9745            };
 9746
 9747            let hide_runnables = project
 9748                .update(&mut cx, |project, cx| {
 9749                    // Do not display any test indicators in non-dev server remote projects.
 9750                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9751                })
 9752                .unwrap_or(true);
 9753            if hide_runnables {
 9754                return;
 9755            }
 9756            let new_rows =
 9757                cx.background_executor()
 9758                    .spawn({
 9759                        let snapshot = display_snapshot.clone();
 9760                        async move {
 9761                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9762                        }
 9763                    })
 9764                    .await;
 9765
 9766            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9767            this.update(&mut cx, |this, _| {
 9768                this.clear_tasks();
 9769                for (key, value) in rows {
 9770                    this.insert_tasks(key, value);
 9771                }
 9772            })
 9773            .ok();
 9774        })
 9775    }
 9776    fn fetch_runnable_ranges(
 9777        snapshot: &DisplaySnapshot,
 9778        range: Range<Anchor>,
 9779    ) -> Vec<language::RunnableRange> {
 9780        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9781    }
 9782
 9783    fn runnable_rows(
 9784        project: Entity<Project>,
 9785        snapshot: DisplaySnapshot,
 9786        runnable_ranges: Vec<RunnableRange>,
 9787        mut cx: AsyncWindowContext,
 9788    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9789        runnable_ranges
 9790            .into_iter()
 9791            .filter_map(|mut runnable| {
 9792                let tasks = cx
 9793                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9794                    .ok()?;
 9795                if tasks.is_empty() {
 9796                    return None;
 9797                }
 9798
 9799                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9800
 9801                let row = snapshot
 9802                    .buffer_snapshot
 9803                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9804                    .1
 9805                    .start
 9806                    .row;
 9807
 9808                let context_range =
 9809                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9810                Some((
 9811                    (runnable.buffer_id, row),
 9812                    RunnableTasks {
 9813                        templates: tasks,
 9814                        offset: MultiBufferOffset(runnable.run_range.start),
 9815                        context_range,
 9816                        column: point.column,
 9817                        extra_variables: runnable.extra_captures,
 9818                    },
 9819                ))
 9820            })
 9821            .collect()
 9822    }
 9823
 9824    fn templates_with_tags(
 9825        project: &Entity<Project>,
 9826        runnable: &mut Runnable,
 9827        cx: &mut App,
 9828    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9829        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9830            let (worktree_id, file) = project
 9831                .buffer_for_id(runnable.buffer, cx)
 9832                .and_then(|buffer| buffer.read(cx).file())
 9833                .map(|file| (file.worktree_id(cx), file.clone()))
 9834                .unzip();
 9835
 9836            (
 9837                project.task_store().read(cx).task_inventory().cloned(),
 9838                worktree_id,
 9839                file,
 9840            )
 9841        });
 9842
 9843        let tags = mem::take(&mut runnable.tags);
 9844        let mut tags: Vec<_> = tags
 9845            .into_iter()
 9846            .flat_map(|tag| {
 9847                let tag = tag.0.clone();
 9848                inventory
 9849                    .as_ref()
 9850                    .into_iter()
 9851                    .flat_map(|inventory| {
 9852                        inventory.read(cx).list_tasks(
 9853                            file.clone(),
 9854                            Some(runnable.language.clone()),
 9855                            worktree_id,
 9856                            cx,
 9857                        )
 9858                    })
 9859                    .filter(move |(_, template)| {
 9860                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9861                    })
 9862            })
 9863            .sorted_by_key(|(kind, _)| kind.to_owned())
 9864            .collect();
 9865        if let Some((leading_tag_source, _)) = tags.first() {
 9866            // Strongest source wins; if we have worktree tag binding, prefer that to
 9867            // global and language bindings;
 9868            // if we have a global binding, prefer that to language binding.
 9869            let first_mismatch = tags
 9870                .iter()
 9871                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9872            if let Some(index) = first_mismatch {
 9873                tags.truncate(index);
 9874            }
 9875        }
 9876
 9877        tags
 9878    }
 9879
 9880    pub fn move_to_enclosing_bracket(
 9881        &mut self,
 9882        _: &MoveToEnclosingBracket,
 9883        window: &mut Window,
 9884        cx: &mut Context<Self>,
 9885    ) {
 9886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9887            s.move_offsets_with(|snapshot, selection| {
 9888                let Some(enclosing_bracket_ranges) =
 9889                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9890                else {
 9891                    return;
 9892                };
 9893
 9894                let mut best_length = usize::MAX;
 9895                let mut best_inside = false;
 9896                let mut best_in_bracket_range = false;
 9897                let mut best_destination = None;
 9898                for (open, close) in enclosing_bracket_ranges {
 9899                    let close = close.to_inclusive();
 9900                    let length = close.end() - open.start;
 9901                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9902                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9903                        || close.contains(&selection.head());
 9904
 9905                    // If best is next to a bracket and current isn't, skip
 9906                    if !in_bracket_range && best_in_bracket_range {
 9907                        continue;
 9908                    }
 9909
 9910                    // Prefer smaller lengths unless best is inside and current isn't
 9911                    if length > best_length && (best_inside || !inside) {
 9912                        continue;
 9913                    }
 9914
 9915                    best_length = length;
 9916                    best_inside = inside;
 9917                    best_in_bracket_range = in_bracket_range;
 9918                    best_destination = Some(
 9919                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9920                            if inside {
 9921                                open.end
 9922                            } else {
 9923                                open.start
 9924                            }
 9925                        } else if inside {
 9926                            *close.start()
 9927                        } else {
 9928                            *close.end()
 9929                        },
 9930                    );
 9931                }
 9932
 9933                if let Some(destination) = best_destination {
 9934                    selection.collapse_to(destination, SelectionGoal::None);
 9935                }
 9936            })
 9937        });
 9938    }
 9939
 9940    pub fn undo_selection(
 9941        &mut self,
 9942        _: &UndoSelection,
 9943        window: &mut Window,
 9944        cx: &mut Context<Self>,
 9945    ) {
 9946        self.end_selection(window, cx);
 9947        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9948        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9949            self.change_selections(None, window, cx, |s| {
 9950                s.select_anchors(entry.selections.to_vec())
 9951            });
 9952            self.select_next_state = entry.select_next_state;
 9953            self.select_prev_state = entry.select_prev_state;
 9954            self.add_selections_state = entry.add_selections_state;
 9955            self.request_autoscroll(Autoscroll::newest(), cx);
 9956        }
 9957        self.selection_history.mode = SelectionHistoryMode::Normal;
 9958    }
 9959
 9960    pub fn redo_selection(
 9961        &mut self,
 9962        _: &RedoSelection,
 9963        window: &mut Window,
 9964        cx: &mut Context<Self>,
 9965    ) {
 9966        self.end_selection(window, cx);
 9967        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9968        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9969            self.change_selections(None, window, cx, |s| {
 9970                s.select_anchors(entry.selections.to_vec())
 9971            });
 9972            self.select_next_state = entry.select_next_state;
 9973            self.select_prev_state = entry.select_prev_state;
 9974            self.add_selections_state = entry.add_selections_state;
 9975            self.request_autoscroll(Autoscroll::newest(), cx);
 9976        }
 9977        self.selection_history.mode = SelectionHistoryMode::Normal;
 9978    }
 9979
 9980    pub fn expand_excerpts(
 9981        &mut self,
 9982        action: &ExpandExcerpts,
 9983        _: &mut Window,
 9984        cx: &mut Context<Self>,
 9985    ) {
 9986        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9987    }
 9988
 9989    pub fn expand_excerpts_down(
 9990        &mut self,
 9991        action: &ExpandExcerptsDown,
 9992        _: &mut Window,
 9993        cx: &mut Context<Self>,
 9994    ) {
 9995        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9996    }
 9997
 9998    pub fn expand_excerpts_up(
 9999        &mut self,
10000        action: &ExpandExcerptsUp,
10001        _: &mut Window,
10002        cx: &mut Context<Self>,
10003    ) {
10004        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10005    }
10006
10007    pub fn expand_excerpts_for_direction(
10008        &mut self,
10009        lines: u32,
10010        direction: ExpandExcerptDirection,
10011
10012        cx: &mut Context<Self>,
10013    ) {
10014        let selections = self.selections.disjoint_anchors();
10015
10016        let lines = if lines == 0 {
10017            EditorSettings::get_global(cx).expand_excerpt_lines
10018        } else {
10019            lines
10020        };
10021
10022        self.buffer.update(cx, |buffer, cx| {
10023            let snapshot = buffer.snapshot(cx);
10024            let mut excerpt_ids = selections
10025                .iter()
10026                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10027                .collect::<Vec<_>>();
10028            excerpt_ids.sort();
10029            excerpt_ids.dedup();
10030            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10031        })
10032    }
10033
10034    pub fn expand_excerpt(
10035        &mut self,
10036        excerpt: ExcerptId,
10037        direction: ExpandExcerptDirection,
10038        cx: &mut Context<Self>,
10039    ) {
10040        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10041        self.buffer.update(cx, |buffer, cx| {
10042            buffer.expand_excerpts([excerpt], lines, direction, cx)
10043        })
10044    }
10045
10046    pub fn go_to_singleton_buffer_point(
10047        &mut self,
10048        point: Point,
10049        window: &mut Window,
10050        cx: &mut Context<Self>,
10051    ) {
10052        self.go_to_singleton_buffer_range(point..point, window, cx);
10053    }
10054
10055    pub fn go_to_singleton_buffer_range(
10056        &mut self,
10057        range: Range<Point>,
10058        window: &mut Window,
10059        cx: &mut Context<Self>,
10060    ) {
10061        let multibuffer = self.buffer().read(cx);
10062        let Some(buffer) = multibuffer.as_singleton() else {
10063            return;
10064        };
10065        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10066            return;
10067        };
10068        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10069            return;
10070        };
10071        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10072            s.select_anchor_ranges([start..end])
10073        });
10074    }
10075
10076    fn go_to_diagnostic(
10077        &mut self,
10078        _: &GoToDiagnostic,
10079        window: &mut Window,
10080        cx: &mut Context<Self>,
10081    ) {
10082        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10083    }
10084
10085    fn go_to_prev_diagnostic(
10086        &mut self,
10087        _: &GoToPrevDiagnostic,
10088        window: &mut Window,
10089        cx: &mut Context<Self>,
10090    ) {
10091        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10092    }
10093
10094    pub fn go_to_diagnostic_impl(
10095        &mut self,
10096        direction: Direction,
10097        window: &mut Window,
10098        cx: &mut Context<Self>,
10099    ) {
10100        let buffer = self.buffer.read(cx).snapshot(cx);
10101        let selection = self.selections.newest::<usize>(cx);
10102
10103        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10104        if direction == Direction::Next {
10105            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10106                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10107                    return;
10108                };
10109                self.activate_diagnostics(
10110                    buffer_id,
10111                    popover.local_diagnostic.diagnostic.group_id,
10112                    window,
10113                    cx,
10114                );
10115                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10116                    let primary_range_start = active_diagnostics.primary_range.start;
10117                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10118                        let mut new_selection = s.newest_anchor().clone();
10119                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10120                        s.select_anchors(vec![new_selection.clone()]);
10121                    });
10122                    self.refresh_inline_completion(false, true, window, cx);
10123                }
10124                return;
10125            }
10126        }
10127
10128        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10129            active_diagnostics
10130                .primary_range
10131                .to_offset(&buffer)
10132                .to_inclusive()
10133        });
10134        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10135            if active_primary_range.contains(&selection.head()) {
10136                *active_primary_range.start()
10137            } else {
10138                selection.head()
10139            }
10140        } else {
10141            selection.head()
10142        };
10143        let snapshot = self.snapshot(window, cx);
10144        loop {
10145            let mut diagnostics;
10146            if direction == Direction::Prev {
10147                diagnostics = buffer
10148                    .diagnostics_in_range::<_, usize>(0..search_start)
10149                    .collect::<Vec<_>>();
10150                diagnostics.reverse();
10151            } else {
10152                diagnostics = buffer
10153                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10154                    .collect::<Vec<_>>();
10155            };
10156            let group = diagnostics
10157                .into_iter()
10158                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10159                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10160                // be sorted in a stable way
10161                // skip until we are at current active diagnostic, if it exists
10162                .skip_while(|entry| {
10163                    let is_in_range = match direction {
10164                        Direction::Prev => entry.range.end > search_start,
10165                        Direction::Next => entry.range.start < search_start,
10166                    };
10167                    is_in_range
10168                        && self
10169                            .active_diagnostics
10170                            .as_ref()
10171                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10172                })
10173                .find_map(|entry| {
10174                    if entry.diagnostic.is_primary
10175                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10176                        && entry.range.start != entry.range.end
10177                        // if we match with the active diagnostic, skip it
10178                        && Some(entry.diagnostic.group_id)
10179                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10180                    {
10181                        Some((entry.range, entry.diagnostic.group_id))
10182                    } else {
10183                        None
10184                    }
10185                });
10186
10187            if let Some((primary_range, group_id)) = group {
10188                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10189                    return;
10190                };
10191                self.activate_diagnostics(buffer_id, group_id, window, cx);
10192                if self.active_diagnostics.is_some() {
10193                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10194                        s.select(vec![Selection {
10195                            id: selection.id,
10196                            start: primary_range.start,
10197                            end: primary_range.start,
10198                            reversed: false,
10199                            goal: SelectionGoal::None,
10200                        }]);
10201                    });
10202                    self.refresh_inline_completion(false, true, window, cx);
10203                }
10204                break;
10205            } else {
10206                // Cycle around to the start of the buffer, potentially moving back to the start of
10207                // the currently active diagnostic.
10208                active_primary_range.take();
10209                if direction == Direction::Prev {
10210                    if search_start == buffer.len() {
10211                        break;
10212                    } else {
10213                        search_start = buffer.len();
10214                    }
10215                } else if search_start == 0 {
10216                    break;
10217                } else {
10218                    search_start = 0;
10219                }
10220            }
10221        }
10222    }
10223
10224    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10225        let snapshot = self.snapshot(window, cx);
10226        let selection = self.selections.newest::<Point>(cx);
10227        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10228    }
10229
10230    fn go_to_hunk_after_position(
10231        &mut self,
10232        snapshot: &EditorSnapshot,
10233        position: Point,
10234        window: &mut Window,
10235        cx: &mut Context<Editor>,
10236    ) -> Option<MultiBufferDiffHunk> {
10237        let mut hunk = snapshot
10238            .buffer_snapshot
10239            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10240            .find(|hunk| hunk.row_range.start.0 > position.row);
10241        if hunk.is_none() {
10242            hunk = snapshot
10243                .buffer_snapshot
10244                .diff_hunks_in_range(Point::zero()..position)
10245                .find(|hunk| hunk.row_range.end.0 < position.row)
10246        }
10247        if let Some(hunk) = &hunk {
10248            let destination = Point::new(hunk.row_range.start.0, 0);
10249            self.unfold_ranges(&[destination..destination], false, false, cx);
10250            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10251                s.select_ranges(vec![destination..destination]);
10252            });
10253        }
10254
10255        hunk
10256    }
10257
10258    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10259        let snapshot = self.snapshot(window, cx);
10260        let selection = self.selections.newest::<Point>(cx);
10261        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10262    }
10263
10264    fn go_to_hunk_before_position(
10265        &mut self,
10266        snapshot: &EditorSnapshot,
10267        position: Point,
10268        window: &mut Window,
10269        cx: &mut Context<Editor>,
10270    ) -> Option<MultiBufferDiffHunk> {
10271        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10272        if hunk.is_none() {
10273            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10274        }
10275        if let Some(hunk) = &hunk {
10276            let destination = Point::new(hunk.row_range.start.0, 0);
10277            self.unfold_ranges(&[destination..destination], false, false, cx);
10278            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10279                s.select_ranges(vec![destination..destination]);
10280            });
10281        }
10282
10283        hunk
10284    }
10285
10286    pub fn go_to_definition(
10287        &mut self,
10288        _: &GoToDefinition,
10289        window: &mut Window,
10290        cx: &mut Context<Self>,
10291    ) -> Task<Result<Navigated>> {
10292        let definition =
10293            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10294        cx.spawn_in(window, |editor, mut cx| async move {
10295            if definition.await? == Navigated::Yes {
10296                return Ok(Navigated::Yes);
10297            }
10298            match editor.update_in(&mut cx, |editor, window, cx| {
10299                editor.find_all_references(&FindAllReferences, window, cx)
10300            })? {
10301                Some(references) => references.await,
10302                None => Ok(Navigated::No),
10303            }
10304        })
10305    }
10306
10307    pub fn go_to_declaration(
10308        &mut self,
10309        _: &GoToDeclaration,
10310        window: &mut Window,
10311        cx: &mut Context<Self>,
10312    ) -> Task<Result<Navigated>> {
10313        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10314    }
10315
10316    pub fn go_to_declaration_split(
10317        &mut self,
10318        _: &GoToDeclaration,
10319        window: &mut Window,
10320        cx: &mut Context<Self>,
10321    ) -> Task<Result<Navigated>> {
10322        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10323    }
10324
10325    pub fn go_to_implementation(
10326        &mut self,
10327        _: &GoToImplementation,
10328        window: &mut Window,
10329        cx: &mut Context<Self>,
10330    ) -> Task<Result<Navigated>> {
10331        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10332    }
10333
10334    pub fn go_to_implementation_split(
10335        &mut self,
10336        _: &GoToImplementationSplit,
10337        window: &mut Window,
10338        cx: &mut Context<Self>,
10339    ) -> Task<Result<Navigated>> {
10340        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10341    }
10342
10343    pub fn go_to_type_definition(
10344        &mut self,
10345        _: &GoToTypeDefinition,
10346        window: &mut Window,
10347        cx: &mut Context<Self>,
10348    ) -> Task<Result<Navigated>> {
10349        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10350    }
10351
10352    pub fn go_to_definition_split(
10353        &mut self,
10354        _: &GoToDefinitionSplit,
10355        window: &mut Window,
10356        cx: &mut Context<Self>,
10357    ) -> Task<Result<Navigated>> {
10358        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10359    }
10360
10361    pub fn go_to_type_definition_split(
10362        &mut self,
10363        _: &GoToTypeDefinitionSplit,
10364        window: &mut Window,
10365        cx: &mut Context<Self>,
10366    ) -> Task<Result<Navigated>> {
10367        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10368    }
10369
10370    fn go_to_definition_of_kind(
10371        &mut self,
10372        kind: GotoDefinitionKind,
10373        split: bool,
10374        window: &mut Window,
10375        cx: &mut Context<Self>,
10376    ) -> Task<Result<Navigated>> {
10377        let Some(provider) = self.semantics_provider.clone() else {
10378            return Task::ready(Ok(Navigated::No));
10379        };
10380        let head = self.selections.newest::<usize>(cx).head();
10381        let buffer = self.buffer.read(cx);
10382        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10383            text_anchor
10384        } else {
10385            return Task::ready(Ok(Navigated::No));
10386        };
10387
10388        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10389            return Task::ready(Ok(Navigated::No));
10390        };
10391
10392        cx.spawn_in(window, |editor, mut cx| async move {
10393            let definitions = definitions.await?;
10394            let navigated = editor
10395                .update_in(&mut cx, |editor, window, cx| {
10396                    editor.navigate_to_hover_links(
10397                        Some(kind),
10398                        definitions
10399                            .into_iter()
10400                            .filter(|location| {
10401                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10402                            })
10403                            .map(HoverLink::Text)
10404                            .collect::<Vec<_>>(),
10405                        split,
10406                        window,
10407                        cx,
10408                    )
10409                })?
10410                .await?;
10411            anyhow::Ok(navigated)
10412        })
10413    }
10414
10415    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10416        let selection = self.selections.newest_anchor();
10417        let head = selection.head();
10418        let tail = selection.tail();
10419
10420        let Some((buffer, start_position)) =
10421            self.buffer.read(cx).text_anchor_for_position(head, cx)
10422        else {
10423            return;
10424        };
10425
10426        let end_position = if head != tail {
10427            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10428                return;
10429            };
10430            Some(pos)
10431        } else {
10432            None
10433        };
10434
10435        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10436            let url = if let Some(end_pos) = end_position {
10437                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10438            } else {
10439                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10440            };
10441
10442            if let Some(url) = url {
10443                editor.update(&mut cx, |_, cx| {
10444                    cx.open_url(&url);
10445                })
10446            } else {
10447                Ok(())
10448            }
10449        });
10450
10451        url_finder.detach();
10452    }
10453
10454    pub fn open_selected_filename(
10455        &mut self,
10456        _: &OpenSelectedFilename,
10457        window: &mut Window,
10458        cx: &mut Context<Self>,
10459    ) {
10460        let Some(workspace) = self.workspace() else {
10461            return;
10462        };
10463
10464        let position = self.selections.newest_anchor().head();
10465
10466        let Some((buffer, buffer_position)) =
10467            self.buffer.read(cx).text_anchor_for_position(position, cx)
10468        else {
10469            return;
10470        };
10471
10472        let project = self.project.clone();
10473
10474        cx.spawn_in(window, |_, mut cx| async move {
10475            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10476
10477            if let Some((_, path)) = result {
10478                workspace
10479                    .update_in(&mut cx, |workspace, window, cx| {
10480                        workspace.open_resolved_path(path, window, cx)
10481                    })?
10482                    .await?;
10483            }
10484            anyhow::Ok(())
10485        })
10486        .detach();
10487    }
10488
10489    pub(crate) fn navigate_to_hover_links(
10490        &mut self,
10491        kind: Option<GotoDefinitionKind>,
10492        mut definitions: Vec<HoverLink>,
10493        split: bool,
10494        window: &mut Window,
10495        cx: &mut Context<Editor>,
10496    ) -> Task<Result<Navigated>> {
10497        // If there is one definition, just open it directly
10498        if definitions.len() == 1 {
10499            let definition = definitions.pop().unwrap();
10500
10501            enum TargetTaskResult {
10502                Location(Option<Location>),
10503                AlreadyNavigated,
10504            }
10505
10506            let target_task = match definition {
10507                HoverLink::Text(link) => {
10508                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10509                }
10510                HoverLink::InlayHint(lsp_location, server_id) => {
10511                    let computation =
10512                        self.compute_target_location(lsp_location, server_id, window, cx);
10513                    cx.background_executor().spawn(async move {
10514                        let location = computation.await?;
10515                        Ok(TargetTaskResult::Location(location))
10516                    })
10517                }
10518                HoverLink::Url(url) => {
10519                    cx.open_url(&url);
10520                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10521                }
10522                HoverLink::File(path) => {
10523                    if let Some(workspace) = self.workspace() {
10524                        cx.spawn_in(window, |_, mut cx| async move {
10525                            workspace
10526                                .update_in(&mut cx, |workspace, window, cx| {
10527                                    workspace.open_resolved_path(path, window, cx)
10528                                })?
10529                                .await
10530                                .map(|_| TargetTaskResult::AlreadyNavigated)
10531                        })
10532                    } else {
10533                        Task::ready(Ok(TargetTaskResult::Location(None)))
10534                    }
10535                }
10536            };
10537            cx.spawn_in(window, |editor, mut cx| async move {
10538                let target = match target_task.await.context("target resolution task")? {
10539                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10540                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10541                    TargetTaskResult::Location(Some(target)) => target,
10542                };
10543
10544                editor.update_in(&mut cx, |editor, window, cx| {
10545                    let Some(workspace) = editor.workspace() else {
10546                        return Navigated::No;
10547                    };
10548                    let pane = workspace.read(cx).active_pane().clone();
10549
10550                    let range = target.range.to_point(target.buffer.read(cx));
10551                    let range = editor.range_for_match(&range);
10552                    let range = collapse_multiline_range(range);
10553
10554                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10555                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10556                    } else {
10557                        window.defer(cx, move |window, cx| {
10558                            let target_editor: Entity<Self> =
10559                                workspace.update(cx, |workspace, cx| {
10560                                    let pane = if split {
10561                                        workspace.adjacent_pane(window, cx)
10562                                    } else {
10563                                        workspace.active_pane().clone()
10564                                    };
10565
10566                                    workspace.open_project_item(
10567                                        pane,
10568                                        target.buffer.clone(),
10569                                        true,
10570                                        true,
10571                                        window,
10572                                        cx,
10573                                    )
10574                                });
10575                            target_editor.update(cx, |target_editor, cx| {
10576                                // When selecting a definition in a different buffer, disable the nav history
10577                                // to avoid creating a history entry at the previous cursor location.
10578                                pane.update(cx, |pane, _| pane.disable_history());
10579                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10580                                pane.update(cx, |pane, _| pane.enable_history());
10581                            });
10582                        });
10583                    }
10584                    Navigated::Yes
10585                })
10586            })
10587        } else if !definitions.is_empty() {
10588            cx.spawn_in(window, |editor, mut cx| async move {
10589                let (title, location_tasks, workspace) = editor
10590                    .update_in(&mut cx, |editor, window, cx| {
10591                        let tab_kind = match kind {
10592                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10593                            _ => "Definitions",
10594                        };
10595                        let title = definitions
10596                            .iter()
10597                            .find_map(|definition| match definition {
10598                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10599                                    let buffer = origin.buffer.read(cx);
10600                                    format!(
10601                                        "{} for {}",
10602                                        tab_kind,
10603                                        buffer
10604                                            .text_for_range(origin.range.clone())
10605                                            .collect::<String>()
10606                                    )
10607                                }),
10608                                HoverLink::InlayHint(_, _) => None,
10609                                HoverLink::Url(_) => None,
10610                                HoverLink::File(_) => None,
10611                            })
10612                            .unwrap_or(tab_kind.to_string());
10613                        let location_tasks = definitions
10614                            .into_iter()
10615                            .map(|definition| match definition {
10616                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10617                                HoverLink::InlayHint(lsp_location, server_id) => editor
10618                                    .compute_target_location(lsp_location, server_id, window, cx),
10619                                HoverLink::Url(_) => Task::ready(Ok(None)),
10620                                HoverLink::File(_) => Task::ready(Ok(None)),
10621                            })
10622                            .collect::<Vec<_>>();
10623                        (title, location_tasks, editor.workspace().clone())
10624                    })
10625                    .context("location tasks preparation")?;
10626
10627                let locations = future::join_all(location_tasks)
10628                    .await
10629                    .into_iter()
10630                    .filter_map(|location| location.transpose())
10631                    .collect::<Result<_>>()
10632                    .context("location tasks")?;
10633
10634                let Some(workspace) = workspace else {
10635                    return Ok(Navigated::No);
10636                };
10637                let opened = workspace
10638                    .update_in(&mut cx, |workspace, window, cx| {
10639                        Self::open_locations_in_multibuffer(
10640                            workspace,
10641                            locations,
10642                            title,
10643                            split,
10644                            MultibufferSelectionMode::First,
10645                            window,
10646                            cx,
10647                        )
10648                    })
10649                    .ok();
10650
10651                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10652            })
10653        } else {
10654            Task::ready(Ok(Navigated::No))
10655        }
10656    }
10657
10658    fn compute_target_location(
10659        &self,
10660        lsp_location: lsp::Location,
10661        server_id: LanguageServerId,
10662        window: &mut Window,
10663        cx: &mut Context<Self>,
10664    ) -> Task<anyhow::Result<Option<Location>>> {
10665        let Some(project) = self.project.clone() else {
10666            return Task::ready(Ok(None));
10667        };
10668
10669        cx.spawn_in(window, move |editor, mut cx| async move {
10670            let location_task = editor.update(&mut cx, |_, cx| {
10671                project.update(cx, |project, cx| {
10672                    let language_server_name = project
10673                        .language_server_statuses(cx)
10674                        .find(|(id, _)| server_id == *id)
10675                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10676                    language_server_name.map(|language_server_name| {
10677                        project.open_local_buffer_via_lsp(
10678                            lsp_location.uri.clone(),
10679                            server_id,
10680                            language_server_name,
10681                            cx,
10682                        )
10683                    })
10684                })
10685            })?;
10686            let location = match location_task {
10687                Some(task) => Some({
10688                    let target_buffer_handle = task.await.context("open local buffer")?;
10689                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10690                        let target_start = target_buffer
10691                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10692                        let target_end = target_buffer
10693                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10694                        target_buffer.anchor_after(target_start)
10695                            ..target_buffer.anchor_before(target_end)
10696                    })?;
10697                    Location {
10698                        buffer: target_buffer_handle,
10699                        range,
10700                    }
10701                }),
10702                None => None,
10703            };
10704            Ok(location)
10705        })
10706    }
10707
10708    pub fn find_all_references(
10709        &mut self,
10710        _: &FindAllReferences,
10711        window: &mut Window,
10712        cx: &mut Context<Self>,
10713    ) -> Option<Task<Result<Navigated>>> {
10714        let selection = self.selections.newest::<usize>(cx);
10715        let multi_buffer = self.buffer.read(cx);
10716        let head = selection.head();
10717
10718        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10719        let head_anchor = multi_buffer_snapshot.anchor_at(
10720            head,
10721            if head < selection.tail() {
10722                Bias::Right
10723            } else {
10724                Bias::Left
10725            },
10726        );
10727
10728        match self
10729            .find_all_references_task_sources
10730            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10731        {
10732            Ok(_) => {
10733                log::info!(
10734                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10735                );
10736                return None;
10737            }
10738            Err(i) => {
10739                self.find_all_references_task_sources.insert(i, head_anchor);
10740            }
10741        }
10742
10743        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10744        let workspace = self.workspace()?;
10745        let project = workspace.read(cx).project().clone();
10746        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10747        Some(cx.spawn_in(window, |editor, mut cx| async move {
10748            let _cleanup = defer({
10749                let mut cx = cx.clone();
10750                move || {
10751                    let _ = editor.update(&mut cx, |editor, _| {
10752                        if let Ok(i) =
10753                            editor
10754                                .find_all_references_task_sources
10755                                .binary_search_by(|anchor| {
10756                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10757                                })
10758                        {
10759                            editor.find_all_references_task_sources.remove(i);
10760                        }
10761                    });
10762                }
10763            });
10764
10765            let locations = references.await?;
10766            if locations.is_empty() {
10767                return anyhow::Ok(Navigated::No);
10768            }
10769
10770            workspace.update_in(&mut cx, |workspace, window, cx| {
10771                let title = locations
10772                    .first()
10773                    .as_ref()
10774                    .map(|location| {
10775                        let buffer = location.buffer.read(cx);
10776                        format!(
10777                            "References to `{}`",
10778                            buffer
10779                                .text_for_range(location.range.clone())
10780                                .collect::<String>()
10781                        )
10782                    })
10783                    .unwrap();
10784                Self::open_locations_in_multibuffer(
10785                    workspace,
10786                    locations,
10787                    title,
10788                    false,
10789                    MultibufferSelectionMode::First,
10790                    window,
10791                    cx,
10792                );
10793                Navigated::Yes
10794            })
10795        }))
10796    }
10797
10798    /// Opens a multibuffer with the given project locations in it
10799    pub fn open_locations_in_multibuffer(
10800        workspace: &mut Workspace,
10801        mut locations: Vec<Location>,
10802        title: String,
10803        split: bool,
10804        multibuffer_selection_mode: MultibufferSelectionMode,
10805        window: &mut Window,
10806        cx: &mut Context<Workspace>,
10807    ) {
10808        // If there are multiple definitions, open them in a multibuffer
10809        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10810        let mut locations = locations.into_iter().peekable();
10811        let mut ranges = Vec::new();
10812        let capability = workspace.project().read(cx).capability();
10813
10814        let excerpt_buffer = cx.new(|cx| {
10815            let mut multibuffer = MultiBuffer::new(capability);
10816            while let Some(location) = locations.next() {
10817                let buffer = location.buffer.read(cx);
10818                let mut ranges_for_buffer = Vec::new();
10819                let range = location.range.to_offset(buffer);
10820                ranges_for_buffer.push(range.clone());
10821
10822                while let Some(next_location) = locations.peek() {
10823                    if next_location.buffer == location.buffer {
10824                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10825                        locations.next();
10826                    } else {
10827                        break;
10828                    }
10829                }
10830
10831                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10832                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10833                    location.buffer.clone(),
10834                    ranges_for_buffer,
10835                    DEFAULT_MULTIBUFFER_CONTEXT,
10836                    cx,
10837                ))
10838            }
10839
10840            multibuffer.with_title(title)
10841        });
10842
10843        let editor = cx.new(|cx| {
10844            Editor::for_multibuffer(
10845                excerpt_buffer,
10846                Some(workspace.project().clone()),
10847                true,
10848                window,
10849                cx,
10850            )
10851        });
10852        editor.update(cx, |editor, cx| {
10853            match multibuffer_selection_mode {
10854                MultibufferSelectionMode::First => {
10855                    if let Some(first_range) = ranges.first() {
10856                        editor.change_selections(None, window, cx, |selections| {
10857                            selections.clear_disjoint();
10858                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10859                        });
10860                    }
10861                    editor.highlight_background::<Self>(
10862                        &ranges,
10863                        |theme| theme.editor_highlighted_line_background,
10864                        cx,
10865                    );
10866                }
10867                MultibufferSelectionMode::All => {
10868                    editor.change_selections(None, window, cx, |selections| {
10869                        selections.clear_disjoint();
10870                        selections.select_anchor_ranges(ranges);
10871                    });
10872                }
10873            }
10874            editor.register_buffers_with_language_servers(cx);
10875        });
10876
10877        let item = Box::new(editor);
10878        let item_id = item.item_id();
10879
10880        if split {
10881            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10882        } else {
10883            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10884                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10885                    pane.close_current_preview_item(window, cx)
10886                } else {
10887                    None
10888                }
10889            });
10890            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10891        }
10892        workspace.active_pane().update(cx, |pane, cx| {
10893            pane.set_preview_item_id(Some(item_id), cx);
10894        });
10895    }
10896
10897    pub fn rename(
10898        &mut self,
10899        _: &Rename,
10900        window: &mut Window,
10901        cx: &mut Context<Self>,
10902    ) -> Option<Task<Result<()>>> {
10903        use language::ToOffset as _;
10904
10905        let provider = self.semantics_provider.clone()?;
10906        let selection = self.selections.newest_anchor().clone();
10907        let (cursor_buffer, cursor_buffer_position) = self
10908            .buffer
10909            .read(cx)
10910            .text_anchor_for_position(selection.head(), cx)?;
10911        let (tail_buffer, cursor_buffer_position_end) = self
10912            .buffer
10913            .read(cx)
10914            .text_anchor_for_position(selection.tail(), cx)?;
10915        if tail_buffer != cursor_buffer {
10916            return None;
10917        }
10918
10919        let snapshot = cursor_buffer.read(cx).snapshot();
10920        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10921        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10922        let prepare_rename = provider
10923            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10924            .unwrap_or_else(|| Task::ready(Ok(None)));
10925        drop(snapshot);
10926
10927        Some(cx.spawn_in(window, |this, mut cx| async move {
10928            let rename_range = if let Some(range) = prepare_rename.await? {
10929                Some(range)
10930            } else {
10931                this.update(&mut cx, |this, cx| {
10932                    let buffer = this.buffer.read(cx).snapshot(cx);
10933                    let mut buffer_highlights = this
10934                        .document_highlights_for_position(selection.head(), &buffer)
10935                        .filter(|highlight| {
10936                            highlight.start.excerpt_id == selection.head().excerpt_id
10937                                && highlight.end.excerpt_id == selection.head().excerpt_id
10938                        });
10939                    buffer_highlights
10940                        .next()
10941                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10942                })?
10943            };
10944            if let Some(rename_range) = rename_range {
10945                this.update_in(&mut cx, |this, window, cx| {
10946                    let snapshot = cursor_buffer.read(cx).snapshot();
10947                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10948                    let cursor_offset_in_rename_range =
10949                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10950                    let cursor_offset_in_rename_range_end =
10951                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10952
10953                    this.take_rename(false, window, cx);
10954                    let buffer = this.buffer.read(cx).read(cx);
10955                    let cursor_offset = selection.head().to_offset(&buffer);
10956                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10957                    let rename_end = rename_start + rename_buffer_range.len();
10958                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10959                    let mut old_highlight_id = None;
10960                    let old_name: Arc<str> = buffer
10961                        .chunks(rename_start..rename_end, true)
10962                        .map(|chunk| {
10963                            if old_highlight_id.is_none() {
10964                                old_highlight_id = chunk.syntax_highlight_id;
10965                            }
10966                            chunk.text
10967                        })
10968                        .collect::<String>()
10969                        .into();
10970
10971                    drop(buffer);
10972
10973                    // Position the selection in the rename editor so that it matches the current selection.
10974                    this.show_local_selections = false;
10975                    let rename_editor = cx.new(|cx| {
10976                        let mut editor = Editor::single_line(window, cx);
10977                        editor.buffer.update(cx, |buffer, cx| {
10978                            buffer.edit([(0..0, old_name.clone())], None, cx)
10979                        });
10980                        let rename_selection_range = match cursor_offset_in_rename_range
10981                            .cmp(&cursor_offset_in_rename_range_end)
10982                        {
10983                            Ordering::Equal => {
10984                                editor.select_all(&SelectAll, window, cx);
10985                                return editor;
10986                            }
10987                            Ordering::Less => {
10988                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10989                            }
10990                            Ordering::Greater => {
10991                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10992                            }
10993                        };
10994                        if rename_selection_range.end > old_name.len() {
10995                            editor.select_all(&SelectAll, window, cx);
10996                        } else {
10997                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10998                                s.select_ranges([rename_selection_range]);
10999                            });
11000                        }
11001                        editor
11002                    });
11003                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11004                        if e == &EditorEvent::Focused {
11005                            cx.emit(EditorEvent::FocusedIn)
11006                        }
11007                    })
11008                    .detach();
11009
11010                    let write_highlights =
11011                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11012                    let read_highlights =
11013                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11014                    let ranges = write_highlights
11015                        .iter()
11016                        .flat_map(|(_, ranges)| ranges.iter())
11017                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11018                        .cloned()
11019                        .collect();
11020
11021                    this.highlight_text::<Rename>(
11022                        ranges,
11023                        HighlightStyle {
11024                            fade_out: Some(0.6),
11025                            ..Default::default()
11026                        },
11027                        cx,
11028                    );
11029                    let rename_focus_handle = rename_editor.focus_handle(cx);
11030                    window.focus(&rename_focus_handle);
11031                    let block_id = this.insert_blocks(
11032                        [BlockProperties {
11033                            style: BlockStyle::Flex,
11034                            placement: BlockPlacement::Below(range.start),
11035                            height: 1,
11036                            render: Arc::new({
11037                                let rename_editor = rename_editor.clone();
11038                                move |cx: &mut BlockContext| {
11039                                    let mut text_style = cx.editor_style.text.clone();
11040                                    if let Some(highlight_style) = old_highlight_id
11041                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11042                                    {
11043                                        text_style = text_style.highlight(highlight_style);
11044                                    }
11045                                    div()
11046                                        .block_mouse_down()
11047                                        .pl(cx.anchor_x)
11048                                        .child(EditorElement::new(
11049                                            &rename_editor,
11050                                            EditorStyle {
11051                                                background: cx.theme().system().transparent,
11052                                                local_player: cx.editor_style.local_player,
11053                                                text: text_style,
11054                                                scrollbar_width: cx.editor_style.scrollbar_width,
11055                                                syntax: cx.editor_style.syntax.clone(),
11056                                                status: cx.editor_style.status.clone(),
11057                                                inlay_hints_style: HighlightStyle {
11058                                                    font_weight: Some(FontWeight::BOLD),
11059                                                    ..make_inlay_hints_style(cx.app)
11060                                                },
11061                                                inline_completion_styles: make_suggestion_styles(
11062                                                    cx.app,
11063                                                ),
11064                                                ..EditorStyle::default()
11065                                            },
11066                                        ))
11067                                        .into_any_element()
11068                                }
11069                            }),
11070                            priority: 0,
11071                        }],
11072                        Some(Autoscroll::fit()),
11073                        cx,
11074                    )[0];
11075                    this.pending_rename = Some(RenameState {
11076                        range,
11077                        old_name,
11078                        editor: rename_editor,
11079                        block_id,
11080                    });
11081                })?;
11082            }
11083
11084            Ok(())
11085        }))
11086    }
11087
11088    pub fn confirm_rename(
11089        &mut self,
11090        _: &ConfirmRename,
11091        window: &mut Window,
11092        cx: &mut Context<Self>,
11093    ) -> Option<Task<Result<()>>> {
11094        let rename = self.take_rename(false, window, cx)?;
11095        let workspace = self.workspace()?.downgrade();
11096        let (buffer, start) = self
11097            .buffer
11098            .read(cx)
11099            .text_anchor_for_position(rename.range.start, cx)?;
11100        let (end_buffer, _) = self
11101            .buffer
11102            .read(cx)
11103            .text_anchor_for_position(rename.range.end, cx)?;
11104        if buffer != end_buffer {
11105            return None;
11106        }
11107
11108        let old_name = rename.old_name;
11109        let new_name = rename.editor.read(cx).text(cx);
11110
11111        let rename = self.semantics_provider.as_ref()?.perform_rename(
11112            &buffer,
11113            start,
11114            new_name.clone(),
11115            cx,
11116        )?;
11117
11118        Some(cx.spawn_in(window, |editor, mut cx| async move {
11119            let project_transaction = rename.await?;
11120            Self::open_project_transaction(
11121                &editor,
11122                workspace,
11123                project_transaction,
11124                format!("Rename: {}{}", old_name, new_name),
11125                cx.clone(),
11126            )
11127            .await?;
11128
11129            editor.update(&mut cx, |editor, cx| {
11130                editor.refresh_document_highlights(cx);
11131            })?;
11132            Ok(())
11133        }))
11134    }
11135
11136    fn take_rename(
11137        &mut self,
11138        moving_cursor: bool,
11139        window: &mut Window,
11140        cx: &mut Context<Self>,
11141    ) -> Option<RenameState> {
11142        let rename = self.pending_rename.take()?;
11143        if rename.editor.focus_handle(cx).is_focused(window) {
11144            window.focus(&self.focus_handle);
11145        }
11146
11147        self.remove_blocks(
11148            [rename.block_id].into_iter().collect(),
11149            Some(Autoscroll::fit()),
11150            cx,
11151        );
11152        self.clear_highlights::<Rename>(cx);
11153        self.show_local_selections = true;
11154
11155        if moving_cursor {
11156            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11157                editor.selections.newest::<usize>(cx).head()
11158            });
11159
11160            // Update the selection to match the position of the selection inside
11161            // the rename editor.
11162            let snapshot = self.buffer.read(cx).read(cx);
11163            let rename_range = rename.range.to_offset(&snapshot);
11164            let cursor_in_editor = snapshot
11165                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11166                .min(rename_range.end);
11167            drop(snapshot);
11168
11169            self.change_selections(None, window, cx, |s| {
11170                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11171            });
11172        } else {
11173            self.refresh_document_highlights(cx);
11174        }
11175
11176        Some(rename)
11177    }
11178
11179    pub fn pending_rename(&self) -> Option<&RenameState> {
11180        self.pending_rename.as_ref()
11181    }
11182
11183    fn format(
11184        &mut self,
11185        _: &Format,
11186        window: &mut Window,
11187        cx: &mut Context<Self>,
11188    ) -> Option<Task<Result<()>>> {
11189        let project = match &self.project {
11190            Some(project) => project.clone(),
11191            None => return None,
11192        };
11193
11194        Some(self.perform_format(
11195            project,
11196            FormatTrigger::Manual,
11197            FormatTarget::Buffers,
11198            window,
11199            cx,
11200        ))
11201    }
11202
11203    fn format_selections(
11204        &mut self,
11205        _: &FormatSelections,
11206        window: &mut Window,
11207        cx: &mut Context<Self>,
11208    ) -> Option<Task<Result<()>>> {
11209        let project = match &self.project {
11210            Some(project) => project.clone(),
11211            None => return None,
11212        };
11213
11214        let ranges = self
11215            .selections
11216            .all_adjusted(cx)
11217            .into_iter()
11218            .map(|selection| selection.range())
11219            .collect_vec();
11220
11221        Some(self.perform_format(
11222            project,
11223            FormatTrigger::Manual,
11224            FormatTarget::Ranges(ranges),
11225            window,
11226            cx,
11227        ))
11228    }
11229
11230    fn perform_format(
11231        &mut self,
11232        project: Entity<Project>,
11233        trigger: FormatTrigger,
11234        target: FormatTarget,
11235        window: &mut Window,
11236        cx: &mut Context<Self>,
11237    ) -> Task<Result<()>> {
11238        let buffer = self.buffer.clone();
11239        let (buffers, target) = match target {
11240            FormatTarget::Buffers => {
11241                let mut buffers = buffer.read(cx).all_buffers();
11242                if trigger == FormatTrigger::Save {
11243                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11244                }
11245                (buffers, LspFormatTarget::Buffers)
11246            }
11247            FormatTarget::Ranges(selection_ranges) => {
11248                let multi_buffer = buffer.read(cx);
11249                let snapshot = multi_buffer.read(cx);
11250                let mut buffers = HashSet::default();
11251                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11252                    BTreeMap::new();
11253                for selection_range in selection_ranges {
11254                    for (buffer, buffer_range, _) in
11255                        snapshot.range_to_buffer_ranges(selection_range)
11256                    {
11257                        let buffer_id = buffer.remote_id();
11258                        let start = buffer.anchor_before(buffer_range.start);
11259                        let end = buffer.anchor_after(buffer_range.end);
11260                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11261                        buffer_id_to_ranges
11262                            .entry(buffer_id)
11263                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11264                            .or_insert_with(|| vec![start..end]);
11265                    }
11266                }
11267                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11268            }
11269        };
11270
11271        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11272        let format = project.update(cx, |project, cx| {
11273            project.format(buffers, target, true, trigger, cx)
11274        });
11275
11276        cx.spawn_in(window, |_, mut cx| async move {
11277            let transaction = futures::select_biased! {
11278                () = timeout => {
11279                    log::warn!("timed out waiting for formatting");
11280                    None
11281                }
11282                transaction = format.log_err().fuse() => transaction,
11283            };
11284
11285            buffer
11286                .update(&mut cx, |buffer, cx| {
11287                    if let Some(transaction) = transaction {
11288                        if !buffer.is_singleton() {
11289                            buffer.push_transaction(&transaction.0, cx);
11290                        }
11291                    }
11292
11293                    cx.notify();
11294                })
11295                .ok();
11296
11297            Ok(())
11298        })
11299    }
11300
11301    fn restart_language_server(
11302        &mut self,
11303        _: &RestartLanguageServer,
11304        _: &mut Window,
11305        cx: &mut Context<Self>,
11306    ) {
11307        if let Some(project) = self.project.clone() {
11308            self.buffer.update(cx, |multi_buffer, cx| {
11309                project.update(cx, |project, cx| {
11310                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11311                });
11312            })
11313        }
11314    }
11315
11316    fn cancel_language_server_work(
11317        &mut self,
11318        _: &actions::CancelLanguageServerWork,
11319        _: &mut Window,
11320        cx: &mut Context<Self>,
11321    ) {
11322        if let Some(project) = self.project.clone() {
11323            self.buffer.update(cx, |multi_buffer, cx| {
11324                project.update(cx, |project, cx| {
11325                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11326                });
11327            })
11328        }
11329    }
11330
11331    fn show_character_palette(
11332        &mut self,
11333        _: &ShowCharacterPalette,
11334        window: &mut Window,
11335        _: &mut Context<Self>,
11336    ) {
11337        window.show_character_palette();
11338    }
11339
11340    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11341        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11342            let buffer = self.buffer.read(cx).snapshot(cx);
11343            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11344            let is_valid = buffer
11345                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11346                .any(|entry| {
11347                    entry.diagnostic.is_primary
11348                        && !entry.range.is_empty()
11349                        && entry.range.start == primary_range_start
11350                        && entry.diagnostic.message == active_diagnostics.primary_message
11351                });
11352
11353            if is_valid != active_diagnostics.is_valid {
11354                active_diagnostics.is_valid = is_valid;
11355                let mut new_styles = HashMap::default();
11356                for (block_id, diagnostic) in &active_diagnostics.blocks {
11357                    new_styles.insert(
11358                        *block_id,
11359                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11360                    );
11361                }
11362                self.display_map.update(cx, |display_map, _cx| {
11363                    display_map.replace_blocks(new_styles)
11364                });
11365            }
11366        }
11367    }
11368
11369    fn activate_diagnostics(
11370        &mut self,
11371        buffer_id: BufferId,
11372        group_id: usize,
11373        window: &mut Window,
11374        cx: &mut Context<Self>,
11375    ) {
11376        self.dismiss_diagnostics(cx);
11377        let snapshot = self.snapshot(window, cx);
11378        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11379            let buffer = self.buffer.read(cx).snapshot(cx);
11380
11381            let mut primary_range = None;
11382            let mut primary_message = None;
11383            let diagnostic_group = buffer
11384                .diagnostic_group(buffer_id, group_id)
11385                .filter_map(|entry| {
11386                    let start = entry.range.start;
11387                    let end = entry.range.end;
11388                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11389                        && (start.row == end.row
11390                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11391                    {
11392                        return None;
11393                    }
11394                    if entry.diagnostic.is_primary {
11395                        primary_range = Some(entry.range.clone());
11396                        primary_message = Some(entry.diagnostic.message.clone());
11397                    }
11398                    Some(entry)
11399                })
11400                .collect::<Vec<_>>();
11401            let primary_range = primary_range?;
11402            let primary_message = primary_message?;
11403
11404            let blocks = display_map
11405                .insert_blocks(
11406                    diagnostic_group.iter().map(|entry| {
11407                        let diagnostic = entry.diagnostic.clone();
11408                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11409                        BlockProperties {
11410                            style: BlockStyle::Fixed,
11411                            placement: BlockPlacement::Below(
11412                                buffer.anchor_after(entry.range.start),
11413                            ),
11414                            height: message_height,
11415                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11416                            priority: 0,
11417                        }
11418                    }),
11419                    cx,
11420                )
11421                .into_iter()
11422                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11423                .collect();
11424
11425            Some(ActiveDiagnosticGroup {
11426                primary_range: buffer.anchor_before(primary_range.start)
11427                    ..buffer.anchor_after(primary_range.end),
11428                primary_message,
11429                group_id,
11430                blocks,
11431                is_valid: true,
11432            })
11433        });
11434    }
11435
11436    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11437        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11438            self.display_map.update(cx, |display_map, cx| {
11439                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11440            });
11441            cx.notify();
11442        }
11443    }
11444
11445    pub fn set_selections_from_remote(
11446        &mut self,
11447        selections: Vec<Selection<Anchor>>,
11448        pending_selection: Option<Selection<Anchor>>,
11449        window: &mut Window,
11450        cx: &mut Context<Self>,
11451    ) {
11452        let old_cursor_position = self.selections.newest_anchor().head();
11453        self.selections.change_with(cx, |s| {
11454            s.select_anchors(selections);
11455            if let Some(pending_selection) = pending_selection {
11456                s.set_pending(pending_selection, SelectMode::Character);
11457            } else {
11458                s.clear_pending();
11459            }
11460        });
11461        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11462    }
11463
11464    fn push_to_selection_history(&mut self) {
11465        self.selection_history.push(SelectionHistoryEntry {
11466            selections: self.selections.disjoint_anchors(),
11467            select_next_state: self.select_next_state.clone(),
11468            select_prev_state: self.select_prev_state.clone(),
11469            add_selections_state: self.add_selections_state.clone(),
11470        });
11471    }
11472
11473    pub fn transact(
11474        &mut self,
11475        window: &mut Window,
11476        cx: &mut Context<Self>,
11477        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11478    ) -> Option<TransactionId> {
11479        self.start_transaction_at(Instant::now(), window, cx);
11480        update(self, window, cx);
11481        self.end_transaction_at(Instant::now(), cx)
11482    }
11483
11484    pub fn start_transaction_at(
11485        &mut self,
11486        now: Instant,
11487        window: &mut Window,
11488        cx: &mut Context<Self>,
11489    ) {
11490        self.end_selection(window, cx);
11491        if let Some(tx_id) = self
11492            .buffer
11493            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11494        {
11495            self.selection_history
11496                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11497            cx.emit(EditorEvent::TransactionBegun {
11498                transaction_id: tx_id,
11499            })
11500        }
11501    }
11502
11503    pub fn end_transaction_at(
11504        &mut self,
11505        now: Instant,
11506        cx: &mut Context<Self>,
11507    ) -> Option<TransactionId> {
11508        if let Some(transaction_id) = self
11509            .buffer
11510            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11511        {
11512            if let Some((_, end_selections)) =
11513                self.selection_history.transaction_mut(transaction_id)
11514            {
11515                *end_selections = Some(self.selections.disjoint_anchors());
11516            } else {
11517                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11518            }
11519
11520            cx.emit(EditorEvent::Edited { transaction_id });
11521            Some(transaction_id)
11522        } else {
11523            None
11524        }
11525    }
11526
11527    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11528        if self.selection_mark_mode {
11529            self.change_selections(None, window, cx, |s| {
11530                s.move_with(|_, sel| {
11531                    sel.collapse_to(sel.head(), SelectionGoal::None);
11532                });
11533            })
11534        }
11535        self.selection_mark_mode = true;
11536        cx.notify();
11537    }
11538
11539    pub fn swap_selection_ends(
11540        &mut self,
11541        _: &actions::SwapSelectionEnds,
11542        window: &mut Window,
11543        cx: &mut Context<Self>,
11544    ) {
11545        self.change_selections(None, window, cx, |s| {
11546            s.move_with(|_, sel| {
11547                if sel.start != sel.end {
11548                    sel.reversed = !sel.reversed
11549                }
11550            });
11551        });
11552        self.request_autoscroll(Autoscroll::newest(), cx);
11553        cx.notify();
11554    }
11555
11556    pub fn toggle_fold(
11557        &mut self,
11558        _: &actions::ToggleFold,
11559        window: &mut Window,
11560        cx: &mut Context<Self>,
11561    ) {
11562        if self.is_singleton(cx) {
11563            let selection = self.selections.newest::<Point>(cx);
11564
11565            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11566            let range = if selection.is_empty() {
11567                let point = selection.head().to_display_point(&display_map);
11568                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11569                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11570                    .to_point(&display_map);
11571                start..end
11572            } else {
11573                selection.range()
11574            };
11575            if display_map.folds_in_range(range).next().is_some() {
11576                self.unfold_lines(&Default::default(), window, cx)
11577            } else {
11578                self.fold(&Default::default(), window, cx)
11579            }
11580        } else {
11581            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11582            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11583                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11584                .map(|(snapshot, _, _)| snapshot.remote_id())
11585                .collect();
11586
11587            for buffer_id in buffer_ids {
11588                if self.is_buffer_folded(buffer_id, cx) {
11589                    self.unfold_buffer(buffer_id, cx);
11590                } else {
11591                    self.fold_buffer(buffer_id, cx);
11592                }
11593            }
11594        }
11595    }
11596
11597    pub fn toggle_fold_recursive(
11598        &mut self,
11599        _: &actions::ToggleFoldRecursive,
11600        window: &mut Window,
11601        cx: &mut Context<Self>,
11602    ) {
11603        let selection = self.selections.newest::<Point>(cx);
11604
11605        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11606        let range = if selection.is_empty() {
11607            let point = selection.head().to_display_point(&display_map);
11608            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11609            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11610                .to_point(&display_map);
11611            start..end
11612        } else {
11613            selection.range()
11614        };
11615        if display_map.folds_in_range(range).next().is_some() {
11616            self.unfold_recursive(&Default::default(), window, cx)
11617        } else {
11618            self.fold_recursive(&Default::default(), window, cx)
11619        }
11620    }
11621
11622    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11623        if self.is_singleton(cx) {
11624            let mut to_fold = Vec::new();
11625            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11626            let selections = self.selections.all_adjusted(cx);
11627
11628            for selection in selections {
11629                let range = selection.range().sorted();
11630                let buffer_start_row = range.start.row;
11631
11632                if range.start.row != range.end.row {
11633                    let mut found = false;
11634                    let mut row = range.start.row;
11635                    while row <= range.end.row {
11636                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11637                        {
11638                            found = true;
11639                            row = crease.range().end.row + 1;
11640                            to_fold.push(crease);
11641                        } else {
11642                            row += 1
11643                        }
11644                    }
11645                    if found {
11646                        continue;
11647                    }
11648                }
11649
11650                for row in (0..=range.start.row).rev() {
11651                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11652                        if crease.range().end.row >= buffer_start_row {
11653                            to_fold.push(crease);
11654                            if row <= range.start.row {
11655                                break;
11656                            }
11657                        }
11658                    }
11659                }
11660            }
11661
11662            self.fold_creases(to_fold, true, window, cx);
11663        } else {
11664            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11665
11666            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11667                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11668                .map(|(snapshot, _, _)| snapshot.remote_id())
11669                .collect();
11670            for buffer_id in buffer_ids {
11671                self.fold_buffer(buffer_id, cx);
11672            }
11673        }
11674    }
11675
11676    fn fold_at_level(
11677        &mut self,
11678        fold_at: &FoldAtLevel,
11679        window: &mut Window,
11680        cx: &mut Context<Self>,
11681    ) {
11682        if !self.buffer.read(cx).is_singleton() {
11683            return;
11684        }
11685
11686        let fold_at_level = fold_at.level;
11687        let snapshot = self.buffer.read(cx).snapshot(cx);
11688        let mut to_fold = Vec::new();
11689        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11690
11691        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11692            while start_row < end_row {
11693                match self
11694                    .snapshot(window, cx)
11695                    .crease_for_buffer_row(MultiBufferRow(start_row))
11696                {
11697                    Some(crease) => {
11698                        let nested_start_row = crease.range().start.row + 1;
11699                        let nested_end_row = crease.range().end.row;
11700
11701                        if current_level < fold_at_level {
11702                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11703                        } else if current_level == fold_at_level {
11704                            to_fold.push(crease);
11705                        }
11706
11707                        start_row = nested_end_row + 1;
11708                    }
11709                    None => start_row += 1,
11710                }
11711            }
11712        }
11713
11714        self.fold_creases(to_fold, true, window, cx);
11715    }
11716
11717    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11718        if self.buffer.read(cx).is_singleton() {
11719            let mut fold_ranges = Vec::new();
11720            let snapshot = self.buffer.read(cx).snapshot(cx);
11721
11722            for row in 0..snapshot.max_row().0 {
11723                if let Some(foldable_range) = self
11724                    .snapshot(window, cx)
11725                    .crease_for_buffer_row(MultiBufferRow(row))
11726                {
11727                    fold_ranges.push(foldable_range);
11728                }
11729            }
11730
11731            self.fold_creases(fold_ranges, true, window, cx);
11732        } else {
11733            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11734                editor
11735                    .update_in(&mut cx, |editor, _, cx| {
11736                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11737                            editor.fold_buffer(buffer_id, cx);
11738                        }
11739                    })
11740                    .ok();
11741            });
11742        }
11743    }
11744
11745    pub fn fold_function_bodies(
11746        &mut self,
11747        _: &actions::FoldFunctionBodies,
11748        window: &mut Window,
11749        cx: &mut Context<Self>,
11750    ) {
11751        let snapshot = self.buffer.read(cx).snapshot(cx);
11752
11753        let ranges = snapshot
11754            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11755            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11756            .collect::<Vec<_>>();
11757
11758        let creases = ranges
11759            .into_iter()
11760            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11761            .collect();
11762
11763        self.fold_creases(creases, true, window, cx);
11764    }
11765
11766    pub fn fold_recursive(
11767        &mut self,
11768        _: &actions::FoldRecursive,
11769        window: &mut Window,
11770        cx: &mut Context<Self>,
11771    ) {
11772        let mut to_fold = Vec::new();
11773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11774        let selections = self.selections.all_adjusted(cx);
11775
11776        for selection in selections {
11777            let range = selection.range().sorted();
11778            let buffer_start_row = range.start.row;
11779
11780            if range.start.row != range.end.row {
11781                let mut found = false;
11782                for row in range.start.row..=range.end.row {
11783                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11784                        found = true;
11785                        to_fold.push(crease);
11786                    }
11787                }
11788                if found {
11789                    continue;
11790                }
11791            }
11792
11793            for row in (0..=range.start.row).rev() {
11794                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11795                    if crease.range().end.row >= buffer_start_row {
11796                        to_fold.push(crease);
11797                    } else {
11798                        break;
11799                    }
11800                }
11801            }
11802        }
11803
11804        self.fold_creases(to_fold, true, window, cx);
11805    }
11806
11807    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11808        let buffer_row = fold_at.buffer_row;
11809        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11810
11811        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11812            let autoscroll = self
11813                .selections
11814                .all::<Point>(cx)
11815                .iter()
11816                .any(|selection| crease.range().overlaps(&selection.range()));
11817
11818            self.fold_creases(vec![crease], autoscroll, window, cx);
11819        }
11820    }
11821
11822    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11823        if self.is_singleton(cx) {
11824            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11825            let buffer = &display_map.buffer_snapshot;
11826            let selections = self.selections.all::<Point>(cx);
11827            let ranges = selections
11828                .iter()
11829                .map(|s| {
11830                    let range = s.display_range(&display_map).sorted();
11831                    let mut start = range.start.to_point(&display_map);
11832                    let mut end = range.end.to_point(&display_map);
11833                    start.column = 0;
11834                    end.column = buffer.line_len(MultiBufferRow(end.row));
11835                    start..end
11836                })
11837                .collect::<Vec<_>>();
11838
11839            self.unfold_ranges(&ranges, true, true, cx);
11840        } else {
11841            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11842            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11843                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11844                .map(|(snapshot, _, _)| snapshot.remote_id())
11845                .collect();
11846            for buffer_id in buffer_ids {
11847                self.unfold_buffer(buffer_id, cx);
11848            }
11849        }
11850    }
11851
11852    pub fn unfold_recursive(
11853        &mut self,
11854        _: &UnfoldRecursive,
11855        _window: &mut Window,
11856        cx: &mut Context<Self>,
11857    ) {
11858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11859        let selections = self.selections.all::<Point>(cx);
11860        let ranges = selections
11861            .iter()
11862            .map(|s| {
11863                let mut range = s.display_range(&display_map).sorted();
11864                *range.start.column_mut() = 0;
11865                *range.end.column_mut() = display_map.line_len(range.end.row());
11866                let start = range.start.to_point(&display_map);
11867                let end = range.end.to_point(&display_map);
11868                start..end
11869            })
11870            .collect::<Vec<_>>();
11871
11872        self.unfold_ranges(&ranges, true, true, cx);
11873    }
11874
11875    pub fn unfold_at(
11876        &mut self,
11877        unfold_at: &UnfoldAt,
11878        _window: &mut Window,
11879        cx: &mut Context<Self>,
11880    ) {
11881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11882
11883        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11884            ..Point::new(
11885                unfold_at.buffer_row.0,
11886                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11887            );
11888
11889        let autoscroll = self
11890            .selections
11891            .all::<Point>(cx)
11892            .iter()
11893            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11894
11895        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11896    }
11897
11898    pub fn unfold_all(
11899        &mut self,
11900        _: &actions::UnfoldAll,
11901        _window: &mut Window,
11902        cx: &mut Context<Self>,
11903    ) {
11904        if self.buffer.read(cx).is_singleton() {
11905            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11906            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11907        } else {
11908            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11909                editor
11910                    .update(&mut cx, |editor, cx| {
11911                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11912                            editor.unfold_buffer(buffer_id, cx);
11913                        }
11914                    })
11915                    .ok();
11916            });
11917        }
11918    }
11919
11920    pub fn fold_selected_ranges(
11921        &mut self,
11922        _: &FoldSelectedRanges,
11923        window: &mut Window,
11924        cx: &mut Context<Self>,
11925    ) {
11926        let selections = self.selections.all::<Point>(cx);
11927        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11928        let line_mode = self.selections.line_mode;
11929        let ranges = selections
11930            .into_iter()
11931            .map(|s| {
11932                if line_mode {
11933                    let start = Point::new(s.start.row, 0);
11934                    let end = Point::new(
11935                        s.end.row,
11936                        display_map
11937                            .buffer_snapshot
11938                            .line_len(MultiBufferRow(s.end.row)),
11939                    );
11940                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11941                } else {
11942                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11943                }
11944            })
11945            .collect::<Vec<_>>();
11946        self.fold_creases(ranges, true, window, cx);
11947    }
11948
11949    pub fn fold_ranges<T: ToOffset + Clone>(
11950        &mut self,
11951        ranges: Vec<Range<T>>,
11952        auto_scroll: bool,
11953        window: &mut Window,
11954        cx: &mut Context<Self>,
11955    ) {
11956        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11957        let ranges = ranges
11958            .into_iter()
11959            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11960            .collect::<Vec<_>>();
11961        self.fold_creases(ranges, auto_scroll, window, cx);
11962    }
11963
11964    pub fn fold_creases<T: ToOffset + Clone>(
11965        &mut self,
11966        creases: Vec<Crease<T>>,
11967        auto_scroll: bool,
11968        window: &mut Window,
11969        cx: &mut Context<Self>,
11970    ) {
11971        if creases.is_empty() {
11972            return;
11973        }
11974
11975        let mut buffers_affected = HashSet::default();
11976        let multi_buffer = self.buffer().read(cx);
11977        for crease in &creases {
11978            if let Some((_, buffer, _)) =
11979                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11980            {
11981                buffers_affected.insert(buffer.read(cx).remote_id());
11982            };
11983        }
11984
11985        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11986
11987        if auto_scroll {
11988            self.request_autoscroll(Autoscroll::fit(), cx);
11989        }
11990
11991        cx.notify();
11992
11993        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11994            // Clear diagnostics block when folding a range that contains it.
11995            let snapshot = self.snapshot(window, cx);
11996            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11997                drop(snapshot);
11998                self.active_diagnostics = Some(active_diagnostics);
11999                self.dismiss_diagnostics(cx);
12000            } else {
12001                self.active_diagnostics = Some(active_diagnostics);
12002            }
12003        }
12004
12005        self.scrollbar_marker_state.dirty = true;
12006    }
12007
12008    /// Removes any folds whose ranges intersect any of the given ranges.
12009    pub fn unfold_ranges<T: ToOffset + Clone>(
12010        &mut self,
12011        ranges: &[Range<T>],
12012        inclusive: bool,
12013        auto_scroll: bool,
12014        cx: &mut Context<Self>,
12015    ) {
12016        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12017            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12018        });
12019    }
12020
12021    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12022        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12023            return;
12024        }
12025        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12026        self.display_map
12027            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12028        cx.emit(EditorEvent::BufferFoldToggled {
12029            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12030            folded: true,
12031        });
12032        cx.notify();
12033    }
12034
12035    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12036        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12037            return;
12038        }
12039        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12040        self.display_map.update(cx, |display_map, cx| {
12041            display_map.unfold_buffer(buffer_id, cx);
12042        });
12043        cx.emit(EditorEvent::BufferFoldToggled {
12044            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12045            folded: false,
12046        });
12047        cx.notify();
12048    }
12049
12050    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12051        self.display_map.read(cx).is_buffer_folded(buffer)
12052    }
12053
12054    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12055        self.display_map.read(cx).folded_buffers()
12056    }
12057
12058    /// Removes any folds with the given ranges.
12059    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12060        &mut self,
12061        ranges: &[Range<T>],
12062        type_id: TypeId,
12063        auto_scroll: bool,
12064        cx: &mut Context<Self>,
12065    ) {
12066        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12067            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12068        });
12069    }
12070
12071    fn remove_folds_with<T: ToOffset + Clone>(
12072        &mut self,
12073        ranges: &[Range<T>],
12074        auto_scroll: bool,
12075        cx: &mut Context<Self>,
12076        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12077    ) {
12078        if ranges.is_empty() {
12079            return;
12080        }
12081
12082        let mut buffers_affected = HashSet::default();
12083        let multi_buffer = self.buffer().read(cx);
12084        for range in ranges {
12085            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12086                buffers_affected.insert(buffer.read(cx).remote_id());
12087            };
12088        }
12089
12090        self.display_map.update(cx, update);
12091
12092        if auto_scroll {
12093            self.request_autoscroll(Autoscroll::fit(), cx);
12094        }
12095
12096        cx.notify();
12097        self.scrollbar_marker_state.dirty = true;
12098        self.active_indent_guides_state.dirty = true;
12099    }
12100
12101    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12102        self.display_map.read(cx).fold_placeholder.clone()
12103    }
12104
12105    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12106        self.buffer.update(cx, |buffer, cx| {
12107            buffer.set_all_diff_hunks_expanded(cx);
12108        });
12109    }
12110
12111    pub fn expand_all_diff_hunks(
12112        &mut self,
12113        _: &ExpandAllHunkDiffs,
12114        _window: &mut Window,
12115        cx: &mut Context<Self>,
12116    ) {
12117        self.buffer.update(cx, |buffer, cx| {
12118            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12119        });
12120    }
12121
12122    pub fn toggle_selected_diff_hunks(
12123        &mut self,
12124        _: &ToggleSelectedDiffHunks,
12125        _window: &mut Window,
12126        cx: &mut Context<Self>,
12127    ) {
12128        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12129        self.toggle_diff_hunks_in_ranges(ranges, cx);
12130    }
12131
12132    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12133        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12134        self.buffer
12135            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12136    }
12137
12138    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12139        self.buffer.update(cx, |buffer, cx| {
12140            let ranges = vec![Anchor::min()..Anchor::max()];
12141            if !buffer.all_diff_hunks_expanded()
12142                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12143            {
12144                buffer.collapse_diff_hunks(ranges, cx);
12145                true
12146            } else {
12147                false
12148            }
12149        })
12150    }
12151
12152    fn toggle_diff_hunks_in_ranges(
12153        &mut self,
12154        ranges: Vec<Range<Anchor>>,
12155        cx: &mut Context<'_, Editor>,
12156    ) {
12157        self.buffer.update(cx, |buffer, cx| {
12158            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12159                buffer.collapse_diff_hunks(ranges, cx)
12160            } else {
12161                buffer.expand_diff_hunks(ranges, cx)
12162            }
12163        })
12164    }
12165
12166    pub(crate) fn apply_all_diff_hunks(
12167        &mut self,
12168        _: &ApplyAllDiffHunks,
12169        window: &mut Window,
12170        cx: &mut Context<Self>,
12171    ) {
12172        let buffers = self.buffer.read(cx).all_buffers();
12173        for branch_buffer in buffers {
12174            branch_buffer.update(cx, |branch_buffer, cx| {
12175                branch_buffer.merge_into_base(Vec::new(), cx);
12176            });
12177        }
12178
12179        if let Some(project) = self.project.clone() {
12180            self.save(true, project, window, cx).detach_and_log_err(cx);
12181        }
12182    }
12183
12184    pub(crate) fn apply_selected_diff_hunks(
12185        &mut self,
12186        _: &ApplyDiffHunk,
12187        window: &mut Window,
12188        cx: &mut Context<Self>,
12189    ) {
12190        let snapshot = self.snapshot(window, cx);
12191        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12192        let mut ranges_by_buffer = HashMap::default();
12193        self.transact(window, cx, |editor, _window, cx| {
12194            for hunk in hunks {
12195                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12196                    ranges_by_buffer
12197                        .entry(buffer.clone())
12198                        .or_insert_with(Vec::new)
12199                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12200                }
12201            }
12202
12203            for (buffer, ranges) in ranges_by_buffer {
12204                buffer.update(cx, |buffer, cx| {
12205                    buffer.merge_into_base(ranges, cx);
12206                });
12207            }
12208        });
12209
12210        if let Some(project) = self.project.clone() {
12211            self.save(true, project, window, cx).detach_and_log_err(cx);
12212        }
12213    }
12214
12215    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12216        if hovered != self.gutter_hovered {
12217            self.gutter_hovered = hovered;
12218            cx.notify();
12219        }
12220    }
12221
12222    pub fn insert_blocks(
12223        &mut self,
12224        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12225        autoscroll: Option<Autoscroll>,
12226        cx: &mut Context<Self>,
12227    ) -> Vec<CustomBlockId> {
12228        let blocks = self
12229            .display_map
12230            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12231        if let Some(autoscroll) = autoscroll {
12232            self.request_autoscroll(autoscroll, cx);
12233        }
12234        cx.notify();
12235        blocks
12236    }
12237
12238    pub fn resize_blocks(
12239        &mut self,
12240        heights: HashMap<CustomBlockId, u32>,
12241        autoscroll: Option<Autoscroll>,
12242        cx: &mut Context<Self>,
12243    ) {
12244        self.display_map
12245            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12246        if let Some(autoscroll) = autoscroll {
12247            self.request_autoscroll(autoscroll, cx);
12248        }
12249        cx.notify();
12250    }
12251
12252    pub fn replace_blocks(
12253        &mut self,
12254        renderers: HashMap<CustomBlockId, RenderBlock>,
12255        autoscroll: Option<Autoscroll>,
12256        cx: &mut Context<Self>,
12257    ) {
12258        self.display_map
12259            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12260        if let Some(autoscroll) = autoscroll {
12261            self.request_autoscroll(autoscroll, cx);
12262        }
12263        cx.notify();
12264    }
12265
12266    pub fn remove_blocks(
12267        &mut self,
12268        block_ids: HashSet<CustomBlockId>,
12269        autoscroll: Option<Autoscroll>,
12270        cx: &mut Context<Self>,
12271    ) {
12272        self.display_map.update(cx, |display_map, cx| {
12273            display_map.remove_blocks(block_ids, cx)
12274        });
12275        if let Some(autoscroll) = autoscroll {
12276            self.request_autoscroll(autoscroll, cx);
12277        }
12278        cx.notify();
12279    }
12280
12281    pub fn row_for_block(
12282        &self,
12283        block_id: CustomBlockId,
12284        cx: &mut Context<Self>,
12285    ) -> Option<DisplayRow> {
12286        self.display_map
12287            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12288    }
12289
12290    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12291        self.focused_block = Some(focused_block);
12292    }
12293
12294    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12295        self.focused_block.take()
12296    }
12297
12298    pub fn insert_creases(
12299        &mut self,
12300        creases: impl IntoIterator<Item = Crease<Anchor>>,
12301        cx: &mut Context<Self>,
12302    ) -> Vec<CreaseId> {
12303        self.display_map
12304            .update(cx, |map, cx| map.insert_creases(creases, cx))
12305    }
12306
12307    pub fn remove_creases(
12308        &mut self,
12309        ids: impl IntoIterator<Item = CreaseId>,
12310        cx: &mut Context<Self>,
12311    ) {
12312        self.display_map
12313            .update(cx, |map, cx| map.remove_creases(ids, cx));
12314    }
12315
12316    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12317        self.display_map
12318            .update(cx, |map, cx| map.snapshot(cx))
12319            .longest_row()
12320    }
12321
12322    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12323        self.display_map
12324            .update(cx, |map, cx| map.snapshot(cx))
12325            .max_point()
12326    }
12327
12328    pub fn text(&self, cx: &App) -> String {
12329        self.buffer.read(cx).read(cx).text()
12330    }
12331
12332    pub fn is_empty(&self, cx: &App) -> bool {
12333        self.buffer.read(cx).read(cx).is_empty()
12334    }
12335
12336    pub fn text_option(&self, cx: &App) -> Option<String> {
12337        let text = self.text(cx);
12338        let text = text.trim();
12339
12340        if text.is_empty() {
12341            return None;
12342        }
12343
12344        Some(text.to_string())
12345    }
12346
12347    pub fn set_text(
12348        &mut self,
12349        text: impl Into<Arc<str>>,
12350        window: &mut Window,
12351        cx: &mut Context<Self>,
12352    ) {
12353        self.transact(window, cx, |this, _, cx| {
12354            this.buffer
12355                .read(cx)
12356                .as_singleton()
12357                .expect("you can only call set_text on editors for singleton buffers")
12358                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12359        });
12360    }
12361
12362    pub fn display_text(&self, cx: &mut App) -> String {
12363        self.display_map
12364            .update(cx, |map, cx| map.snapshot(cx))
12365            .text()
12366    }
12367
12368    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12369        let mut wrap_guides = smallvec::smallvec![];
12370
12371        if self.show_wrap_guides == Some(false) {
12372            return wrap_guides;
12373        }
12374
12375        let settings = self.buffer.read(cx).settings_at(0, cx);
12376        if settings.show_wrap_guides {
12377            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12378                wrap_guides.push((soft_wrap as usize, true));
12379            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12380                wrap_guides.push((soft_wrap as usize, true));
12381            }
12382            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12383        }
12384
12385        wrap_guides
12386    }
12387
12388    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12389        let settings = self.buffer.read(cx).settings_at(0, cx);
12390        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12391        match mode {
12392            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12393                SoftWrap::None
12394            }
12395            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12396            language_settings::SoftWrap::PreferredLineLength => {
12397                SoftWrap::Column(settings.preferred_line_length)
12398            }
12399            language_settings::SoftWrap::Bounded => {
12400                SoftWrap::Bounded(settings.preferred_line_length)
12401            }
12402        }
12403    }
12404
12405    pub fn set_soft_wrap_mode(
12406        &mut self,
12407        mode: language_settings::SoftWrap,
12408
12409        cx: &mut Context<Self>,
12410    ) {
12411        self.soft_wrap_mode_override = Some(mode);
12412        cx.notify();
12413    }
12414
12415    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12416        self.text_style_refinement = Some(style);
12417    }
12418
12419    /// called by the Element so we know what style we were most recently rendered with.
12420    pub(crate) fn set_style(
12421        &mut self,
12422        style: EditorStyle,
12423        window: &mut Window,
12424        cx: &mut Context<Self>,
12425    ) {
12426        let rem_size = window.rem_size();
12427        self.display_map.update(cx, |map, cx| {
12428            map.set_font(
12429                style.text.font(),
12430                style.text.font_size.to_pixels(rem_size),
12431                cx,
12432            )
12433        });
12434        self.style = Some(style);
12435    }
12436
12437    pub fn style(&self) -> Option<&EditorStyle> {
12438        self.style.as_ref()
12439    }
12440
12441    // Called by the element. This method is not designed to be called outside of the editor
12442    // element's layout code because it does not notify when rewrapping is computed synchronously.
12443    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12444        self.display_map
12445            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12446    }
12447
12448    pub fn set_soft_wrap(&mut self) {
12449        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12450    }
12451
12452    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12453        if self.soft_wrap_mode_override.is_some() {
12454            self.soft_wrap_mode_override.take();
12455        } else {
12456            let soft_wrap = match self.soft_wrap_mode(cx) {
12457                SoftWrap::GitDiff => return,
12458                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12459                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12460                    language_settings::SoftWrap::None
12461                }
12462            };
12463            self.soft_wrap_mode_override = Some(soft_wrap);
12464        }
12465        cx.notify();
12466    }
12467
12468    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12469        let Some(workspace) = self.workspace() else {
12470            return;
12471        };
12472        let fs = workspace.read(cx).app_state().fs.clone();
12473        let current_show = TabBarSettings::get_global(cx).show;
12474        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12475            setting.show = Some(!current_show);
12476        });
12477    }
12478
12479    pub fn toggle_indent_guides(
12480        &mut self,
12481        _: &ToggleIndentGuides,
12482        _: &mut Window,
12483        cx: &mut Context<Self>,
12484    ) {
12485        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12486            self.buffer
12487                .read(cx)
12488                .settings_at(0, cx)
12489                .indent_guides
12490                .enabled
12491        });
12492        self.show_indent_guides = Some(!currently_enabled);
12493        cx.notify();
12494    }
12495
12496    fn should_show_indent_guides(&self) -> Option<bool> {
12497        self.show_indent_guides
12498    }
12499
12500    pub fn toggle_line_numbers(
12501        &mut self,
12502        _: &ToggleLineNumbers,
12503        _: &mut Window,
12504        cx: &mut Context<Self>,
12505    ) {
12506        let mut editor_settings = EditorSettings::get_global(cx).clone();
12507        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12508        EditorSettings::override_global(editor_settings, cx);
12509    }
12510
12511    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12512        self.use_relative_line_numbers
12513            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12514    }
12515
12516    pub fn toggle_relative_line_numbers(
12517        &mut self,
12518        _: &ToggleRelativeLineNumbers,
12519        _: &mut Window,
12520        cx: &mut Context<Self>,
12521    ) {
12522        let is_relative = self.should_use_relative_line_numbers(cx);
12523        self.set_relative_line_number(Some(!is_relative), cx)
12524    }
12525
12526    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12527        self.use_relative_line_numbers = is_relative;
12528        cx.notify();
12529    }
12530
12531    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12532        self.show_gutter = show_gutter;
12533        cx.notify();
12534    }
12535
12536    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12537        self.show_scrollbars = show_scrollbars;
12538        cx.notify();
12539    }
12540
12541    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12542        self.show_line_numbers = Some(show_line_numbers);
12543        cx.notify();
12544    }
12545
12546    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12547        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12548        cx.notify();
12549    }
12550
12551    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12552        self.show_code_actions = Some(show_code_actions);
12553        cx.notify();
12554    }
12555
12556    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12557        self.show_runnables = Some(show_runnables);
12558        cx.notify();
12559    }
12560
12561    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12562        if self.display_map.read(cx).masked != masked {
12563            self.display_map.update(cx, |map, _| map.masked = masked);
12564        }
12565        cx.notify()
12566    }
12567
12568    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12569        self.show_wrap_guides = Some(show_wrap_guides);
12570        cx.notify();
12571    }
12572
12573    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12574        self.show_indent_guides = Some(show_indent_guides);
12575        cx.notify();
12576    }
12577
12578    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12579        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12580            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12581                if let Some(dir) = file.abs_path(cx).parent() {
12582                    return Some(dir.to_owned());
12583                }
12584            }
12585
12586            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12587                return Some(project_path.path.to_path_buf());
12588            }
12589        }
12590
12591        None
12592    }
12593
12594    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12595        self.active_excerpt(cx)?
12596            .1
12597            .read(cx)
12598            .file()
12599            .and_then(|f| f.as_local())
12600    }
12601
12602    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12603        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12604            let project_path = buffer.read(cx).project_path(cx)?;
12605            let project = self.project.as_ref()?.read(cx);
12606            project.absolute_path(&project_path, cx)
12607        })
12608    }
12609
12610    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12611        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12612            let project_path = buffer.read(cx).project_path(cx)?;
12613            let project = self.project.as_ref()?.read(cx);
12614            let entry = project.entry_for_path(&project_path, cx)?;
12615            let path = entry.path.to_path_buf();
12616            Some(path)
12617        })
12618    }
12619
12620    pub fn reveal_in_finder(
12621        &mut self,
12622        _: &RevealInFileManager,
12623        _window: &mut Window,
12624        cx: &mut Context<Self>,
12625    ) {
12626        if let Some(target) = self.target_file(cx) {
12627            cx.reveal_path(&target.abs_path(cx));
12628        }
12629    }
12630
12631    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12632        if let Some(path) = self.target_file_abs_path(cx) {
12633            if let Some(path) = path.to_str() {
12634                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12635            }
12636        }
12637    }
12638
12639    pub fn copy_relative_path(
12640        &mut self,
12641        _: &CopyRelativePath,
12642        _window: &mut Window,
12643        cx: &mut Context<Self>,
12644    ) {
12645        if let Some(path) = self.target_file_path(cx) {
12646            if let Some(path) = path.to_str() {
12647                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12648            }
12649        }
12650    }
12651
12652    pub fn toggle_git_blame(
12653        &mut self,
12654        _: &ToggleGitBlame,
12655        window: &mut Window,
12656        cx: &mut Context<Self>,
12657    ) {
12658        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12659
12660        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12661            self.start_git_blame(true, window, cx);
12662        }
12663
12664        cx.notify();
12665    }
12666
12667    pub fn toggle_git_blame_inline(
12668        &mut self,
12669        _: &ToggleGitBlameInline,
12670        window: &mut Window,
12671        cx: &mut Context<Self>,
12672    ) {
12673        self.toggle_git_blame_inline_internal(true, window, cx);
12674        cx.notify();
12675    }
12676
12677    pub fn git_blame_inline_enabled(&self) -> bool {
12678        self.git_blame_inline_enabled
12679    }
12680
12681    pub fn toggle_selection_menu(
12682        &mut self,
12683        _: &ToggleSelectionMenu,
12684        _: &mut Window,
12685        cx: &mut Context<Self>,
12686    ) {
12687        self.show_selection_menu = self
12688            .show_selection_menu
12689            .map(|show_selections_menu| !show_selections_menu)
12690            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12691
12692        cx.notify();
12693    }
12694
12695    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12696        self.show_selection_menu
12697            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12698    }
12699
12700    fn start_git_blame(
12701        &mut self,
12702        user_triggered: bool,
12703        window: &mut Window,
12704        cx: &mut Context<Self>,
12705    ) {
12706        if let Some(project) = self.project.as_ref() {
12707            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12708                return;
12709            };
12710
12711            if buffer.read(cx).file().is_none() {
12712                return;
12713            }
12714
12715            let focused = self.focus_handle(cx).contains_focused(window, cx);
12716
12717            let project = project.clone();
12718            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12719            self.blame_subscription =
12720                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12721            self.blame = Some(blame);
12722        }
12723    }
12724
12725    fn toggle_git_blame_inline_internal(
12726        &mut self,
12727        user_triggered: bool,
12728        window: &mut Window,
12729        cx: &mut Context<Self>,
12730    ) {
12731        if self.git_blame_inline_enabled {
12732            self.git_blame_inline_enabled = false;
12733            self.show_git_blame_inline = false;
12734            self.show_git_blame_inline_delay_task.take();
12735        } else {
12736            self.git_blame_inline_enabled = true;
12737            self.start_git_blame_inline(user_triggered, window, cx);
12738        }
12739
12740        cx.notify();
12741    }
12742
12743    fn start_git_blame_inline(
12744        &mut self,
12745        user_triggered: bool,
12746        window: &mut Window,
12747        cx: &mut Context<Self>,
12748    ) {
12749        self.start_git_blame(user_triggered, window, cx);
12750
12751        if ProjectSettings::get_global(cx)
12752            .git
12753            .inline_blame_delay()
12754            .is_some()
12755        {
12756            self.start_inline_blame_timer(window, cx);
12757        } else {
12758            self.show_git_blame_inline = true
12759        }
12760    }
12761
12762    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12763        self.blame.as_ref()
12764    }
12765
12766    pub fn show_git_blame_gutter(&self) -> bool {
12767        self.show_git_blame_gutter
12768    }
12769
12770    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12771        self.show_git_blame_gutter && self.has_blame_entries(cx)
12772    }
12773
12774    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12775        self.show_git_blame_inline
12776            && self.focus_handle.is_focused(window)
12777            && !self.newest_selection_head_on_empty_line(cx)
12778            && self.has_blame_entries(cx)
12779    }
12780
12781    fn has_blame_entries(&self, cx: &App) -> bool {
12782        self.blame()
12783            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12784    }
12785
12786    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12787        let cursor_anchor = self.selections.newest_anchor().head();
12788
12789        let snapshot = self.buffer.read(cx).snapshot(cx);
12790        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12791
12792        snapshot.line_len(buffer_row) == 0
12793    }
12794
12795    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12796        let buffer_and_selection = maybe!({
12797            let selection = self.selections.newest::<Point>(cx);
12798            let selection_range = selection.range();
12799
12800            let multi_buffer = self.buffer().read(cx);
12801            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12802            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12803
12804            let (buffer, range, _) = if selection.reversed {
12805                buffer_ranges.first()
12806            } else {
12807                buffer_ranges.last()
12808            }?;
12809
12810            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12811                ..text::ToPoint::to_point(&range.end, &buffer).row;
12812            Some((
12813                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12814                selection,
12815            ))
12816        });
12817
12818        let Some((buffer, selection)) = buffer_and_selection else {
12819            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12820        };
12821
12822        let Some(project) = self.project.as_ref() else {
12823            return Task::ready(Err(anyhow!("editor does not have project")));
12824        };
12825
12826        project.update(cx, |project, cx| {
12827            project.get_permalink_to_line(&buffer, selection, cx)
12828        })
12829    }
12830
12831    pub fn copy_permalink_to_line(
12832        &mut self,
12833        _: &CopyPermalinkToLine,
12834        window: &mut Window,
12835        cx: &mut Context<Self>,
12836    ) {
12837        let permalink_task = self.get_permalink_to_line(cx);
12838        let workspace = self.workspace();
12839
12840        cx.spawn_in(window, |_, mut cx| async move {
12841            match permalink_task.await {
12842                Ok(permalink) => {
12843                    cx.update(|_, cx| {
12844                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12845                    })
12846                    .ok();
12847                }
12848                Err(err) => {
12849                    let message = format!("Failed to copy permalink: {err}");
12850
12851                    Err::<(), anyhow::Error>(err).log_err();
12852
12853                    if let Some(workspace) = workspace {
12854                        workspace
12855                            .update_in(&mut cx, |workspace, _, cx| {
12856                                struct CopyPermalinkToLine;
12857
12858                                workspace.show_toast(
12859                                    Toast::new(
12860                                        NotificationId::unique::<CopyPermalinkToLine>(),
12861                                        message,
12862                                    ),
12863                                    cx,
12864                                )
12865                            })
12866                            .ok();
12867                    }
12868                }
12869            }
12870        })
12871        .detach();
12872    }
12873
12874    pub fn copy_file_location(
12875        &mut self,
12876        _: &CopyFileLocation,
12877        _: &mut Window,
12878        cx: &mut Context<Self>,
12879    ) {
12880        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12881        if let Some(file) = self.target_file(cx) {
12882            if let Some(path) = file.path().to_str() {
12883                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12884            }
12885        }
12886    }
12887
12888    pub fn open_permalink_to_line(
12889        &mut self,
12890        _: &OpenPermalinkToLine,
12891        window: &mut Window,
12892        cx: &mut Context<Self>,
12893    ) {
12894        let permalink_task = self.get_permalink_to_line(cx);
12895        let workspace = self.workspace();
12896
12897        cx.spawn_in(window, |_, mut cx| async move {
12898            match permalink_task.await {
12899                Ok(permalink) => {
12900                    cx.update(|_, cx| {
12901                        cx.open_url(permalink.as_ref());
12902                    })
12903                    .ok();
12904                }
12905                Err(err) => {
12906                    let message = format!("Failed to open permalink: {err}");
12907
12908                    Err::<(), anyhow::Error>(err).log_err();
12909
12910                    if let Some(workspace) = workspace {
12911                        workspace
12912                            .update(&mut cx, |workspace, cx| {
12913                                struct OpenPermalinkToLine;
12914
12915                                workspace.show_toast(
12916                                    Toast::new(
12917                                        NotificationId::unique::<OpenPermalinkToLine>(),
12918                                        message,
12919                                    ),
12920                                    cx,
12921                                )
12922                            })
12923                            .ok();
12924                    }
12925                }
12926            }
12927        })
12928        .detach();
12929    }
12930
12931    pub fn insert_uuid_v4(
12932        &mut self,
12933        _: &InsertUuidV4,
12934        window: &mut Window,
12935        cx: &mut Context<Self>,
12936    ) {
12937        self.insert_uuid(UuidVersion::V4, window, cx);
12938    }
12939
12940    pub fn insert_uuid_v7(
12941        &mut self,
12942        _: &InsertUuidV7,
12943        window: &mut Window,
12944        cx: &mut Context<Self>,
12945    ) {
12946        self.insert_uuid(UuidVersion::V7, window, cx);
12947    }
12948
12949    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12950        self.transact(window, cx, |this, window, cx| {
12951            let edits = this
12952                .selections
12953                .all::<Point>(cx)
12954                .into_iter()
12955                .map(|selection| {
12956                    let uuid = match version {
12957                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12958                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12959                    };
12960
12961                    (selection.range(), uuid.to_string())
12962                });
12963            this.edit(edits, cx);
12964            this.refresh_inline_completion(true, false, window, cx);
12965        });
12966    }
12967
12968    pub fn open_selections_in_multibuffer(
12969        &mut self,
12970        _: &OpenSelectionsInMultibuffer,
12971        window: &mut Window,
12972        cx: &mut Context<Self>,
12973    ) {
12974        let multibuffer = self.buffer.read(cx);
12975
12976        let Some(buffer) = multibuffer.as_singleton() else {
12977            return;
12978        };
12979
12980        let Some(workspace) = self.workspace() else {
12981            return;
12982        };
12983
12984        let locations = self
12985            .selections
12986            .disjoint_anchors()
12987            .iter()
12988            .map(|range| Location {
12989                buffer: buffer.clone(),
12990                range: range.start.text_anchor..range.end.text_anchor,
12991            })
12992            .collect::<Vec<_>>();
12993
12994        let title = multibuffer.title(cx).to_string();
12995
12996        cx.spawn_in(window, |_, mut cx| async move {
12997            workspace.update_in(&mut cx, |workspace, window, cx| {
12998                Self::open_locations_in_multibuffer(
12999                    workspace,
13000                    locations,
13001                    format!("Selections for '{title}'"),
13002                    false,
13003                    MultibufferSelectionMode::All,
13004                    window,
13005                    cx,
13006                );
13007            })
13008        })
13009        .detach();
13010    }
13011
13012    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13013    /// last highlight added will be used.
13014    ///
13015    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13016    pub fn highlight_rows<T: 'static>(
13017        &mut self,
13018        range: Range<Anchor>,
13019        color: Hsla,
13020        should_autoscroll: bool,
13021        cx: &mut Context<Self>,
13022    ) {
13023        let snapshot = self.buffer().read(cx).snapshot(cx);
13024        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13025        let ix = row_highlights.binary_search_by(|highlight| {
13026            Ordering::Equal
13027                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13028                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13029        });
13030
13031        if let Err(mut ix) = ix {
13032            let index = post_inc(&mut self.highlight_order);
13033
13034            // If this range intersects with the preceding highlight, then merge it with
13035            // the preceding highlight. Otherwise insert a new highlight.
13036            let mut merged = false;
13037            if ix > 0 {
13038                let prev_highlight = &mut row_highlights[ix - 1];
13039                if prev_highlight
13040                    .range
13041                    .end
13042                    .cmp(&range.start, &snapshot)
13043                    .is_ge()
13044                {
13045                    ix -= 1;
13046                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13047                        prev_highlight.range.end = range.end;
13048                    }
13049                    merged = true;
13050                    prev_highlight.index = index;
13051                    prev_highlight.color = color;
13052                    prev_highlight.should_autoscroll = should_autoscroll;
13053                }
13054            }
13055
13056            if !merged {
13057                row_highlights.insert(
13058                    ix,
13059                    RowHighlight {
13060                        range: range.clone(),
13061                        index,
13062                        color,
13063                        should_autoscroll,
13064                    },
13065                );
13066            }
13067
13068            // If any of the following highlights intersect with this one, merge them.
13069            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13070                let highlight = &row_highlights[ix];
13071                if next_highlight
13072                    .range
13073                    .start
13074                    .cmp(&highlight.range.end, &snapshot)
13075                    .is_le()
13076                {
13077                    if next_highlight
13078                        .range
13079                        .end
13080                        .cmp(&highlight.range.end, &snapshot)
13081                        .is_gt()
13082                    {
13083                        row_highlights[ix].range.end = next_highlight.range.end;
13084                    }
13085                    row_highlights.remove(ix + 1);
13086                } else {
13087                    break;
13088                }
13089            }
13090        }
13091    }
13092
13093    /// Remove any highlighted row ranges of the given type that intersect the
13094    /// given ranges.
13095    pub fn remove_highlighted_rows<T: 'static>(
13096        &mut self,
13097        ranges_to_remove: Vec<Range<Anchor>>,
13098        cx: &mut Context<Self>,
13099    ) {
13100        let snapshot = self.buffer().read(cx).snapshot(cx);
13101        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13102        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13103        row_highlights.retain(|highlight| {
13104            while let Some(range_to_remove) = ranges_to_remove.peek() {
13105                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13106                    Ordering::Less | Ordering::Equal => {
13107                        ranges_to_remove.next();
13108                    }
13109                    Ordering::Greater => {
13110                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13111                            Ordering::Less | Ordering::Equal => {
13112                                return false;
13113                            }
13114                            Ordering::Greater => break,
13115                        }
13116                    }
13117                }
13118            }
13119
13120            true
13121        })
13122    }
13123
13124    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13125    pub fn clear_row_highlights<T: 'static>(&mut self) {
13126        self.highlighted_rows.remove(&TypeId::of::<T>());
13127    }
13128
13129    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13130    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13131        self.highlighted_rows
13132            .get(&TypeId::of::<T>())
13133            .map_or(&[] as &[_], |vec| vec.as_slice())
13134            .iter()
13135            .map(|highlight| (highlight.range.clone(), highlight.color))
13136    }
13137
13138    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13139    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13140    /// Allows to ignore certain kinds of highlights.
13141    pub fn highlighted_display_rows(
13142        &self,
13143        window: &mut Window,
13144        cx: &mut App,
13145    ) -> BTreeMap<DisplayRow, Hsla> {
13146        let snapshot = self.snapshot(window, cx);
13147        let mut used_highlight_orders = HashMap::default();
13148        self.highlighted_rows
13149            .iter()
13150            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13151            .fold(
13152                BTreeMap::<DisplayRow, Hsla>::new(),
13153                |mut unique_rows, highlight| {
13154                    let start = highlight.range.start.to_display_point(&snapshot);
13155                    let end = highlight.range.end.to_display_point(&snapshot);
13156                    let start_row = start.row().0;
13157                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13158                        && end.column() == 0
13159                    {
13160                        end.row().0.saturating_sub(1)
13161                    } else {
13162                        end.row().0
13163                    };
13164                    for row in start_row..=end_row {
13165                        let used_index =
13166                            used_highlight_orders.entry(row).or_insert(highlight.index);
13167                        if highlight.index >= *used_index {
13168                            *used_index = highlight.index;
13169                            unique_rows.insert(DisplayRow(row), highlight.color);
13170                        }
13171                    }
13172                    unique_rows
13173                },
13174            )
13175    }
13176
13177    pub fn highlighted_display_row_for_autoscroll(
13178        &self,
13179        snapshot: &DisplaySnapshot,
13180    ) -> Option<DisplayRow> {
13181        self.highlighted_rows
13182            .values()
13183            .flat_map(|highlighted_rows| highlighted_rows.iter())
13184            .filter_map(|highlight| {
13185                if highlight.should_autoscroll {
13186                    Some(highlight.range.start.to_display_point(snapshot).row())
13187                } else {
13188                    None
13189                }
13190            })
13191            .min()
13192    }
13193
13194    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13195        self.highlight_background::<SearchWithinRange>(
13196            ranges,
13197            |colors| colors.editor_document_highlight_read_background,
13198            cx,
13199        )
13200    }
13201
13202    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13203        self.breadcrumb_header = Some(new_header);
13204    }
13205
13206    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13207        self.clear_background_highlights::<SearchWithinRange>(cx);
13208    }
13209
13210    pub fn highlight_background<T: 'static>(
13211        &mut self,
13212        ranges: &[Range<Anchor>],
13213        color_fetcher: fn(&ThemeColors) -> Hsla,
13214        cx: &mut Context<Self>,
13215    ) {
13216        self.background_highlights
13217            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13218        self.scrollbar_marker_state.dirty = true;
13219        cx.notify();
13220    }
13221
13222    pub fn clear_background_highlights<T: 'static>(
13223        &mut self,
13224        cx: &mut Context<Self>,
13225    ) -> Option<BackgroundHighlight> {
13226        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13227        if !text_highlights.1.is_empty() {
13228            self.scrollbar_marker_state.dirty = true;
13229            cx.notify();
13230        }
13231        Some(text_highlights)
13232    }
13233
13234    pub fn highlight_gutter<T: 'static>(
13235        &mut self,
13236        ranges: &[Range<Anchor>],
13237        color_fetcher: fn(&App) -> Hsla,
13238        cx: &mut Context<Self>,
13239    ) {
13240        self.gutter_highlights
13241            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13242        cx.notify();
13243    }
13244
13245    pub fn clear_gutter_highlights<T: 'static>(
13246        &mut self,
13247        cx: &mut Context<Self>,
13248    ) -> Option<GutterHighlight> {
13249        cx.notify();
13250        self.gutter_highlights.remove(&TypeId::of::<T>())
13251    }
13252
13253    #[cfg(feature = "test-support")]
13254    pub fn all_text_background_highlights(
13255        &self,
13256        window: &mut Window,
13257        cx: &mut Context<Self>,
13258    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13259        let snapshot = self.snapshot(window, cx);
13260        let buffer = &snapshot.buffer_snapshot;
13261        let start = buffer.anchor_before(0);
13262        let end = buffer.anchor_after(buffer.len());
13263        let theme = cx.theme().colors();
13264        self.background_highlights_in_range(start..end, &snapshot, theme)
13265    }
13266
13267    #[cfg(feature = "test-support")]
13268    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13269        let snapshot = self.buffer().read(cx).snapshot(cx);
13270
13271        let highlights = self
13272            .background_highlights
13273            .get(&TypeId::of::<items::BufferSearchHighlights>());
13274
13275        if let Some((_color, ranges)) = highlights {
13276            ranges
13277                .iter()
13278                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13279                .collect_vec()
13280        } else {
13281            vec![]
13282        }
13283    }
13284
13285    fn document_highlights_for_position<'a>(
13286        &'a self,
13287        position: Anchor,
13288        buffer: &'a MultiBufferSnapshot,
13289    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13290        let read_highlights = self
13291            .background_highlights
13292            .get(&TypeId::of::<DocumentHighlightRead>())
13293            .map(|h| &h.1);
13294        let write_highlights = self
13295            .background_highlights
13296            .get(&TypeId::of::<DocumentHighlightWrite>())
13297            .map(|h| &h.1);
13298        let left_position = position.bias_left(buffer);
13299        let right_position = position.bias_right(buffer);
13300        read_highlights
13301            .into_iter()
13302            .chain(write_highlights)
13303            .flat_map(move |ranges| {
13304                let start_ix = match ranges.binary_search_by(|probe| {
13305                    let cmp = probe.end.cmp(&left_position, buffer);
13306                    if cmp.is_ge() {
13307                        Ordering::Greater
13308                    } else {
13309                        Ordering::Less
13310                    }
13311                }) {
13312                    Ok(i) | Err(i) => i,
13313                };
13314
13315                ranges[start_ix..]
13316                    .iter()
13317                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13318            })
13319    }
13320
13321    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13322        self.background_highlights
13323            .get(&TypeId::of::<T>())
13324            .map_or(false, |(_, highlights)| !highlights.is_empty())
13325    }
13326
13327    pub fn background_highlights_in_range(
13328        &self,
13329        search_range: Range<Anchor>,
13330        display_snapshot: &DisplaySnapshot,
13331        theme: &ThemeColors,
13332    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13333        let mut results = Vec::new();
13334        for (color_fetcher, ranges) in self.background_highlights.values() {
13335            let color = color_fetcher(theme);
13336            let start_ix = match ranges.binary_search_by(|probe| {
13337                let cmp = probe
13338                    .end
13339                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13340                if cmp.is_gt() {
13341                    Ordering::Greater
13342                } else {
13343                    Ordering::Less
13344                }
13345            }) {
13346                Ok(i) | Err(i) => i,
13347            };
13348            for range in &ranges[start_ix..] {
13349                if range
13350                    .start
13351                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13352                    .is_ge()
13353                {
13354                    break;
13355                }
13356
13357                let start = range.start.to_display_point(display_snapshot);
13358                let end = range.end.to_display_point(display_snapshot);
13359                results.push((start..end, color))
13360            }
13361        }
13362        results
13363    }
13364
13365    pub fn background_highlight_row_ranges<T: 'static>(
13366        &self,
13367        search_range: Range<Anchor>,
13368        display_snapshot: &DisplaySnapshot,
13369        count: usize,
13370    ) -> Vec<RangeInclusive<DisplayPoint>> {
13371        let mut results = Vec::new();
13372        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13373            return vec![];
13374        };
13375
13376        let start_ix = match ranges.binary_search_by(|probe| {
13377            let cmp = probe
13378                .end
13379                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13380            if cmp.is_gt() {
13381                Ordering::Greater
13382            } else {
13383                Ordering::Less
13384            }
13385        }) {
13386            Ok(i) | Err(i) => i,
13387        };
13388        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13389            if let (Some(start_display), Some(end_display)) = (start, end) {
13390                results.push(
13391                    start_display.to_display_point(display_snapshot)
13392                        ..=end_display.to_display_point(display_snapshot),
13393                );
13394            }
13395        };
13396        let mut start_row: Option<Point> = None;
13397        let mut end_row: Option<Point> = None;
13398        if ranges.len() > count {
13399            return Vec::new();
13400        }
13401        for range in &ranges[start_ix..] {
13402            if range
13403                .start
13404                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13405                .is_ge()
13406            {
13407                break;
13408            }
13409            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13410            if let Some(current_row) = &end_row {
13411                if end.row == current_row.row {
13412                    continue;
13413                }
13414            }
13415            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13416            if start_row.is_none() {
13417                assert_eq!(end_row, None);
13418                start_row = Some(start);
13419                end_row = Some(end);
13420                continue;
13421            }
13422            if let Some(current_end) = end_row.as_mut() {
13423                if start.row > current_end.row + 1 {
13424                    push_region(start_row, end_row);
13425                    start_row = Some(start);
13426                    end_row = Some(end);
13427                } else {
13428                    // Merge two hunks.
13429                    *current_end = end;
13430                }
13431            } else {
13432                unreachable!();
13433            }
13434        }
13435        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13436        push_region(start_row, end_row);
13437        results
13438    }
13439
13440    pub fn gutter_highlights_in_range(
13441        &self,
13442        search_range: Range<Anchor>,
13443        display_snapshot: &DisplaySnapshot,
13444        cx: &App,
13445    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13446        let mut results = Vec::new();
13447        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13448            let color = color_fetcher(cx);
13449            let start_ix = match ranges.binary_search_by(|probe| {
13450                let cmp = probe
13451                    .end
13452                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13453                if cmp.is_gt() {
13454                    Ordering::Greater
13455                } else {
13456                    Ordering::Less
13457                }
13458            }) {
13459                Ok(i) | Err(i) => i,
13460            };
13461            for range in &ranges[start_ix..] {
13462                if range
13463                    .start
13464                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13465                    .is_ge()
13466                {
13467                    break;
13468                }
13469
13470                let start = range.start.to_display_point(display_snapshot);
13471                let end = range.end.to_display_point(display_snapshot);
13472                results.push((start..end, color))
13473            }
13474        }
13475        results
13476    }
13477
13478    /// Get the text ranges corresponding to the redaction query
13479    pub fn redacted_ranges(
13480        &self,
13481        search_range: Range<Anchor>,
13482        display_snapshot: &DisplaySnapshot,
13483        cx: &App,
13484    ) -> Vec<Range<DisplayPoint>> {
13485        display_snapshot
13486            .buffer_snapshot
13487            .redacted_ranges(search_range, |file| {
13488                if let Some(file) = file {
13489                    file.is_private()
13490                        && EditorSettings::get(
13491                            Some(SettingsLocation {
13492                                worktree_id: file.worktree_id(cx),
13493                                path: file.path().as_ref(),
13494                            }),
13495                            cx,
13496                        )
13497                        .redact_private_values
13498                } else {
13499                    false
13500                }
13501            })
13502            .map(|range| {
13503                range.start.to_display_point(display_snapshot)
13504                    ..range.end.to_display_point(display_snapshot)
13505            })
13506            .collect()
13507    }
13508
13509    pub fn highlight_text<T: 'static>(
13510        &mut self,
13511        ranges: Vec<Range<Anchor>>,
13512        style: HighlightStyle,
13513        cx: &mut Context<Self>,
13514    ) {
13515        self.display_map.update(cx, |map, _| {
13516            map.highlight_text(TypeId::of::<T>(), ranges, style)
13517        });
13518        cx.notify();
13519    }
13520
13521    pub(crate) fn highlight_inlays<T: 'static>(
13522        &mut self,
13523        highlights: Vec<InlayHighlight>,
13524        style: HighlightStyle,
13525        cx: &mut Context<Self>,
13526    ) {
13527        self.display_map.update(cx, |map, _| {
13528            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13529        });
13530        cx.notify();
13531    }
13532
13533    pub fn text_highlights<'a, T: 'static>(
13534        &'a self,
13535        cx: &'a App,
13536    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13537        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13538    }
13539
13540    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13541        let cleared = self
13542            .display_map
13543            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13544        if cleared {
13545            cx.notify();
13546        }
13547    }
13548
13549    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13550        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13551            && self.focus_handle.is_focused(window)
13552    }
13553
13554    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13555        self.show_cursor_when_unfocused = is_enabled;
13556        cx.notify();
13557    }
13558
13559    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13560        self.project
13561            .as_ref()
13562            .map(|project| project.read(cx).lsp_store())
13563    }
13564
13565    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13566        cx.notify();
13567    }
13568
13569    fn on_buffer_event(
13570        &mut self,
13571        multibuffer: &Entity<MultiBuffer>,
13572        event: &multi_buffer::Event,
13573        window: &mut Window,
13574        cx: &mut Context<Self>,
13575    ) {
13576        match event {
13577            multi_buffer::Event::Edited {
13578                singleton_buffer_edited,
13579                edited_buffer: buffer_edited,
13580            } => {
13581                self.scrollbar_marker_state.dirty = true;
13582                self.active_indent_guides_state.dirty = true;
13583                self.refresh_active_diagnostics(cx);
13584                self.refresh_code_actions(window, cx);
13585                if self.has_active_inline_completion() {
13586                    self.update_visible_inline_completion(window, cx);
13587                }
13588                if let Some(buffer) = buffer_edited {
13589                    let buffer_id = buffer.read(cx).remote_id();
13590                    if !self.registered_buffers.contains_key(&buffer_id) {
13591                        if let Some(lsp_store) = self.lsp_store(cx) {
13592                            lsp_store.update(cx, |lsp_store, cx| {
13593                                self.registered_buffers.insert(
13594                                    buffer_id,
13595                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13596                                );
13597                            })
13598                        }
13599                    }
13600                }
13601                cx.emit(EditorEvent::BufferEdited);
13602                cx.emit(SearchEvent::MatchesInvalidated);
13603                if *singleton_buffer_edited {
13604                    if let Some(project) = &self.project {
13605                        let project = project.read(cx);
13606                        #[allow(clippy::mutable_key_type)]
13607                        let languages_affected = multibuffer
13608                            .read(cx)
13609                            .all_buffers()
13610                            .into_iter()
13611                            .filter_map(|buffer| {
13612                                let buffer = buffer.read(cx);
13613                                let language = buffer.language()?;
13614                                if project.is_local()
13615                                    && project
13616                                        .language_servers_for_local_buffer(buffer, cx)
13617                                        .count()
13618                                        == 0
13619                                {
13620                                    None
13621                                } else {
13622                                    Some(language)
13623                                }
13624                            })
13625                            .cloned()
13626                            .collect::<HashSet<_>>();
13627                        if !languages_affected.is_empty() {
13628                            self.refresh_inlay_hints(
13629                                InlayHintRefreshReason::BufferEdited(languages_affected),
13630                                cx,
13631                            );
13632                        }
13633                    }
13634                }
13635
13636                let Some(project) = &self.project else { return };
13637                let (telemetry, is_via_ssh) = {
13638                    let project = project.read(cx);
13639                    let telemetry = project.client().telemetry().clone();
13640                    let is_via_ssh = project.is_via_ssh();
13641                    (telemetry, is_via_ssh)
13642                };
13643                refresh_linked_ranges(self, window, cx);
13644                telemetry.log_edit_event("editor", is_via_ssh);
13645            }
13646            multi_buffer::Event::ExcerptsAdded {
13647                buffer,
13648                predecessor,
13649                excerpts,
13650            } => {
13651                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13652                let buffer_id = buffer.read(cx).remote_id();
13653                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13654                    if let Some(project) = &self.project {
13655                        get_unstaged_changes_for_buffers(
13656                            project,
13657                            [buffer.clone()],
13658                            self.buffer.clone(),
13659                            cx,
13660                        );
13661                    }
13662                }
13663                cx.emit(EditorEvent::ExcerptsAdded {
13664                    buffer: buffer.clone(),
13665                    predecessor: *predecessor,
13666                    excerpts: excerpts.clone(),
13667                });
13668                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13669            }
13670            multi_buffer::Event::ExcerptsRemoved { ids } => {
13671                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13672                let buffer = self.buffer.read(cx);
13673                self.registered_buffers
13674                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13675                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13676            }
13677            multi_buffer::Event::ExcerptsEdited { ids } => {
13678                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13679            }
13680            multi_buffer::Event::ExcerptsExpanded { ids } => {
13681                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13682                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13683            }
13684            multi_buffer::Event::Reparsed(buffer_id) => {
13685                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13686
13687                cx.emit(EditorEvent::Reparsed(*buffer_id));
13688            }
13689            multi_buffer::Event::DiffHunksToggled => {
13690                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13691            }
13692            multi_buffer::Event::LanguageChanged(buffer_id) => {
13693                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13694                cx.emit(EditorEvent::Reparsed(*buffer_id));
13695                cx.notify();
13696            }
13697            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13698            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13699            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13700                cx.emit(EditorEvent::TitleChanged)
13701            }
13702            // multi_buffer::Event::DiffBaseChanged => {
13703            //     self.scrollbar_marker_state.dirty = true;
13704            //     cx.emit(EditorEvent::DiffBaseChanged);
13705            //     cx.notify();
13706            // }
13707            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13708            multi_buffer::Event::DiagnosticsUpdated => {
13709                self.refresh_active_diagnostics(cx);
13710                self.scrollbar_marker_state.dirty = true;
13711                cx.notify();
13712            }
13713            _ => {}
13714        };
13715    }
13716
13717    fn on_display_map_changed(
13718        &mut self,
13719        _: Entity<DisplayMap>,
13720        _: &mut Window,
13721        cx: &mut Context<Self>,
13722    ) {
13723        cx.notify();
13724    }
13725
13726    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13727        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13728        self.refresh_inline_completion(true, false, window, cx);
13729        self.refresh_inlay_hints(
13730            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13731                self.selections.newest_anchor().head(),
13732                &self.buffer.read(cx).snapshot(cx),
13733                cx,
13734            )),
13735            cx,
13736        );
13737
13738        let old_cursor_shape = self.cursor_shape;
13739
13740        {
13741            let editor_settings = EditorSettings::get_global(cx);
13742            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13743            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13744            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13745        }
13746
13747        if old_cursor_shape != self.cursor_shape {
13748            cx.emit(EditorEvent::CursorShapeChanged);
13749        }
13750
13751        let project_settings = ProjectSettings::get_global(cx);
13752        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13753
13754        if self.mode == EditorMode::Full {
13755            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13756            if self.git_blame_inline_enabled != inline_blame_enabled {
13757                self.toggle_git_blame_inline_internal(false, window, cx);
13758            }
13759        }
13760
13761        cx.notify();
13762    }
13763
13764    pub fn set_searchable(&mut self, searchable: bool) {
13765        self.searchable = searchable;
13766    }
13767
13768    pub fn searchable(&self) -> bool {
13769        self.searchable
13770    }
13771
13772    fn open_proposed_changes_editor(
13773        &mut self,
13774        _: &OpenProposedChangesEditor,
13775        window: &mut Window,
13776        cx: &mut Context<Self>,
13777    ) {
13778        let Some(workspace) = self.workspace() else {
13779            cx.propagate();
13780            return;
13781        };
13782
13783        let selections = self.selections.all::<usize>(cx);
13784        let multi_buffer = self.buffer.read(cx);
13785        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13786        let mut new_selections_by_buffer = HashMap::default();
13787        for selection in selections {
13788            for (buffer, range, _) in
13789                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13790            {
13791                let mut range = range.to_point(buffer);
13792                range.start.column = 0;
13793                range.end.column = buffer.line_len(range.end.row);
13794                new_selections_by_buffer
13795                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13796                    .or_insert(Vec::new())
13797                    .push(range)
13798            }
13799        }
13800
13801        let proposed_changes_buffers = new_selections_by_buffer
13802            .into_iter()
13803            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13804            .collect::<Vec<_>>();
13805        let proposed_changes_editor = cx.new(|cx| {
13806            ProposedChangesEditor::new(
13807                "Proposed changes",
13808                proposed_changes_buffers,
13809                self.project.clone(),
13810                window,
13811                cx,
13812            )
13813        });
13814
13815        window.defer(cx, move |window, cx| {
13816            workspace.update(cx, |workspace, cx| {
13817                workspace.active_pane().update(cx, |pane, cx| {
13818                    pane.add_item(
13819                        Box::new(proposed_changes_editor),
13820                        true,
13821                        true,
13822                        None,
13823                        window,
13824                        cx,
13825                    );
13826                });
13827            });
13828        });
13829    }
13830
13831    pub fn open_excerpts_in_split(
13832        &mut self,
13833        _: &OpenExcerptsSplit,
13834        window: &mut Window,
13835        cx: &mut Context<Self>,
13836    ) {
13837        self.open_excerpts_common(None, true, window, cx)
13838    }
13839
13840    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13841        self.open_excerpts_common(None, false, window, cx)
13842    }
13843
13844    fn open_excerpts_common(
13845        &mut self,
13846        jump_data: Option<JumpData>,
13847        split: bool,
13848        window: &mut Window,
13849        cx: &mut Context<Self>,
13850    ) {
13851        let Some(workspace) = self.workspace() else {
13852            cx.propagate();
13853            return;
13854        };
13855
13856        if self.buffer.read(cx).is_singleton() {
13857            cx.propagate();
13858            return;
13859        }
13860
13861        let mut new_selections_by_buffer = HashMap::default();
13862        match &jump_data {
13863            Some(JumpData::MultiBufferPoint {
13864                excerpt_id,
13865                position,
13866                anchor,
13867                line_offset_from_top,
13868            }) => {
13869                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13870                if let Some(buffer) = multi_buffer_snapshot
13871                    .buffer_id_for_excerpt(*excerpt_id)
13872                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13873                {
13874                    let buffer_snapshot = buffer.read(cx).snapshot();
13875                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13876                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13877                    } else {
13878                        buffer_snapshot.clip_point(*position, Bias::Left)
13879                    };
13880                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13881                    new_selections_by_buffer.insert(
13882                        buffer,
13883                        (
13884                            vec![jump_to_offset..jump_to_offset],
13885                            Some(*line_offset_from_top),
13886                        ),
13887                    );
13888                }
13889            }
13890            Some(JumpData::MultiBufferRow {
13891                row,
13892                line_offset_from_top,
13893            }) => {
13894                let point = MultiBufferPoint::new(row.0, 0);
13895                if let Some((buffer, buffer_point, _)) =
13896                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13897                {
13898                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13899                    new_selections_by_buffer
13900                        .entry(buffer)
13901                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13902                        .0
13903                        .push(buffer_offset..buffer_offset)
13904                }
13905            }
13906            None => {
13907                let selections = self.selections.all::<usize>(cx);
13908                let multi_buffer = self.buffer.read(cx);
13909                for selection in selections {
13910                    for (buffer, mut range, _) in multi_buffer
13911                        .snapshot(cx)
13912                        .range_to_buffer_ranges(selection.range())
13913                    {
13914                        // When editing branch buffers, jump to the corresponding location
13915                        // in their base buffer.
13916                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13917                        let buffer = buffer_handle.read(cx);
13918                        if let Some(base_buffer) = buffer.base_buffer() {
13919                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13920                            buffer_handle = base_buffer;
13921                        }
13922
13923                        if selection.reversed {
13924                            mem::swap(&mut range.start, &mut range.end);
13925                        }
13926                        new_selections_by_buffer
13927                            .entry(buffer_handle)
13928                            .or_insert((Vec::new(), None))
13929                            .0
13930                            .push(range)
13931                    }
13932                }
13933            }
13934        }
13935
13936        if new_selections_by_buffer.is_empty() {
13937            return;
13938        }
13939
13940        // We defer the pane interaction because we ourselves are a workspace item
13941        // and activating a new item causes the pane to call a method on us reentrantly,
13942        // which panics if we're on the stack.
13943        window.defer(cx, move |window, cx| {
13944            workspace.update(cx, |workspace, cx| {
13945                let pane = if split {
13946                    workspace.adjacent_pane(window, cx)
13947                } else {
13948                    workspace.active_pane().clone()
13949                };
13950
13951                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13952                    let editor = buffer
13953                        .read(cx)
13954                        .file()
13955                        .is_none()
13956                        .then(|| {
13957                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13958                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13959                            // Instead, we try to activate the existing editor in the pane first.
13960                            let (editor, pane_item_index) =
13961                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13962                                    let editor = item.downcast::<Editor>()?;
13963                                    let singleton_buffer =
13964                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13965                                    if singleton_buffer == buffer {
13966                                        Some((editor, i))
13967                                    } else {
13968                                        None
13969                                    }
13970                                })?;
13971                            pane.update(cx, |pane, cx| {
13972                                pane.activate_item(pane_item_index, true, true, window, cx)
13973                            });
13974                            Some(editor)
13975                        })
13976                        .flatten()
13977                        .unwrap_or_else(|| {
13978                            workspace.open_project_item::<Self>(
13979                                pane.clone(),
13980                                buffer,
13981                                true,
13982                                true,
13983                                window,
13984                                cx,
13985                            )
13986                        });
13987
13988                    editor.update(cx, |editor, cx| {
13989                        let autoscroll = match scroll_offset {
13990                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13991                            None => Autoscroll::newest(),
13992                        };
13993                        let nav_history = editor.nav_history.take();
13994                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13995                            s.select_ranges(ranges);
13996                        });
13997                        editor.nav_history = nav_history;
13998                    });
13999                }
14000            })
14001        });
14002    }
14003
14004    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14005        let snapshot = self.buffer.read(cx).read(cx);
14006        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14007        Some(
14008            ranges
14009                .iter()
14010                .map(move |range| {
14011                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14012                })
14013                .collect(),
14014        )
14015    }
14016
14017    fn selection_replacement_ranges(
14018        &self,
14019        range: Range<OffsetUtf16>,
14020        cx: &mut App,
14021    ) -> Vec<Range<OffsetUtf16>> {
14022        let selections = self.selections.all::<OffsetUtf16>(cx);
14023        let newest_selection = selections
14024            .iter()
14025            .max_by_key(|selection| selection.id)
14026            .unwrap();
14027        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14028        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14029        let snapshot = self.buffer.read(cx).read(cx);
14030        selections
14031            .into_iter()
14032            .map(|mut selection| {
14033                selection.start.0 =
14034                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14035                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14036                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14037                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14038            })
14039            .collect()
14040    }
14041
14042    fn report_editor_event(
14043        &self,
14044        event_type: &'static str,
14045        file_extension: Option<String>,
14046        cx: &App,
14047    ) {
14048        if cfg!(any(test, feature = "test-support")) {
14049            return;
14050        }
14051
14052        let Some(project) = &self.project else { return };
14053
14054        // If None, we are in a file without an extension
14055        let file = self
14056            .buffer
14057            .read(cx)
14058            .as_singleton()
14059            .and_then(|b| b.read(cx).file());
14060        let file_extension = file_extension.or(file
14061            .as_ref()
14062            .and_then(|file| Path::new(file.file_name(cx)).extension())
14063            .and_then(|e| e.to_str())
14064            .map(|a| a.to_string()));
14065
14066        let vim_mode = cx
14067            .global::<SettingsStore>()
14068            .raw_user_settings()
14069            .get("vim_mode")
14070            == Some(&serde_json::Value::Bool(true));
14071
14072        let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14073        let copilot_enabled = edit_predictions_provider
14074            == language::language_settings::InlineCompletionProvider::Copilot;
14075        let copilot_enabled_for_language = self
14076            .buffer
14077            .read(cx)
14078            .settings_at(0, cx)
14079            .show_inline_completions;
14080
14081        let project = project.read(cx);
14082        telemetry::event!(
14083            event_type,
14084            file_extension,
14085            vim_mode,
14086            copilot_enabled,
14087            copilot_enabled_for_language,
14088            edit_predictions_provider,
14089            is_via_ssh = project.is_via_ssh(),
14090        );
14091    }
14092
14093    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14094    /// with each line being an array of {text, highlight} objects.
14095    fn copy_highlight_json(
14096        &mut self,
14097        _: &CopyHighlightJson,
14098        window: &mut Window,
14099        cx: &mut Context<Self>,
14100    ) {
14101        #[derive(Serialize)]
14102        struct Chunk<'a> {
14103            text: String,
14104            highlight: Option<&'a str>,
14105        }
14106
14107        let snapshot = self.buffer.read(cx).snapshot(cx);
14108        let range = self
14109            .selected_text_range(false, window, cx)
14110            .and_then(|selection| {
14111                if selection.range.is_empty() {
14112                    None
14113                } else {
14114                    Some(selection.range)
14115                }
14116            })
14117            .unwrap_or_else(|| 0..snapshot.len());
14118
14119        let chunks = snapshot.chunks(range, true);
14120        let mut lines = Vec::new();
14121        let mut line: VecDeque<Chunk> = VecDeque::new();
14122
14123        let Some(style) = self.style.as_ref() else {
14124            return;
14125        };
14126
14127        for chunk in chunks {
14128            let highlight = chunk
14129                .syntax_highlight_id
14130                .and_then(|id| id.name(&style.syntax));
14131            let mut chunk_lines = chunk.text.split('\n').peekable();
14132            while let Some(text) = chunk_lines.next() {
14133                let mut merged_with_last_token = false;
14134                if let Some(last_token) = line.back_mut() {
14135                    if last_token.highlight == highlight {
14136                        last_token.text.push_str(text);
14137                        merged_with_last_token = true;
14138                    }
14139                }
14140
14141                if !merged_with_last_token {
14142                    line.push_back(Chunk {
14143                        text: text.into(),
14144                        highlight,
14145                    });
14146                }
14147
14148                if chunk_lines.peek().is_some() {
14149                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14150                        line.pop_front();
14151                    }
14152                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14153                        line.pop_back();
14154                    }
14155
14156                    lines.push(mem::take(&mut line));
14157                }
14158            }
14159        }
14160
14161        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14162            return;
14163        };
14164        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14165    }
14166
14167    pub fn open_context_menu(
14168        &mut self,
14169        _: &OpenContextMenu,
14170        window: &mut Window,
14171        cx: &mut Context<Self>,
14172    ) {
14173        self.request_autoscroll(Autoscroll::newest(), cx);
14174        let position = self.selections.newest_display(cx).start;
14175        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14176    }
14177
14178    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14179        &self.inlay_hint_cache
14180    }
14181
14182    pub fn replay_insert_event(
14183        &mut self,
14184        text: &str,
14185        relative_utf16_range: Option<Range<isize>>,
14186        window: &mut Window,
14187        cx: &mut Context<Self>,
14188    ) {
14189        if !self.input_enabled {
14190            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14191            return;
14192        }
14193        if let Some(relative_utf16_range) = relative_utf16_range {
14194            let selections = self.selections.all::<OffsetUtf16>(cx);
14195            self.change_selections(None, window, cx, |s| {
14196                let new_ranges = selections.into_iter().map(|range| {
14197                    let start = OffsetUtf16(
14198                        range
14199                            .head()
14200                            .0
14201                            .saturating_add_signed(relative_utf16_range.start),
14202                    );
14203                    let end = OffsetUtf16(
14204                        range
14205                            .head()
14206                            .0
14207                            .saturating_add_signed(relative_utf16_range.end),
14208                    );
14209                    start..end
14210                });
14211                s.select_ranges(new_ranges);
14212            });
14213        }
14214
14215        self.handle_input(text, window, cx);
14216    }
14217
14218    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14219        let Some(provider) = self.semantics_provider.as_ref() else {
14220            return false;
14221        };
14222
14223        let mut supports = false;
14224        self.buffer().read(cx).for_each_buffer(|buffer| {
14225            supports |= provider.supports_inlay_hints(buffer, cx);
14226        });
14227        supports
14228    }
14229    pub fn is_focused(&self, window: &mut Window) -> bool {
14230        self.focus_handle.is_focused(window)
14231    }
14232
14233    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14234        cx.emit(EditorEvent::Focused);
14235
14236        if let Some(descendant) = self
14237            .last_focused_descendant
14238            .take()
14239            .and_then(|descendant| descendant.upgrade())
14240        {
14241            window.focus(&descendant);
14242        } else {
14243            if let Some(blame) = self.blame.as_ref() {
14244                blame.update(cx, GitBlame::focus)
14245            }
14246
14247            self.blink_manager.update(cx, BlinkManager::enable);
14248            self.show_cursor_names(window, cx);
14249            self.buffer.update(cx, |buffer, cx| {
14250                buffer.finalize_last_transaction(cx);
14251                if self.leader_peer_id.is_none() {
14252                    buffer.set_active_selections(
14253                        &self.selections.disjoint_anchors(),
14254                        self.selections.line_mode,
14255                        self.cursor_shape,
14256                        cx,
14257                    );
14258                }
14259            });
14260        }
14261    }
14262
14263    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14264        cx.emit(EditorEvent::FocusedIn)
14265    }
14266
14267    fn handle_focus_out(
14268        &mut self,
14269        event: FocusOutEvent,
14270        _window: &mut Window,
14271        _cx: &mut Context<Self>,
14272    ) {
14273        if event.blurred != self.focus_handle {
14274            self.last_focused_descendant = Some(event.blurred);
14275        }
14276    }
14277
14278    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14279        self.blink_manager.update(cx, BlinkManager::disable);
14280        self.buffer
14281            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14282
14283        if let Some(blame) = self.blame.as_ref() {
14284            blame.update(cx, GitBlame::blur)
14285        }
14286        if !self.hover_state.focused(window, cx) {
14287            hide_hover(self, cx);
14288        }
14289
14290        self.hide_context_menu(window, cx);
14291        cx.emit(EditorEvent::Blurred);
14292        cx.notify();
14293    }
14294
14295    pub fn register_action<A: Action>(
14296        &mut self,
14297        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14298    ) -> Subscription {
14299        let id = self.next_editor_action_id.post_inc();
14300        let listener = Arc::new(listener);
14301        self.editor_actions.borrow_mut().insert(
14302            id,
14303            Box::new(move |window, _| {
14304                let listener = listener.clone();
14305                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14306                    let action = action.downcast_ref().unwrap();
14307                    if phase == DispatchPhase::Bubble {
14308                        listener(action, window, cx)
14309                    }
14310                })
14311            }),
14312        );
14313
14314        let editor_actions = self.editor_actions.clone();
14315        Subscription::new(move || {
14316            editor_actions.borrow_mut().remove(&id);
14317        })
14318    }
14319
14320    pub fn file_header_size(&self) -> u32 {
14321        FILE_HEADER_HEIGHT
14322    }
14323
14324    pub fn revert(
14325        &mut self,
14326        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14327        window: &mut Window,
14328        cx: &mut Context<Self>,
14329    ) {
14330        self.buffer().update(cx, |multi_buffer, cx| {
14331            for (buffer_id, changes) in revert_changes {
14332                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14333                    buffer.update(cx, |buffer, cx| {
14334                        buffer.edit(
14335                            changes.into_iter().map(|(range, text)| {
14336                                (range, text.to_string().map(Arc::<str>::from))
14337                            }),
14338                            None,
14339                            cx,
14340                        );
14341                    });
14342                }
14343            }
14344        });
14345        self.change_selections(None, window, cx, |selections| selections.refresh());
14346    }
14347
14348    pub fn to_pixel_point(
14349        &self,
14350        source: multi_buffer::Anchor,
14351        editor_snapshot: &EditorSnapshot,
14352        window: &mut Window,
14353    ) -> Option<gpui::Point<Pixels>> {
14354        let source_point = source.to_display_point(editor_snapshot);
14355        self.display_to_pixel_point(source_point, editor_snapshot, window)
14356    }
14357
14358    pub fn display_to_pixel_point(
14359        &self,
14360        source: DisplayPoint,
14361        editor_snapshot: &EditorSnapshot,
14362        window: &mut Window,
14363    ) -> Option<gpui::Point<Pixels>> {
14364        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14365        let text_layout_details = self.text_layout_details(window);
14366        let scroll_top = text_layout_details
14367            .scroll_anchor
14368            .scroll_position(editor_snapshot)
14369            .y;
14370
14371        if source.row().as_f32() < scroll_top.floor() {
14372            return None;
14373        }
14374        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14375        let source_y = line_height * (source.row().as_f32() - scroll_top);
14376        Some(gpui::Point::new(source_x, source_y))
14377    }
14378
14379    pub fn has_active_completions_menu(&self) -> bool {
14380        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14381            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14382        })
14383    }
14384
14385    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14386        self.addons
14387            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14388    }
14389
14390    pub fn unregister_addon<T: Addon>(&mut self) {
14391        self.addons.remove(&std::any::TypeId::of::<T>());
14392    }
14393
14394    pub fn addon<T: Addon>(&self) -> Option<&T> {
14395        let type_id = std::any::TypeId::of::<T>();
14396        self.addons
14397            .get(&type_id)
14398            .and_then(|item| item.to_any().downcast_ref::<T>())
14399    }
14400
14401    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14402        let text_layout_details = self.text_layout_details(window);
14403        let style = &text_layout_details.editor_style;
14404        let font_id = window.text_system().resolve_font(&style.text.font());
14405        let font_size = style.text.font_size.to_pixels(window.rem_size());
14406        let line_height = style.text.line_height_in_pixels(window.rem_size());
14407        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14408
14409        gpui::Size::new(em_width, line_height)
14410    }
14411}
14412
14413fn get_unstaged_changes_for_buffers(
14414    project: &Entity<Project>,
14415    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14416    buffer: Entity<MultiBuffer>,
14417    cx: &mut App,
14418) {
14419    let mut tasks = Vec::new();
14420    project.update(cx, |project, cx| {
14421        for buffer in buffers {
14422            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14423        }
14424    });
14425    cx.spawn(|mut cx| async move {
14426        let change_sets = futures::future::join_all(tasks).await;
14427        buffer
14428            .update(&mut cx, |buffer, cx| {
14429                for change_set in change_sets {
14430                    if let Some(change_set) = change_set.log_err() {
14431                        buffer.add_change_set(change_set, cx);
14432                    }
14433                }
14434            })
14435            .ok();
14436    })
14437    .detach();
14438}
14439
14440fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14441    let tab_size = tab_size.get() as usize;
14442    let mut width = offset;
14443
14444    for ch in text.chars() {
14445        width += if ch == '\t' {
14446            tab_size - (width % tab_size)
14447        } else {
14448            1
14449        };
14450    }
14451
14452    width - offset
14453}
14454
14455#[cfg(test)]
14456mod tests {
14457    use super::*;
14458
14459    #[test]
14460    fn test_string_size_with_expanded_tabs() {
14461        let nz = |val| NonZeroU32::new(val).unwrap();
14462        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14463        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14464        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14465        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14466        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14467        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14468        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14469        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14470    }
14471}
14472
14473/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14474struct WordBreakingTokenizer<'a> {
14475    input: &'a str,
14476}
14477
14478impl<'a> WordBreakingTokenizer<'a> {
14479    fn new(input: &'a str) -> Self {
14480        Self { input }
14481    }
14482}
14483
14484fn is_char_ideographic(ch: char) -> bool {
14485    use unicode_script::Script::*;
14486    use unicode_script::UnicodeScript;
14487    matches!(ch.script(), Han | Tangut | Yi)
14488}
14489
14490fn is_grapheme_ideographic(text: &str) -> bool {
14491    text.chars().any(is_char_ideographic)
14492}
14493
14494fn is_grapheme_whitespace(text: &str) -> bool {
14495    text.chars().any(|x| x.is_whitespace())
14496}
14497
14498fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14499    text.chars().next().map_or(false, |ch| {
14500        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14501    })
14502}
14503
14504#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14505struct WordBreakToken<'a> {
14506    token: &'a str,
14507    grapheme_len: usize,
14508    is_whitespace: bool,
14509}
14510
14511impl<'a> Iterator for WordBreakingTokenizer<'a> {
14512    /// Yields a span, the count of graphemes in the token, and whether it was
14513    /// whitespace. Note that it also breaks at word boundaries.
14514    type Item = WordBreakToken<'a>;
14515
14516    fn next(&mut self) -> Option<Self::Item> {
14517        use unicode_segmentation::UnicodeSegmentation;
14518        if self.input.is_empty() {
14519            return None;
14520        }
14521
14522        let mut iter = self.input.graphemes(true).peekable();
14523        let mut offset = 0;
14524        let mut graphemes = 0;
14525        if let Some(first_grapheme) = iter.next() {
14526            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14527            offset += first_grapheme.len();
14528            graphemes += 1;
14529            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14530                if let Some(grapheme) = iter.peek().copied() {
14531                    if should_stay_with_preceding_ideograph(grapheme) {
14532                        offset += grapheme.len();
14533                        graphemes += 1;
14534                    }
14535                }
14536            } else {
14537                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14538                let mut next_word_bound = words.peek().copied();
14539                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14540                    next_word_bound = words.next();
14541                }
14542                while let Some(grapheme) = iter.peek().copied() {
14543                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14544                        break;
14545                    };
14546                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14547                        break;
14548                    };
14549                    offset += grapheme.len();
14550                    graphemes += 1;
14551                    iter.next();
14552                }
14553            }
14554            let token = &self.input[..offset];
14555            self.input = &self.input[offset..];
14556            if is_whitespace {
14557                Some(WordBreakToken {
14558                    token: " ",
14559                    grapheme_len: 1,
14560                    is_whitespace: true,
14561                })
14562            } else {
14563                Some(WordBreakToken {
14564                    token,
14565                    grapheme_len: graphemes,
14566                    is_whitespace: false,
14567                })
14568            }
14569        } else {
14570            None
14571        }
14572    }
14573}
14574
14575#[test]
14576fn test_word_breaking_tokenizer() {
14577    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14578        ("", &[]),
14579        ("  ", &[(" ", 1, true)]),
14580        ("Ʒ", &[("Ʒ", 1, false)]),
14581        ("Ǽ", &[("Ǽ", 1, false)]),
14582        ("", &[("", 1, false)]),
14583        ("⋑⋑", &[("⋑⋑", 2, false)]),
14584        (
14585            "原理,进而",
14586            &[
14587                ("", 1, false),
14588                ("理,", 2, false),
14589                ("", 1, false),
14590                ("", 1, false),
14591            ],
14592        ),
14593        (
14594            "hello world",
14595            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14596        ),
14597        (
14598            "hello, world",
14599            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14600        ),
14601        (
14602            "  hello world",
14603            &[
14604                (" ", 1, true),
14605                ("hello", 5, false),
14606                (" ", 1, true),
14607                ("world", 5, false),
14608            ],
14609        ),
14610        (
14611            "这是什么 \n 钢笔",
14612            &[
14613                ("", 1, false),
14614                ("", 1, false),
14615                ("", 1, false),
14616                ("", 1, false),
14617                (" ", 1, true),
14618                ("", 1, false),
14619                ("", 1, false),
14620            ],
14621        ),
14622        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14623    ];
14624
14625    for (input, result) in tests {
14626        assert_eq!(
14627            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14628            result
14629                .iter()
14630                .copied()
14631                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14632                    token,
14633                    grapheme_len,
14634                    is_whitespace,
14635                })
14636                .collect::<Vec<_>>()
14637        );
14638    }
14639}
14640
14641fn wrap_with_prefix(
14642    line_prefix: String,
14643    unwrapped_text: String,
14644    wrap_column: usize,
14645    tab_size: NonZeroU32,
14646) -> String {
14647    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14648    let mut wrapped_text = String::new();
14649    let mut current_line = line_prefix.clone();
14650
14651    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14652    let mut current_line_len = line_prefix_len;
14653    for WordBreakToken {
14654        token,
14655        grapheme_len,
14656        is_whitespace,
14657    } in tokenizer
14658    {
14659        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14660            wrapped_text.push_str(current_line.trim_end());
14661            wrapped_text.push('\n');
14662            current_line.truncate(line_prefix.len());
14663            current_line_len = line_prefix_len;
14664            if !is_whitespace {
14665                current_line.push_str(token);
14666                current_line_len += grapheme_len;
14667            }
14668        } else if !is_whitespace {
14669            current_line.push_str(token);
14670            current_line_len += grapheme_len;
14671        } else if current_line_len != line_prefix_len {
14672            current_line.push(' ');
14673            current_line_len += 1;
14674        }
14675    }
14676
14677    if !current_line.is_empty() {
14678        wrapped_text.push_str(&current_line);
14679    }
14680    wrapped_text
14681}
14682
14683#[test]
14684fn test_wrap_with_prefix() {
14685    assert_eq!(
14686        wrap_with_prefix(
14687            "# ".to_string(),
14688            "abcdefg".to_string(),
14689            4,
14690            NonZeroU32::new(4).unwrap()
14691        ),
14692        "# abcdefg"
14693    );
14694    assert_eq!(
14695        wrap_with_prefix(
14696            "".to_string(),
14697            "\thello world".to_string(),
14698            8,
14699            NonZeroU32::new(4).unwrap()
14700        ),
14701        "hello\nworld"
14702    );
14703    assert_eq!(
14704        wrap_with_prefix(
14705            "// ".to_string(),
14706            "xx \nyy zz aa bb cc".to_string(),
14707            12,
14708            NonZeroU32::new(4).unwrap()
14709        ),
14710        "// xx yy zz\n// aa bb cc"
14711    );
14712    assert_eq!(
14713        wrap_with_prefix(
14714            String::new(),
14715            "这是什么 \n 钢笔".to_string(),
14716            3,
14717            NonZeroU32::new(4).unwrap()
14718        ),
14719        "这是什\n么 钢\n"
14720    );
14721}
14722
14723pub trait CollaborationHub {
14724    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14725    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14726    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14727}
14728
14729impl CollaborationHub for Entity<Project> {
14730    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14731        self.read(cx).collaborators()
14732    }
14733
14734    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14735        self.read(cx).user_store().read(cx).participant_indices()
14736    }
14737
14738    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14739        let this = self.read(cx);
14740        let user_ids = this.collaborators().values().map(|c| c.user_id);
14741        this.user_store().read_with(cx, |user_store, cx| {
14742            user_store.participant_names(user_ids, cx)
14743        })
14744    }
14745}
14746
14747pub trait SemanticsProvider {
14748    fn hover(
14749        &self,
14750        buffer: &Entity<Buffer>,
14751        position: text::Anchor,
14752        cx: &mut App,
14753    ) -> Option<Task<Vec<project::Hover>>>;
14754
14755    fn inlay_hints(
14756        &self,
14757        buffer_handle: Entity<Buffer>,
14758        range: Range<text::Anchor>,
14759        cx: &mut App,
14760    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14761
14762    fn resolve_inlay_hint(
14763        &self,
14764        hint: InlayHint,
14765        buffer_handle: Entity<Buffer>,
14766        server_id: LanguageServerId,
14767        cx: &mut App,
14768    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14769
14770    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14771
14772    fn document_highlights(
14773        &self,
14774        buffer: &Entity<Buffer>,
14775        position: text::Anchor,
14776        cx: &mut App,
14777    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14778
14779    fn definitions(
14780        &self,
14781        buffer: &Entity<Buffer>,
14782        position: text::Anchor,
14783        kind: GotoDefinitionKind,
14784        cx: &mut App,
14785    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14786
14787    fn range_for_rename(
14788        &self,
14789        buffer: &Entity<Buffer>,
14790        position: text::Anchor,
14791        cx: &mut App,
14792    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14793
14794    fn perform_rename(
14795        &self,
14796        buffer: &Entity<Buffer>,
14797        position: text::Anchor,
14798        new_name: String,
14799        cx: &mut App,
14800    ) -> Option<Task<Result<ProjectTransaction>>>;
14801}
14802
14803pub trait CompletionProvider {
14804    fn completions(
14805        &self,
14806        buffer: &Entity<Buffer>,
14807        buffer_position: text::Anchor,
14808        trigger: CompletionContext,
14809        window: &mut Window,
14810        cx: &mut Context<Editor>,
14811    ) -> Task<Result<Vec<Completion>>>;
14812
14813    fn resolve_completions(
14814        &self,
14815        buffer: Entity<Buffer>,
14816        completion_indices: Vec<usize>,
14817        completions: Rc<RefCell<Box<[Completion]>>>,
14818        cx: &mut Context<Editor>,
14819    ) -> Task<Result<bool>>;
14820
14821    fn apply_additional_edits_for_completion(
14822        &self,
14823        _buffer: Entity<Buffer>,
14824        _completions: Rc<RefCell<Box<[Completion]>>>,
14825        _completion_index: usize,
14826        _push_to_history: bool,
14827        _cx: &mut Context<Editor>,
14828    ) -> Task<Result<Option<language::Transaction>>> {
14829        Task::ready(Ok(None))
14830    }
14831
14832    fn is_completion_trigger(
14833        &self,
14834        buffer: &Entity<Buffer>,
14835        position: language::Anchor,
14836        text: &str,
14837        trigger_in_words: bool,
14838        cx: &mut Context<Editor>,
14839    ) -> bool;
14840
14841    fn sort_completions(&self) -> bool {
14842        true
14843    }
14844}
14845
14846pub trait CodeActionProvider {
14847    fn id(&self) -> Arc<str>;
14848
14849    fn code_actions(
14850        &self,
14851        buffer: &Entity<Buffer>,
14852        range: Range<text::Anchor>,
14853        window: &mut Window,
14854        cx: &mut App,
14855    ) -> Task<Result<Vec<CodeAction>>>;
14856
14857    fn apply_code_action(
14858        &self,
14859        buffer_handle: Entity<Buffer>,
14860        action: CodeAction,
14861        excerpt_id: ExcerptId,
14862        push_to_history: bool,
14863        window: &mut Window,
14864        cx: &mut App,
14865    ) -> Task<Result<ProjectTransaction>>;
14866}
14867
14868impl CodeActionProvider for Entity<Project> {
14869    fn id(&self) -> Arc<str> {
14870        "project".into()
14871    }
14872
14873    fn code_actions(
14874        &self,
14875        buffer: &Entity<Buffer>,
14876        range: Range<text::Anchor>,
14877        _window: &mut Window,
14878        cx: &mut App,
14879    ) -> Task<Result<Vec<CodeAction>>> {
14880        self.update(cx, |project, cx| {
14881            project.code_actions(buffer, range, None, cx)
14882        })
14883    }
14884
14885    fn apply_code_action(
14886        &self,
14887        buffer_handle: Entity<Buffer>,
14888        action: CodeAction,
14889        _excerpt_id: ExcerptId,
14890        push_to_history: bool,
14891        _window: &mut Window,
14892        cx: &mut App,
14893    ) -> Task<Result<ProjectTransaction>> {
14894        self.update(cx, |project, cx| {
14895            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14896        })
14897    }
14898}
14899
14900fn snippet_completions(
14901    project: &Project,
14902    buffer: &Entity<Buffer>,
14903    buffer_position: text::Anchor,
14904    cx: &mut App,
14905) -> Task<Result<Vec<Completion>>> {
14906    let language = buffer.read(cx).language_at(buffer_position);
14907    let language_name = language.as_ref().map(|language| language.lsp_id());
14908    let snippet_store = project.snippets().read(cx);
14909    let snippets = snippet_store.snippets_for(language_name, cx);
14910
14911    if snippets.is_empty() {
14912        return Task::ready(Ok(vec![]));
14913    }
14914    let snapshot = buffer.read(cx).text_snapshot();
14915    let chars: String = snapshot
14916        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14917        .collect();
14918
14919    let scope = language.map(|language| language.default_scope());
14920    let executor = cx.background_executor().clone();
14921
14922    cx.background_executor().spawn(async move {
14923        let classifier = CharClassifier::new(scope).for_completion(true);
14924        let mut last_word = chars
14925            .chars()
14926            .take_while(|c| classifier.is_word(*c))
14927            .collect::<String>();
14928        last_word = last_word.chars().rev().collect();
14929
14930        if last_word.is_empty() {
14931            return Ok(vec![]);
14932        }
14933
14934        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14935        let to_lsp = |point: &text::Anchor| {
14936            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14937            point_to_lsp(end)
14938        };
14939        let lsp_end = to_lsp(&buffer_position);
14940
14941        let candidates = snippets
14942            .iter()
14943            .enumerate()
14944            .flat_map(|(ix, snippet)| {
14945                snippet
14946                    .prefix
14947                    .iter()
14948                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14949            })
14950            .collect::<Vec<StringMatchCandidate>>();
14951
14952        let mut matches = fuzzy::match_strings(
14953            &candidates,
14954            &last_word,
14955            last_word.chars().any(|c| c.is_uppercase()),
14956            100,
14957            &Default::default(),
14958            executor,
14959        )
14960        .await;
14961
14962        // Remove all candidates where the query's start does not match the start of any word in the candidate
14963        if let Some(query_start) = last_word.chars().next() {
14964            matches.retain(|string_match| {
14965                split_words(&string_match.string).any(|word| {
14966                    // Check that the first codepoint of the word as lowercase matches the first
14967                    // codepoint of the query as lowercase
14968                    word.chars()
14969                        .flat_map(|codepoint| codepoint.to_lowercase())
14970                        .zip(query_start.to_lowercase())
14971                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14972                })
14973            });
14974        }
14975
14976        let matched_strings = matches
14977            .into_iter()
14978            .map(|m| m.string)
14979            .collect::<HashSet<_>>();
14980
14981        let result: Vec<Completion> = snippets
14982            .into_iter()
14983            .filter_map(|snippet| {
14984                let matching_prefix = snippet
14985                    .prefix
14986                    .iter()
14987                    .find(|prefix| matched_strings.contains(*prefix))?;
14988                let start = as_offset - last_word.len();
14989                let start = snapshot.anchor_before(start);
14990                let range = start..buffer_position;
14991                let lsp_start = to_lsp(&start);
14992                let lsp_range = lsp::Range {
14993                    start: lsp_start,
14994                    end: lsp_end,
14995                };
14996                Some(Completion {
14997                    old_range: range,
14998                    new_text: snippet.body.clone(),
14999                    resolved: false,
15000                    label: CodeLabel {
15001                        text: matching_prefix.clone(),
15002                        runs: vec![],
15003                        filter_range: 0..matching_prefix.len(),
15004                    },
15005                    server_id: LanguageServerId(usize::MAX),
15006                    documentation: snippet
15007                        .description
15008                        .clone()
15009                        .map(CompletionDocumentation::SingleLine),
15010                    lsp_completion: lsp::CompletionItem {
15011                        label: snippet.prefix.first().unwrap().clone(),
15012                        kind: Some(CompletionItemKind::SNIPPET),
15013                        label_details: snippet.description.as_ref().map(|description| {
15014                            lsp::CompletionItemLabelDetails {
15015                                detail: Some(description.clone()),
15016                                description: None,
15017                            }
15018                        }),
15019                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15020                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15021                            lsp::InsertReplaceEdit {
15022                                new_text: snippet.body.clone(),
15023                                insert: lsp_range,
15024                                replace: lsp_range,
15025                            },
15026                        )),
15027                        filter_text: Some(snippet.body.clone()),
15028                        sort_text: Some(char::MAX.to_string()),
15029                        ..Default::default()
15030                    },
15031                    confirm: None,
15032                })
15033            })
15034            .collect();
15035
15036        Ok(result)
15037    })
15038}
15039
15040impl CompletionProvider for Entity<Project> {
15041    fn completions(
15042        &self,
15043        buffer: &Entity<Buffer>,
15044        buffer_position: text::Anchor,
15045        options: CompletionContext,
15046        _window: &mut Window,
15047        cx: &mut Context<Editor>,
15048    ) -> Task<Result<Vec<Completion>>> {
15049        self.update(cx, |project, cx| {
15050            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15051            let project_completions = project.completions(buffer, buffer_position, options, cx);
15052            cx.background_executor().spawn(async move {
15053                let mut completions = project_completions.await?;
15054                let snippets_completions = snippets.await?;
15055                completions.extend(snippets_completions);
15056                Ok(completions)
15057            })
15058        })
15059    }
15060
15061    fn resolve_completions(
15062        &self,
15063        buffer: Entity<Buffer>,
15064        completion_indices: Vec<usize>,
15065        completions: Rc<RefCell<Box<[Completion]>>>,
15066        cx: &mut Context<Editor>,
15067    ) -> Task<Result<bool>> {
15068        self.update(cx, |project, cx| {
15069            project.lsp_store().update(cx, |lsp_store, cx| {
15070                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15071            })
15072        })
15073    }
15074
15075    fn apply_additional_edits_for_completion(
15076        &self,
15077        buffer: Entity<Buffer>,
15078        completions: Rc<RefCell<Box<[Completion]>>>,
15079        completion_index: usize,
15080        push_to_history: bool,
15081        cx: &mut Context<Editor>,
15082    ) -> Task<Result<Option<language::Transaction>>> {
15083        self.update(cx, |project, cx| {
15084            project.lsp_store().update(cx, |lsp_store, cx| {
15085                lsp_store.apply_additional_edits_for_completion(
15086                    buffer,
15087                    completions,
15088                    completion_index,
15089                    push_to_history,
15090                    cx,
15091                )
15092            })
15093        })
15094    }
15095
15096    fn is_completion_trigger(
15097        &self,
15098        buffer: &Entity<Buffer>,
15099        position: language::Anchor,
15100        text: &str,
15101        trigger_in_words: bool,
15102        cx: &mut Context<Editor>,
15103    ) -> bool {
15104        let mut chars = text.chars();
15105        let char = if let Some(char) = chars.next() {
15106            char
15107        } else {
15108            return false;
15109        };
15110        if chars.next().is_some() {
15111            return false;
15112        }
15113
15114        let buffer = buffer.read(cx);
15115        let snapshot = buffer.snapshot();
15116        if !snapshot.settings_at(position, cx).show_completions_on_input {
15117            return false;
15118        }
15119        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15120        if trigger_in_words && classifier.is_word(char) {
15121            return true;
15122        }
15123
15124        buffer.completion_triggers().contains(text)
15125    }
15126}
15127
15128impl SemanticsProvider for Entity<Project> {
15129    fn hover(
15130        &self,
15131        buffer: &Entity<Buffer>,
15132        position: text::Anchor,
15133        cx: &mut App,
15134    ) -> Option<Task<Vec<project::Hover>>> {
15135        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15136    }
15137
15138    fn document_highlights(
15139        &self,
15140        buffer: &Entity<Buffer>,
15141        position: text::Anchor,
15142        cx: &mut App,
15143    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15144        Some(self.update(cx, |project, cx| {
15145            project.document_highlights(buffer, position, cx)
15146        }))
15147    }
15148
15149    fn definitions(
15150        &self,
15151        buffer: &Entity<Buffer>,
15152        position: text::Anchor,
15153        kind: GotoDefinitionKind,
15154        cx: &mut App,
15155    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15156        Some(self.update(cx, |project, cx| match kind {
15157            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15158            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15159            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15160            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15161        }))
15162    }
15163
15164    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15165        // TODO: make this work for remote projects
15166        self.read(cx)
15167            .language_servers_for_local_buffer(buffer.read(cx), cx)
15168            .any(
15169                |(_, server)| match server.capabilities().inlay_hint_provider {
15170                    Some(lsp::OneOf::Left(enabled)) => enabled,
15171                    Some(lsp::OneOf::Right(_)) => true,
15172                    None => false,
15173                },
15174            )
15175    }
15176
15177    fn inlay_hints(
15178        &self,
15179        buffer_handle: Entity<Buffer>,
15180        range: Range<text::Anchor>,
15181        cx: &mut App,
15182    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15183        Some(self.update(cx, |project, cx| {
15184            project.inlay_hints(buffer_handle, range, cx)
15185        }))
15186    }
15187
15188    fn resolve_inlay_hint(
15189        &self,
15190        hint: InlayHint,
15191        buffer_handle: Entity<Buffer>,
15192        server_id: LanguageServerId,
15193        cx: &mut App,
15194    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15195        Some(self.update(cx, |project, cx| {
15196            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15197        }))
15198    }
15199
15200    fn range_for_rename(
15201        &self,
15202        buffer: &Entity<Buffer>,
15203        position: text::Anchor,
15204        cx: &mut App,
15205    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15206        Some(self.update(cx, |project, cx| {
15207            let buffer = buffer.clone();
15208            let task = project.prepare_rename(buffer.clone(), position, cx);
15209            cx.spawn(|_, mut cx| async move {
15210                Ok(match task.await? {
15211                    PrepareRenameResponse::Success(range) => Some(range),
15212                    PrepareRenameResponse::InvalidPosition => None,
15213                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15214                        // Fallback on using TreeSitter info to determine identifier range
15215                        buffer.update(&mut cx, |buffer, _| {
15216                            let snapshot = buffer.snapshot();
15217                            let (range, kind) = snapshot.surrounding_word(position);
15218                            if kind != Some(CharKind::Word) {
15219                                return None;
15220                            }
15221                            Some(
15222                                snapshot.anchor_before(range.start)
15223                                    ..snapshot.anchor_after(range.end),
15224                            )
15225                        })?
15226                    }
15227                })
15228            })
15229        }))
15230    }
15231
15232    fn perform_rename(
15233        &self,
15234        buffer: &Entity<Buffer>,
15235        position: text::Anchor,
15236        new_name: String,
15237        cx: &mut App,
15238    ) -> Option<Task<Result<ProjectTransaction>>> {
15239        Some(self.update(cx, |project, cx| {
15240            project.perform_rename(buffer.clone(), position, new_name, cx)
15241        }))
15242    }
15243}
15244
15245fn inlay_hint_settings(
15246    location: Anchor,
15247    snapshot: &MultiBufferSnapshot,
15248    cx: &mut Context<Editor>,
15249) -> InlayHintSettings {
15250    let file = snapshot.file_at(location);
15251    let language = snapshot.language_at(location).map(|l| l.name());
15252    language_settings(language, file, cx).inlay_hints
15253}
15254
15255fn consume_contiguous_rows(
15256    contiguous_row_selections: &mut Vec<Selection<Point>>,
15257    selection: &Selection<Point>,
15258    display_map: &DisplaySnapshot,
15259    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15260) -> (MultiBufferRow, MultiBufferRow) {
15261    contiguous_row_selections.push(selection.clone());
15262    let start_row = MultiBufferRow(selection.start.row);
15263    let mut end_row = ending_row(selection, display_map);
15264
15265    while let Some(next_selection) = selections.peek() {
15266        if next_selection.start.row <= end_row.0 {
15267            end_row = ending_row(next_selection, display_map);
15268            contiguous_row_selections.push(selections.next().unwrap().clone());
15269        } else {
15270            break;
15271        }
15272    }
15273    (start_row, end_row)
15274}
15275
15276fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15277    if next_selection.end.column > 0 || next_selection.is_empty() {
15278        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15279    } else {
15280        MultiBufferRow(next_selection.end.row)
15281    }
15282}
15283
15284impl EditorSnapshot {
15285    pub fn remote_selections_in_range<'a>(
15286        &'a self,
15287        range: &'a Range<Anchor>,
15288        collaboration_hub: &dyn CollaborationHub,
15289        cx: &'a App,
15290    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15291        let participant_names = collaboration_hub.user_names(cx);
15292        let participant_indices = collaboration_hub.user_participant_indices(cx);
15293        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15294        let collaborators_by_replica_id = collaborators_by_peer_id
15295            .iter()
15296            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15297            .collect::<HashMap<_, _>>();
15298        self.buffer_snapshot
15299            .selections_in_range(range, false)
15300            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15301                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15302                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15303                let user_name = participant_names.get(&collaborator.user_id).cloned();
15304                Some(RemoteSelection {
15305                    replica_id,
15306                    selection,
15307                    cursor_shape,
15308                    line_mode,
15309                    participant_index,
15310                    peer_id: collaborator.peer_id,
15311                    user_name,
15312                })
15313            })
15314    }
15315
15316    pub fn hunks_for_ranges(
15317        &self,
15318        ranges: impl Iterator<Item = Range<Point>>,
15319    ) -> Vec<MultiBufferDiffHunk> {
15320        let mut hunks = Vec::new();
15321        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15322            HashMap::default();
15323        for query_range in ranges {
15324            let query_rows =
15325                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15326            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15327                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15328            ) {
15329                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15330                // when the caret is just above or just below the deleted hunk.
15331                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15332                let related_to_selection = if allow_adjacent {
15333                    hunk.row_range.overlaps(&query_rows)
15334                        || hunk.row_range.start == query_rows.end
15335                        || hunk.row_range.end == query_rows.start
15336                } else {
15337                    hunk.row_range.overlaps(&query_rows)
15338                };
15339                if related_to_selection {
15340                    if !processed_buffer_rows
15341                        .entry(hunk.buffer_id)
15342                        .or_default()
15343                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15344                    {
15345                        continue;
15346                    }
15347                    hunks.push(hunk);
15348                }
15349            }
15350        }
15351
15352        hunks
15353    }
15354
15355    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15356        self.display_snapshot.buffer_snapshot.language_at(position)
15357    }
15358
15359    pub fn is_focused(&self) -> bool {
15360        self.is_focused
15361    }
15362
15363    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15364        self.placeholder_text.as_ref()
15365    }
15366
15367    pub fn scroll_position(&self) -> gpui::Point<f32> {
15368        self.scroll_anchor.scroll_position(&self.display_snapshot)
15369    }
15370
15371    fn gutter_dimensions(
15372        &self,
15373        font_id: FontId,
15374        font_size: Pixels,
15375        max_line_number_width: Pixels,
15376        cx: &App,
15377    ) -> Option<GutterDimensions> {
15378        if !self.show_gutter {
15379            return None;
15380        }
15381
15382        let descent = cx.text_system().descent(font_id, font_size);
15383        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15384        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15385
15386        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15387            matches!(
15388                ProjectSettings::get_global(cx).git.git_gutter,
15389                Some(GitGutterSetting::TrackedFiles)
15390            )
15391        });
15392        let gutter_settings = EditorSettings::get_global(cx).gutter;
15393        let show_line_numbers = self
15394            .show_line_numbers
15395            .unwrap_or(gutter_settings.line_numbers);
15396        let line_gutter_width = if show_line_numbers {
15397            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15398            let min_width_for_number_on_gutter = em_advance * 4.0;
15399            max_line_number_width.max(min_width_for_number_on_gutter)
15400        } else {
15401            0.0.into()
15402        };
15403
15404        let show_code_actions = self
15405            .show_code_actions
15406            .unwrap_or(gutter_settings.code_actions);
15407
15408        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15409
15410        let git_blame_entries_width =
15411            self.git_blame_gutter_max_author_length
15412                .map(|max_author_length| {
15413                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15414
15415                    /// The number of characters to dedicate to gaps and margins.
15416                    const SPACING_WIDTH: usize = 4;
15417
15418                    let max_char_count = max_author_length
15419                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15420                        + ::git::SHORT_SHA_LENGTH
15421                        + MAX_RELATIVE_TIMESTAMP.len()
15422                        + SPACING_WIDTH;
15423
15424                    em_advance * max_char_count
15425                });
15426
15427        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15428        left_padding += if show_code_actions || show_runnables {
15429            em_width * 3.0
15430        } else if show_git_gutter && show_line_numbers {
15431            em_width * 2.0
15432        } else if show_git_gutter || show_line_numbers {
15433            em_width
15434        } else {
15435            px(0.)
15436        };
15437
15438        let right_padding = if gutter_settings.folds && show_line_numbers {
15439            em_width * 4.0
15440        } else if gutter_settings.folds {
15441            em_width * 3.0
15442        } else if show_line_numbers {
15443            em_width
15444        } else {
15445            px(0.)
15446        };
15447
15448        Some(GutterDimensions {
15449            left_padding,
15450            right_padding,
15451            width: line_gutter_width + left_padding + right_padding,
15452            margin: -descent,
15453            git_blame_entries_width,
15454        })
15455    }
15456
15457    pub fn render_crease_toggle(
15458        &self,
15459        buffer_row: MultiBufferRow,
15460        row_contains_cursor: bool,
15461        editor: Entity<Editor>,
15462        window: &mut Window,
15463        cx: &mut App,
15464    ) -> Option<AnyElement> {
15465        let folded = self.is_line_folded(buffer_row);
15466        let mut is_foldable = false;
15467
15468        if let Some(crease) = self
15469            .crease_snapshot
15470            .query_row(buffer_row, &self.buffer_snapshot)
15471        {
15472            is_foldable = true;
15473            match crease {
15474                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15475                    if let Some(render_toggle) = render_toggle {
15476                        let toggle_callback =
15477                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15478                                if folded {
15479                                    editor.update(cx, |editor, cx| {
15480                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15481                                    });
15482                                } else {
15483                                    editor.update(cx, |editor, cx| {
15484                                        editor.unfold_at(
15485                                            &crate::UnfoldAt { buffer_row },
15486                                            window,
15487                                            cx,
15488                                        )
15489                                    });
15490                                }
15491                            });
15492                        return Some((render_toggle)(
15493                            buffer_row,
15494                            folded,
15495                            toggle_callback,
15496                            window,
15497                            cx,
15498                        ));
15499                    }
15500                }
15501            }
15502        }
15503
15504        is_foldable |= self.starts_indent(buffer_row);
15505
15506        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15507            Some(
15508                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15509                    .toggle_state(folded)
15510                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15511                        if folded {
15512                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15513                        } else {
15514                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15515                        }
15516                    }))
15517                    .into_any_element(),
15518            )
15519        } else {
15520            None
15521        }
15522    }
15523
15524    pub fn render_crease_trailer(
15525        &self,
15526        buffer_row: MultiBufferRow,
15527        window: &mut Window,
15528        cx: &mut App,
15529    ) -> Option<AnyElement> {
15530        let folded = self.is_line_folded(buffer_row);
15531        if let Crease::Inline { render_trailer, .. } = self
15532            .crease_snapshot
15533            .query_row(buffer_row, &self.buffer_snapshot)?
15534        {
15535            let render_trailer = render_trailer.as_ref()?;
15536            Some(render_trailer(buffer_row, folded, window, cx))
15537        } else {
15538            None
15539        }
15540    }
15541}
15542
15543impl Deref for EditorSnapshot {
15544    type Target = DisplaySnapshot;
15545
15546    fn deref(&self) -> &Self::Target {
15547        &self.display_snapshot
15548    }
15549}
15550
15551#[derive(Clone, Debug, PartialEq, Eq)]
15552pub enum EditorEvent {
15553    InputIgnored {
15554        text: Arc<str>,
15555    },
15556    InputHandled {
15557        utf16_range_to_replace: Option<Range<isize>>,
15558        text: Arc<str>,
15559    },
15560    ExcerptsAdded {
15561        buffer: Entity<Buffer>,
15562        predecessor: ExcerptId,
15563        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15564    },
15565    ExcerptsRemoved {
15566        ids: Vec<ExcerptId>,
15567    },
15568    BufferFoldToggled {
15569        ids: Vec<ExcerptId>,
15570        folded: bool,
15571    },
15572    ExcerptsEdited {
15573        ids: Vec<ExcerptId>,
15574    },
15575    ExcerptsExpanded {
15576        ids: Vec<ExcerptId>,
15577    },
15578    BufferEdited,
15579    Edited {
15580        transaction_id: clock::Lamport,
15581    },
15582    Reparsed(BufferId),
15583    Focused,
15584    FocusedIn,
15585    Blurred,
15586    DirtyChanged,
15587    Saved,
15588    TitleChanged,
15589    DiffBaseChanged,
15590    SelectionsChanged {
15591        local: bool,
15592    },
15593    ScrollPositionChanged {
15594        local: bool,
15595        autoscroll: bool,
15596    },
15597    Closed,
15598    TransactionUndone {
15599        transaction_id: clock::Lamport,
15600    },
15601    TransactionBegun {
15602        transaction_id: clock::Lamport,
15603    },
15604    Reloaded,
15605    CursorShapeChanged,
15606}
15607
15608impl EventEmitter<EditorEvent> for Editor {}
15609
15610impl Focusable for Editor {
15611    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15612        self.focus_handle.clone()
15613    }
15614}
15615
15616impl Render for Editor {
15617    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15618        let settings = ThemeSettings::get_global(cx);
15619
15620        let mut text_style = match self.mode {
15621            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15622                color: cx.theme().colors().editor_foreground,
15623                font_family: settings.ui_font.family.clone(),
15624                font_features: settings.ui_font.features.clone(),
15625                font_fallbacks: settings.ui_font.fallbacks.clone(),
15626                font_size: rems(0.875).into(),
15627                font_weight: settings.ui_font.weight,
15628                line_height: relative(settings.buffer_line_height.value()),
15629                ..Default::default()
15630            },
15631            EditorMode::Full => TextStyle {
15632                color: cx.theme().colors().editor_foreground,
15633                font_family: settings.buffer_font.family.clone(),
15634                font_features: settings.buffer_font.features.clone(),
15635                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15636                font_size: settings.buffer_font_size().into(),
15637                font_weight: settings.buffer_font.weight,
15638                line_height: relative(settings.buffer_line_height.value()),
15639                ..Default::default()
15640            },
15641        };
15642        if let Some(text_style_refinement) = &self.text_style_refinement {
15643            text_style.refine(text_style_refinement)
15644        }
15645
15646        let background = match self.mode {
15647            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15648            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15649            EditorMode::Full => cx.theme().colors().editor_background,
15650        };
15651
15652        EditorElement::new(
15653            &cx.entity(),
15654            EditorStyle {
15655                background,
15656                local_player: cx.theme().players().local(),
15657                text: text_style,
15658                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15659                syntax: cx.theme().syntax().clone(),
15660                status: cx.theme().status().clone(),
15661                inlay_hints_style: make_inlay_hints_style(cx),
15662                inline_completion_styles: make_suggestion_styles(cx),
15663                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15664            },
15665        )
15666    }
15667}
15668
15669impl EntityInputHandler for Editor {
15670    fn text_for_range(
15671        &mut self,
15672        range_utf16: Range<usize>,
15673        adjusted_range: &mut Option<Range<usize>>,
15674        _: &mut Window,
15675        cx: &mut Context<Self>,
15676    ) -> Option<String> {
15677        let snapshot = self.buffer.read(cx).read(cx);
15678        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15679        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15680        if (start.0..end.0) != range_utf16 {
15681            adjusted_range.replace(start.0..end.0);
15682        }
15683        Some(snapshot.text_for_range(start..end).collect())
15684    }
15685
15686    fn selected_text_range(
15687        &mut self,
15688        ignore_disabled_input: bool,
15689        _: &mut Window,
15690        cx: &mut Context<Self>,
15691    ) -> Option<UTF16Selection> {
15692        // Prevent the IME menu from appearing when holding down an alphabetic key
15693        // while input is disabled.
15694        if !ignore_disabled_input && !self.input_enabled {
15695            return None;
15696        }
15697
15698        let selection = self.selections.newest::<OffsetUtf16>(cx);
15699        let range = selection.range();
15700
15701        Some(UTF16Selection {
15702            range: range.start.0..range.end.0,
15703            reversed: selection.reversed,
15704        })
15705    }
15706
15707    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15708        let snapshot = self.buffer.read(cx).read(cx);
15709        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15710        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15711    }
15712
15713    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15714        self.clear_highlights::<InputComposition>(cx);
15715        self.ime_transaction.take();
15716    }
15717
15718    fn replace_text_in_range(
15719        &mut self,
15720        range_utf16: Option<Range<usize>>,
15721        text: &str,
15722        window: &mut Window,
15723        cx: &mut Context<Self>,
15724    ) {
15725        if !self.input_enabled {
15726            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15727            return;
15728        }
15729
15730        self.transact(window, cx, |this, window, cx| {
15731            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15732                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15733                Some(this.selection_replacement_ranges(range_utf16, cx))
15734            } else {
15735                this.marked_text_ranges(cx)
15736            };
15737
15738            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15739                let newest_selection_id = this.selections.newest_anchor().id;
15740                this.selections
15741                    .all::<OffsetUtf16>(cx)
15742                    .iter()
15743                    .zip(ranges_to_replace.iter())
15744                    .find_map(|(selection, range)| {
15745                        if selection.id == newest_selection_id {
15746                            Some(
15747                                (range.start.0 as isize - selection.head().0 as isize)
15748                                    ..(range.end.0 as isize - selection.head().0 as isize),
15749                            )
15750                        } else {
15751                            None
15752                        }
15753                    })
15754            });
15755
15756            cx.emit(EditorEvent::InputHandled {
15757                utf16_range_to_replace: range_to_replace,
15758                text: text.into(),
15759            });
15760
15761            if let Some(new_selected_ranges) = new_selected_ranges {
15762                this.change_selections(None, window, cx, |selections| {
15763                    selections.select_ranges(new_selected_ranges)
15764                });
15765                this.backspace(&Default::default(), window, cx);
15766            }
15767
15768            this.handle_input(text, window, cx);
15769        });
15770
15771        if let Some(transaction) = self.ime_transaction {
15772            self.buffer.update(cx, |buffer, cx| {
15773                buffer.group_until_transaction(transaction, cx);
15774            });
15775        }
15776
15777        self.unmark_text(window, cx);
15778    }
15779
15780    fn replace_and_mark_text_in_range(
15781        &mut self,
15782        range_utf16: Option<Range<usize>>,
15783        text: &str,
15784        new_selected_range_utf16: Option<Range<usize>>,
15785        window: &mut Window,
15786        cx: &mut Context<Self>,
15787    ) {
15788        if !self.input_enabled {
15789            return;
15790        }
15791
15792        let transaction = self.transact(window, cx, |this, window, cx| {
15793            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15794                let snapshot = this.buffer.read(cx).read(cx);
15795                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15796                    for marked_range in &mut marked_ranges {
15797                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15798                        marked_range.start.0 += relative_range_utf16.start;
15799                        marked_range.start =
15800                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15801                        marked_range.end =
15802                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15803                    }
15804                }
15805                Some(marked_ranges)
15806            } else if let Some(range_utf16) = range_utf16 {
15807                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15808                Some(this.selection_replacement_ranges(range_utf16, cx))
15809            } else {
15810                None
15811            };
15812
15813            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15814                let newest_selection_id = this.selections.newest_anchor().id;
15815                this.selections
15816                    .all::<OffsetUtf16>(cx)
15817                    .iter()
15818                    .zip(ranges_to_replace.iter())
15819                    .find_map(|(selection, range)| {
15820                        if selection.id == newest_selection_id {
15821                            Some(
15822                                (range.start.0 as isize - selection.head().0 as isize)
15823                                    ..(range.end.0 as isize - selection.head().0 as isize),
15824                            )
15825                        } else {
15826                            None
15827                        }
15828                    })
15829            });
15830
15831            cx.emit(EditorEvent::InputHandled {
15832                utf16_range_to_replace: range_to_replace,
15833                text: text.into(),
15834            });
15835
15836            if let Some(ranges) = ranges_to_replace {
15837                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15838            }
15839
15840            let marked_ranges = {
15841                let snapshot = this.buffer.read(cx).read(cx);
15842                this.selections
15843                    .disjoint_anchors()
15844                    .iter()
15845                    .map(|selection| {
15846                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15847                    })
15848                    .collect::<Vec<_>>()
15849            };
15850
15851            if text.is_empty() {
15852                this.unmark_text(window, cx);
15853            } else {
15854                this.highlight_text::<InputComposition>(
15855                    marked_ranges.clone(),
15856                    HighlightStyle {
15857                        underline: Some(UnderlineStyle {
15858                            thickness: px(1.),
15859                            color: None,
15860                            wavy: false,
15861                        }),
15862                        ..Default::default()
15863                    },
15864                    cx,
15865                );
15866            }
15867
15868            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15869            let use_autoclose = this.use_autoclose;
15870            let use_auto_surround = this.use_auto_surround;
15871            this.set_use_autoclose(false);
15872            this.set_use_auto_surround(false);
15873            this.handle_input(text, window, cx);
15874            this.set_use_autoclose(use_autoclose);
15875            this.set_use_auto_surround(use_auto_surround);
15876
15877            if let Some(new_selected_range) = new_selected_range_utf16 {
15878                let snapshot = this.buffer.read(cx).read(cx);
15879                let new_selected_ranges = marked_ranges
15880                    .into_iter()
15881                    .map(|marked_range| {
15882                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15883                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15884                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15885                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15886                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15887                    })
15888                    .collect::<Vec<_>>();
15889
15890                drop(snapshot);
15891                this.change_selections(None, window, cx, |selections| {
15892                    selections.select_ranges(new_selected_ranges)
15893                });
15894            }
15895        });
15896
15897        self.ime_transaction = self.ime_transaction.or(transaction);
15898        if let Some(transaction) = self.ime_transaction {
15899            self.buffer.update(cx, |buffer, cx| {
15900                buffer.group_until_transaction(transaction, cx);
15901            });
15902        }
15903
15904        if self.text_highlights::<InputComposition>(cx).is_none() {
15905            self.ime_transaction.take();
15906        }
15907    }
15908
15909    fn bounds_for_range(
15910        &mut self,
15911        range_utf16: Range<usize>,
15912        element_bounds: gpui::Bounds<Pixels>,
15913        window: &mut Window,
15914        cx: &mut Context<Self>,
15915    ) -> Option<gpui::Bounds<Pixels>> {
15916        let text_layout_details = self.text_layout_details(window);
15917        let gpui::Size {
15918            width: em_width,
15919            height: line_height,
15920        } = self.character_size(window);
15921
15922        let snapshot = self.snapshot(window, cx);
15923        let scroll_position = snapshot.scroll_position();
15924        let scroll_left = scroll_position.x * em_width;
15925
15926        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15927        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15928            + self.gutter_dimensions.width
15929            + self.gutter_dimensions.margin;
15930        let y = line_height * (start.row().as_f32() - scroll_position.y);
15931
15932        Some(Bounds {
15933            origin: element_bounds.origin + point(x, y),
15934            size: size(em_width, line_height),
15935        })
15936    }
15937
15938    fn character_index_for_point(
15939        &mut self,
15940        point: gpui::Point<Pixels>,
15941        _window: &mut Window,
15942        _cx: &mut Context<Self>,
15943    ) -> Option<usize> {
15944        let position_map = self.last_position_map.as_ref()?;
15945        if !position_map.text_hitbox.contains(&point) {
15946            return None;
15947        }
15948        let display_point = position_map.point_for_position(point).previous_valid;
15949        let anchor = position_map
15950            .snapshot
15951            .display_point_to_anchor(display_point, Bias::Left);
15952        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
15953        Some(utf16_offset.0)
15954    }
15955}
15956
15957trait SelectionExt {
15958    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15959    fn spanned_rows(
15960        &self,
15961        include_end_if_at_line_start: bool,
15962        map: &DisplaySnapshot,
15963    ) -> Range<MultiBufferRow>;
15964}
15965
15966impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15967    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15968        let start = self
15969            .start
15970            .to_point(&map.buffer_snapshot)
15971            .to_display_point(map);
15972        let end = self
15973            .end
15974            .to_point(&map.buffer_snapshot)
15975            .to_display_point(map);
15976        if self.reversed {
15977            end..start
15978        } else {
15979            start..end
15980        }
15981    }
15982
15983    fn spanned_rows(
15984        &self,
15985        include_end_if_at_line_start: bool,
15986        map: &DisplaySnapshot,
15987    ) -> Range<MultiBufferRow> {
15988        let start = self.start.to_point(&map.buffer_snapshot);
15989        let mut end = self.end.to_point(&map.buffer_snapshot);
15990        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15991            end.row -= 1;
15992        }
15993
15994        let buffer_start = map.prev_line_boundary(start).0;
15995        let buffer_end = map.next_line_boundary(end).0;
15996        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15997    }
15998}
15999
16000impl<T: InvalidationRegion> InvalidationStack<T> {
16001    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16002    where
16003        S: Clone + ToOffset,
16004    {
16005        while let Some(region) = self.last() {
16006            let all_selections_inside_invalidation_ranges =
16007                if selections.len() == region.ranges().len() {
16008                    selections
16009                        .iter()
16010                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16011                        .all(|(selection, invalidation_range)| {
16012                            let head = selection.head().to_offset(buffer);
16013                            invalidation_range.start <= head && invalidation_range.end >= head
16014                        })
16015                } else {
16016                    false
16017                };
16018
16019            if all_selections_inside_invalidation_ranges {
16020                break;
16021            } else {
16022                self.pop();
16023            }
16024        }
16025    }
16026}
16027
16028impl<T> Default for InvalidationStack<T> {
16029    fn default() -> Self {
16030        Self(Default::default())
16031    }
16032}
16033
16034impl<T> Deref for InvalidationStack<T> {
16035    type Target = Vec<T>;
16036
16037    fn deref(&self) -> &Self::Target {
16038        &self.0
16039    }
16040}
16041
16042impl<T> DerefMut for InvalidationStack<T> {
16043    fn deref_mut(&mut self) -> &mut Self::Target {
16044        &mut self.0
16045    }
16046}
16047
16048impl InvalidationRegion for SnippetState {
16049    fn ranges(&self) -> &[Range<Anchor>] {
16050        &self.ranges[self.active_index]
16051    }
16052}
16053
16054pub fn diagnostic_block_renderer(
16055    diagnostic: Diagnostic,
16056    max_message_rows: Option<u8>,
16057    allow_closing: bool,
16058    _is_valid: bool,
16059) -> RenderBlock {
16060    let (text_without_backticks, code_ranges) =
16061        highlight_diagnostic_message(&diagnostic, max_message_rows);
16062
16063    Arc::new(move |cx: &mut BlockContext| {
16064        let group_id: SharedString = cx.block_id.to_string().into();
16065
16066        let mut text_style = cx.window.text_style().clone();
16067        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16068        let theme_settings = ThemeSettings::get_global(cx);
16069        text_style.font_family = theme_settings.buffer_font.family.clone();
16070        text_style.font_style = theme_settings.buffer_font.style;
16071        text_style.font_features = theme_settings.buffer_font.features.clone();
16072        text_style.font_weight = theme_settings.buffer_font.weight;
16073
16074        let multi_line_diagnostic = diagnostic.message.contains('\n');
16075
16076        let buttons = |diagnostic: &Diagnostic| {
16077            if multi_line_diagnostic {
16078                v_flex()
16079            } else {
16080                h_flex()
16081            }
16082            .when(allow_closing, |div| {
16083                div.children(diagnostic.is_primary.then(|| {
16084                    IconButton::new("close-block", IconName::XCircle)
16085                        .icon_color(Color::Muted)
16086                        .size(ButtonSize::Compact)
16087                        .style(ButtonStyle::Transparent)
16088                        .visible_on_hover(group_id.clone())
16089                        .on_click(move |_click, window, cx| {
16090                            window.dispatch_action(Box::new(Cancel), cx)
16091                        })
16092                        .tooltip(|window, cx| {
16093                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16094                        })
16095                }))
16096            })
16097            .child(
16098                IconButton::new("copy-block", IconName::Copy)
16099                    .icon_color(Color::Muted)
16100                    .size(ButtonSize::Compact)
16101                    .style(ButtonStyle::Transparent)
16102                    .visible_on_hover(group_id.clone())
16103                    .on_click({
16104                        let message = diagnostic.message.clone();
16105                        move |_click, _, cx| {
16106                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16107                        }
16108                    })
16109                    .tooltip(Tooltip::text("Copy diagnostic message")),
16110            )
16111        };
16112
16113        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16114            AvailableSpace::min_size(),
16115            cx.window,
16116            cx.app,
16117        );
16118
16119        h_flex()
16120            .id(cx.block_id)
16121            .group(group_id.clone())
16122            .relative()
16123            .size_full()
16124            .block_mouse_down()
16125            .pl(cx.gutter_dimensions.width)
16126            .w(cx.max_width - cx.gutter_dimensions.full_width())
16127            .child(
16128                div()
16129                    .flex()
16130                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16131                    .flex_shrink(),
16132            )
16133            .child(buttons(&diagnostic))
16134            .child(div().flex().flex_shrink_0().child(
16135                StyledText::new(text_without_backticks.clone()).with_highlights(
16136                    &text_style,
16137                    code_ranges.iter().map(|range| {
16138                        (
16139                            range.clone(),
16140                            HighlightStyle {
16141                                font_weight: Some(FontWeight::BOLD),
16142                                ..Default::default()
16143                            },
16144                        )
16145                    }),
16146                ),
16147            ))
16148            .into_any_element()
16149    })
16150}
16151
16152fn inline_completion_edit_text(
16153    current_snapshot: &BufferSnapshot,
16154    edits: &[(Range<Anchor>, String)],
16155    edit_preview: &EditPreview,
16156    include_deletions: bool,
16157    cx: &App,
16158) -> HighlightedText {
16159    let edits = edits
16160        .iter()
16161        .map(|(anchor, text)| {
16162            (
16163                anchor.start.text_anchor..anchor.end.text_anchor,
16164                text.clone(),
16165            )
16166        })
16167        .collect::<Vec<_>>();
16168
16169    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16170}
16171
16172pub fn highlight_diagnostic_message(
16173    diagnostic: &Diagnostic,
16174    mut max_message_rows: Option<u8>,
16175) -> (SharedString, Vec<Range<usize>>) {
16176    let mut text_without_backticks = String::new();
16177    let mut code_ranges = Vec::new();
16178
16179    if let Some(source) = &diagnostic.source {
16180        text_without_backticks.push_str(source);
16181        code_ranges.push(0..source.len());
16182        text_without_backticks.push_str(": ");
16183    }
16184
16185    let mut prev_offset = 0;
16186    let mut in_code_block = false;
16187    let has_row_limit = max_message_rows.is_some();
16188    let mut newline_indices = diagnostic
16189        .message
16190        .match_indices('\n')
16191        .filter(|_| has_row_limit)
16192        .map(|(ix, _)| ix)
16193        .fuse()
16194        .peekable();
16195
16196    for (quote_ix, _) in diagnostic
16197        .message
16198        .match_indices('`')
16199        .chain([(diagnostic.message.len(), "")])
16200    {
16201        let mut first_newline_ix = None;
16202        let mut last_newline_ix = None;
16203        while let Some(newline_ix) = newline_indices.peek() {
16204            if *newline_ix < quote_ix {
16205                if first_newline_ix.is_none() {
16206                    first_newline_ix = Some(*newline_ix);
16207                }
16208                last_newline_ix = Some(*newline_ix);
16209
16210                if let Some(rows_left) = &mut max_message_rows {
16211                    if *rows_left == 0 {
16212                        break;
16213                    } else {
16214                        *rows_left -= 1;
16215                    }
16216                }
16217                let _ = newline_indices.next();
16218            } else {
16219                break;
16220            }
16221        }
16222        let prev_len = text_without_backticks.len();
16223        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16224        text_without_backticks.push_str(new_text);
16225        if in_code_block {
16226            code_ranges.push(prev_len..text_without_backticks.len());
16227        }
16228        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16229        in_code_block = !in_code_block;
16230        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16231            text_without_backticks.push_str("...");
16232            break;
16233        }
16234    }
16235
16236    (text_without_backticks.into(), code_ranges)
16237}
16238
16239fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16240    match severity {
16241        DiagnosticSeverity::ERROR => colors.error,
16242        DiagnosticSeverity::WARNING => colors.warning,
16243        DiagnosticSeverity::INFORMATION => colors.info,
16244        DiagnosticSeverity::HINT => colors.info,
16245        _ => colors.ignored,
16246    }
16247}
16248
16249pub fn styled_runs_for_code_label<'a>(
16250    label: &'a CodeLabel,
16251    syntax_theme: &'a theme::SyntaxTheme,
16252) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16253    let fade_out = HighlightStyle {
16254        fade_out: Some(0.35),
16255        ..Default::default()
16256    };
16257
16258    let mut prev_end = label.filter_range.end;
16259    label
16260        .runs
16261        .iter()
16262        .enumerate()
16263        .flat_map(move |(ix, (range, highlight_id))| {
16264            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16265                style
16266            } else {
16267                return Default::default();
16268            };
16269            let mut muted_style = style;
16270            muted_style.highlight(fade_out);
16271
16272            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16273            if range.start >= label.filter_range.end {
16274                if range.start > prev_end {
16275                    runs.push((prev_end..range.start, fade_out));
16276                }
16277                runs.push((range.clone(), muted_style));
16278            } else if range.end <= label.filter_range.end {
16279                runs.push((range.clone(), style));
16280            } else {
16281                runs.push((range.start..label.filter_range.end, style));
16282                runs.push((label.filter_range.end..range.end, muted_style));
16283            }
16284            prev_end = cmp::max(prev_end, range.end);
16285
16286            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16287                runs.push((prev_end..label.text.len(), fade_out));
16288            }
16289
16290            runs
16291        })
16292}
16293
16294pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16295    let mut prev_index = 0;
16296    let mut prev_codepoint: Option<char> = None;
16297    text.char_indices()
16298        .chain([(text.len(), '\0')])
16299        .filter_map(move |(index, codepoint)| {
16300            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16301            let is_boundary = index == text.len()
16302                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16303                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16304            if is_boundary {
16305                let chunk = &text[prev_index..index];
16306                prev_index = index;
16307                Some(chunk)
16308            } else {
16309                None
16310            }
16311        })
16312}
16313
16314pub trait RangeToAnchorExt: Sized {
16315    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16316
16317    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16318        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16319        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16320    }
16321}
16322
16323impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16324    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16325        let start_offset = self.start.to_offset(snapshot);
16326        let end_offset = self.end.to_offset(snapshot);
16327        if start_offset == end_offset {
16328            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16329        } else {
16330            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16331        }
16332    }
16333}
16334
16335pub trait RowExt {
16336    fn as_f32(&self) -> f32;
16337
16338    fn next_row(&self) -> Self;
16339
16340    fn previous_row(&self) -> Self;
16341
16342    fn minus(&self, other: Self) -> u32;
16343}
16344
16345impl RowExt for DisplayRow {
16346    fn as_f32(&self) -> f32 {
16347        self.0 as f32
16348    }
16349
16350    fn next_row(&self) -> Self {
16351        Self(self.0 + 1)
16352    }
16353
16354    fn previous_row(&self) -> Self {
16355        Self(self.0.saturating_sub(1))
16356    }
16357
16358    fn minus(&self, other: Self) -> u32 {
16359        self.0 - other.0
16360    }
16361}
16362
16363impl RowExt for MultiBufferRow {
16364    fn as_f32(&self) -> f32 {
16365        self.0 as f32
16366    }
16367
16368    fn next_row(&self) -> Self {
16369        Self(self.0 + 1)
16370    }
16371
16372    fn previous_row(&self) -> Self {
16373        Self(self.0.saturating_sub(1))
16374    }
16375
16376    fn minus(&self, other: Self) -> u32 {
16377        self.0 - other.0
16378    }
16379}
16380
16381trait RowRangeExt {
16382    type Row;
16383
16384    fn len(&self) -> usize;
16385
16386    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16387}
16388
16389impl RowRangeExt for Range<MultiBufferRow> {
16390    type Row = MultiBufferRow;
16391
16392    fn len(&self) -> usize {
16393        (self.end.0 - self.start.0) as usize
16394    }
16395
16396    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16397        (self.start.0..self.end.0).map(MultiBufferRow)
16398    }
16399}
16400
16401impl RowRangeExt for Range<DisplayRow> {
16402    type Row = DisplayRow;
16403
16404    fn len(&self) -> usize {
16405        (self.end.0 - self.start.0) as usize
16406    }
16407
16408    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16409        (self.start.0..self.end.0).map(DisplayRow)
16410    }
16411}
16412
16413/// If select range has more than one line, we
16414/// just point the cursor to range.start.
16415fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16416    if range.start.row == range.end.row {
16417        range
16418    } else {
16419        range.start..range.start
16420    }
16421}
16422pub struct KillRing(ClipboardItem);
16423impl Global for KillRing {}
16424
16425const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16426
16427fn all_edits_insertions_or_deletions(
16428    edits: &Vec<(Range<Anchor>, String)>,
16429    snapshot: &MultiBufferSnapshot,
16430) -> bool {
16431    let mut all_insertions = true;
16432    let mut all_deletions = true;
16433
16434    for (range, new_text) in edits.iter() {
16435        let range_is_empty = range.to_offset(&snapshot).is_empty();
16436        let text_is_empty = new_text.is_empty();
16437
16438        if range_is_empty != text_is_empty {
16439            if range_is_empty {
16440                all_deletions = false;
16441            } else {
16442                all_insertions = false;
16443            }
16444        } else {
16445            return false;
16446        }
16447
16448        if !all_insertions && !all_deletions {
16449            return false;
16450        }
16451    }
16452    all_insertions || all_deletions
16453}