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