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::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   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    expect_bounds_change: Option<Bounds<Pixels>>,
  719    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  720    tasks_update_task: Option<Task<()>>,
  721    in_project_search: bool,
  722    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  723    breadcrumb_header: Option<String>,
  724    focused_block: Option<FocusedBlock>,
  725    next_scroll_position: NextScrollCursorCenterTopBottom,
  726    addons: HashMap<TypeId, Box<dyn Addon>>,
  727    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  728    selection_mark_mode: bool,
  729    toggle_fold_multiple_buffers: Task<()>,
  730    _scroll_cursor_center_top_bottom_task: Task<()>,
  731}
  732
  733#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  734enum NextScrollCursorCenterTopBottom {
  735    #[default]
  736    Center,
  737    Top,
  738    Bottom,
  739}
  740
  741impl NextScrollCursorCenterTopBottom {
  742    fn next(&self) -> Self {
  743        match self {
  744            Self::Center => Self::Top,
  745            Self::Top => Self::Bottom,
  746            Self::Bottom => Self::Center,
  747        }
  748    }
  749}
  750
  751#[derive(Clone)]
  752pub struct EditorSnapshot {
  753    pub mode: EditorMode,
  754    show_gutter: bool,
  755    show_line_numbers: Option<bool>,
  756    show_git_diff_gutter: Option<bool>,
  757    show_code_actions: Option<bool>,
  758    show_runnables: Option<bool>,
  759    git_blame_gutter_max_author_length: Option<usize>,
  760    pub display_snapshot: DisplaySnapshot,
  761    pub placeholder_text: Option<Arc<str>>,
  762    is_focused: bool,
  763    scroll_anchor: ScrollAnchor,
  764    ongoing_scroll: OngoingScroll,
  765    current_line_highlight: CurrentLineHighlight,
  766    gutter_hovered: bool,
  767}
  768
  769const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  770
  771#[derive(Default, Debug, Clone, Copy)]
  772pub struct GutterDimensions {
  773    pub left_padding: Pixels,
  774    pub right_padding: Pixels,
  775    pub width: Pixels,
  776    pub margin: Pixels,
  777    pub git_blame_entries_width: Option<Pixels>,
  778}
  779
  780impl GutterDimensions {
  781    /// The full width of the space taken up by the gutter.
  782    pub fn full_width(&self) -> Pixels {
  783        self.margin + self.width
  784    }
  785
  786    /// The width of the space reserved for the fold indicators,
  787    /// use alongside 'justify_end' and `gutter_width` to
  788    /// right align content with the line numbers
  789    pub fn fold_area_width(&self) -> Pixels {
  790        self.margin + self.right_padding
  791    }
  792}
  793
  794#[derive(Debug)]
  795pub struct RemoteSelection {
  796    pub replica_id: ReplicaId,
  797    pub selection: Selection<Anchor>,
  798    pub cursor_shape: CursorShape,
  799    pub peer_id: PeerId,
  800    pub line_mode: bool,
  801    pub participant_index: Option<ParticipantIndex>,
  802    pub user_name: Option<SharedString>,
  803}
  804
  805#[derive(Clone, Debug)]
  806struct SelectionHistoryEntry {
  807    selections: Arc<[Selection<Anchor>]>,
  808    select_next_state: Option<SelectNextState>,
  809    select_prev_state: Option<SelectNextState>,
  810    add_selections_state: Option<AddSelectionsState>,
  811}
  812
  813enum SelectionHistoryMode {
  814    Normal,
  815    Undoing,
  816    Redoing,
  817}
  818
  819#[derive(Clone, PartialEq, Eq, Hash)]
  820struct HoveredCursor {
  821    replica_id: u16,
  822    selection_id: usize,
  823}
  824
  825impl Default for SelectionHistoryMode {
  826    fn default() -> Self {
  827        Self::Normal
  828    }
  829}
  830
  831#[derive(Default)]
  832struct SelectionHistory {
  833    #[allow(clippy::type_complexity)]
  834    selections_by_transaction:
  835        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  836    mode: SelectionHistoryMode,
  837    undo_stack: VecDeque<SelectionHistoryEntry>,
  838    redo_stack: VecDeque<SelectionHistoryEntry>,
  839}
  840
  841impl SelectionHistory {
  842    fn insert_transaction(
  843        &mut self,
  844        transaction_id: TransactionId,
  845        selections: Arc<[Selection<Anchor>]>,
  846    ) {
  847        self.selections_by_transaction
  848            .insert(transaction_id, (selections, None));
  849    }
  850
  851    #[allow(clippy::type_complexity)]
  852    fn transaction(
  853        &self,
  854        transaction_id: TransactionId,
  855    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  856        self.selections_by_transaction.get(&transaction_id)
  857    }
  858
  859    #[allow(clippy::type_complexity)]
  860    fn transaction_mut(
  861        &mut self,
  862        transaction_id: TransactionId,
  863    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  864        self.selections_by_transaction.get_mut(&transaction_id)
  865    }
  866
  867    fn push(&mut self, entry: SelectionHistoryEntry) {
  868        if !entry.selections.is_empty() {
  869            match self.mode {
  870                SelectionHistoryMode::Normal => {
  871                    self.push_undo(entry);
  872                    self.redo_stack.clear();
  873                }
  874                SelectionHistoryMode::Undoing => self.push_redo(entry),
  875                SelectionHistoryMode::Redoing => self.push_undo(entry),
  876            }
  877        }
  878    }
  879
  880    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  881        if self
  882            .undo_stack
  883            .back()
  884            .map_or(true, |e| e.selections != entry.selections)
  885        {
  886            self.undo_stack.push_back(entry);
  887            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  888                self.undo_stack.pop_front();
  889            }
  890        }
  891    }
  892
  893    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  894        if self
  895            .redo_stack
  896            .back()
  897            .map_or(true, |e| e.selections != entry.selections)
  898        {
  899            self.redo_stack.push_back(entry);
  900            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  901                self.redo_stack.pop_front();
  902            }
  903        }
  904    }
  905}
  906
  907struct RowHighlight {
  908    index: usize,
  909    range: Range<Anchor>,
  910    color: Hsla,
  911    should_autoscroll: bool,
  912}
  913
  914#[derive(Clone, Debug)]
  915struct AddSelectionsState {
  916    above: bool,
  917    stack: Vec<usize>,
  918}
  919
  920#[derive(Clone)]
  921struct SelectNextState {
  922    query: AhoCorasick,
  923    wordwise: bool,
  924    done: bool,
  925}
  926
  927impl std::fmt::Debug for SelectNextState {
  928    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  929        f.debug_struct(std::any::type_name::<Self>())
  930            .field("wordwise", &self.wordwise)
  931            .field("done", &self.done)
  932            .finish()
  933    }
  934}
  935
  936#[derive(Debug)]
  937struct AutocloseRegion {
  938    selection_id: usize,
  939    range: Range<Anchor>,
  940    pair: BracketPair,
  941}
  942
  943#[derive(Debug)]
  944struct SnippetState {
  945    ranges: Vec<Vec<Range<Anchor>>>,
  946    active_index: usize,
  947    choices: Vec<Option<Vec<String>>>,
  948}
  949
  950#[doc(hidden)]
  951pub struct RenameState {
  952    pub range: Range<Anchor>,
  953    pub old_name: Arc<str>,
  954    pub editor: Entity<Editor>,
  955    block_id: CustomBlockId,
  956}
  957
  958struct InvalidationStack<T>(Vec<T>);
  959
  960struct RegisteredInlineCompletionProvider {
  961    provider: Arc<dyn InlineCompletionProviderHandle>,
  962    _subscription: Subscription,
  963}
  964
  965#[derive(Debug)]
  966struct ActiveDiagnosticGroup {
  967    primary_range: Range<Anchor>,
  968    primary_message: String,
  969    group_id: usize,
  970    blocks: HashMap<CustomBlockId, Diagnostic>,
  971    is_valid: bool,
  972}
  973
  974#[derive(Serialize, Deserialize, Clone, Debug)]
  975pub struct ClipboardSelection {
  976    pub len: usize,
  977    pub is_entire_line: bool,
  978    pub first_line_indent: u32,
  979}
  980
  981#[derive(Debug)]
  982pub(crate) struct NavigationData {
  983    cursor_anchor: Anchor,
  984    cursor_position: Point,
  985    scroll_anchor: ScrollAnchor,
  986    scroll_top_row: u32,
  987}
  988
  989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  990pub enum GotoDefinitionKind {
  991    Symbol,
  992    Declaration,
  993    Type,
  994    Implementation,
  995}
  996
  997#[derive(Debug, Clone)]
  998enum InlayHintRefreshReason {
  999    Toggle(bool),
 1000    SettingsChange(InlayHintSettings),
 1001    NewLinesShown,
 1002    BufferEdited(HashSet<Arc<Language>>),
 1003    RefreshRequested,
 1004    ExcerptsRemoved(Vec<ExcerptId>),
 1005}
 1006
 1007impl InlayHintRefreshReason {
 1008    fn description(&self) -> &'static str {
 1009        match self {
 1010            Self::Toggle(_) => "toggle",
 1011            Self::SettingsChange(_) => "settings change",
 1012            Self::NewLinesShown => "new lines shown",
 1013            Self::BufferEdited(_) => "buffer edited",
 1014            Self::RefreshRequested => "refresh requested",
 1015            Self::ExcerptsRemoved(_) => "excerpts removed",
 1016        }
 1017    }
 1018}
 1019
 1020pub enum FormatTarget {
 1021    Buffers,
 1022    Ranges(Vec<Range<MultiBufferPoint>>),
 1023}
 1024
 1025pub(crate) struct FocusedBlock {
 1026    id: BlockId,
 1027    focus_handle: WeakFocusHandle,
 1028}
 1029
 1030#[derive(Clone)]
 1031enum JumpData {
 1032    MultiBufferRow {
 1033        row: MultiBufferRow,
 1034        line_offset_from_top: u32,
 1035    },
 1036    MultiBufferPoint {
 1037        excerpt_id: ExcerptId,
 1038        position: Point,
 1039        anchor: text::Anchor,
 1040        line_offset_from_top: u32,
 1041    },
 1042}
 1043
 1044pub enum MultibufferSelectionMode {
 1045    First,
 1046    All,
 1047}
 1048
 1049impl Editor {
 1050    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1051        let buffer = cx.new(|cx| Buffer::local("", cx));
 1052        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1053        Self::new(
 1054            EditorMode::SingleLine { auto_width: false },
 1055            buffer,
 1056            None,
 1057            false,
 1058            window,
 1059            cx,
 1060        )
 1061    }
 1062
 1063    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1064        let buffer = cx.new(|cx| Buffer::local("", cx));
 1065        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1066        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1067    }
 1068
 1069    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1070        let buffer = cx.new(|cx| Buffer::local("", cx));
 1071        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1072        Self::new(
 1073            EditorMode::SingleLine { auto_width: true },
 1074            buffer,
 1075            None,
 1076            false,
 1077            window,
 1078            cx,
 1079        )
 1080    }
 1081
 1082    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1083        let buffer = cx.new(|cx| Buffer::local("", cx));
 1084        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1085        Self::new(
 1086            EditorMode::AutoHeight { max_lines },
 1087            buffer,
 1088            None,
 1089            false,
 1090            window,
 1091            cx,
 1092        )
 1093    }
 1094
 1095    pub fn for_buffer(
 1096        buffer: Entity<Buffer>,
 1097        project: Option<Entity<Project>>,
 1098        window: &mut Window,
 1099        cx: &mut Context<Self>,
 1100    ) -> Self {
 1101        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1102        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1103    }
 1104
 1105    pub fn for_multibuffer(
 1106        buffer: Entity<MultiBuffer>,
 1107        project: Option<Entity<Project>>,
 1108        show_excerpt_controls: bool,
 1109        window: &mut Window,
 1110        cx: &mut Context<Self>,
 1111    ) -> Self {
 1112        Self::new(
 1113            EditorMode::Full,
 1114            buffer,
 1115            project,
 1116            show_excerpt_controls,
 1117            window,
 1118            cx,
 1119        )
 1120    }
 1121
 1122    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1123        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1124        let mut clone = Self::new(
 1125            self.mode,
 1126            self.buffer.clone(),
 1127            self.project.clone(),
 1128            show_excerpt_controls,
 1129            window,
 1130            cx,
 1131        );
 1132        self.display_map.update(cx, |display_map, cx| {
 1133            let snapshot = display_map.snapshot(cx);
 1134            clone.display_map.update(cx, |display_map, cx| {
 1135                display_map.set_state(&snapshot, cx);
 1136            });
 1137        });
 1138        clone.selections.clone_state(&self.selections);
 1139        clone.scroll_manager.clone_state(&self.scroll_manager);
 1140        clone.searchable = self.searchable;
 1141        clone
 1142    }
 1143
 1144    pub fn new(
 1145        mode: EditorMode,
 1146        buffer: Entity<MultiBuffer>,
 1147        project: Option<Entity<Project>>,
 1148        show_excerpt_controls: bool,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let style = window.text_style();
 1153        let font_size = style.font_size.to_pixels(window.rem_size());
 1154        let editor = cx.entity().downgrade();
 1155        let fold_placeholder = FoldPlaceholder {
 1156            constrain_width: true,
 1157            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1158                let editor = editor.clone();
 1159                div()
 1160                    .id(fold_id)
 1161                    .bg(cx.theme().colors().ghost_element_background)
 1162                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1163                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1164                    .rounded_sm()
 1165                    .size_full()
 1166                    .cursor_pointer()
 1167                    .child("")
 1168                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1169                    .on_click(move |_, _window, cx| {
 1170                        editor
 1171                            .update(cx, |editor, cx| {
 1172                                editor.unfold_ranges(
 1173                                    &[fold_range.start..fold_range.end],
 1174                                    true,
 1175                                    false,
 1176                                    cx,
 1177                                );
 1178                                cx.stop_propagation();
 1179                            })
 1180                            .ok();
 1181                    })
 1182                    .into_any()
 1183            }),
 1184            merge_adjacent: true,
 1185            ..Default::default()
 1186        };
 1187        let display_map = cx.new(|cx| {
 1188            DisplayMap::new(
 1189                buffer.clone(),
 1190                style.font(),
 1191                font_size,
 1192                None,
 1193                show_excerpt_controls,
 1194                FILE_HEADER_HEIGHT,
 1195                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1196                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1197                fold_placeholder,
 1198                cx,
 1199            )
 1200        });
 1201
 1202        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1203
 1204        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1205
 1206        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1207            .then(|| language_settings::SoftWrap::None);
 1208
 1209        let mut project_subscriptions = Vec::new();
 1210        if mode == EditorMode::Full {
 1211            if let Some(project) = project.as_ref() {
 1212                if buffer.read(cx).is_singleton() {
 1213                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1214                        cx.emit(EditorEvent::TitleChanged);
 1215                    }));
 1216                }
 1217                project_subscriptions.push(cx.subscribe_in(
 1218                    project,
 1219                    window,
 1220                    |editor, _, event, window, cx| {
 1221                        if let project::Event::RefreshInlayHints = event {
 1222                            editor
 1223                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1224                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1225                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1226                                let focus_handle = editor.focus_handle(cx);
 1227                                if focus_handle.is_focused(window) {
 1228                                    let snapshot = buffer.read(cx).snapshot();
 1229                                    for (range, snippet) in snippet_edits {
 1230                                        let editor_range =
 1231                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1232                                        editor
 1233                                            .insert_snippet(
 1234                                                &[editor_range],
 1235                                                snippet.clone(),
 1236                                                window,
 1237                                                cx,
 1238                                            )
 1239                                            .ok();
 1240                                    }
 1241                                }
 1242                            }
 1243                        }
 1244                    },
 1245                ));
 1246                if let Some(task_inventory) = project
 1247                    .read(cx)
 1248                    .task_store()
 1249                    .read(cx)
 1250                    .task_inventory()
 1251                    .cloned()
 1252                {
 1253                    project_subscriptions.push(cx.observe_in(
 1254                        &task_inventory,
 1255                        window,
 1256                        |editor, _, window, cx| {
 1257                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1258                        },
 1259                    ));
 1260                }
 1261            }
 1262        }
 1263
 1264        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1265
 1266        let inlay_hint_settings =
 1267            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1268        let focus_handle = cx.focus_handle();
 1269        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1270            .detach();
 1271        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1272            .detach();
 1273        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1274            .detach();
 1275        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1276            .detach();
 1277
 1278        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1279            Some(false)
 1280        } else {
 1281            None
 1282        };
 1283
 1284        let mut code_action_providers = Vec::new();
 1285        if let Some(project) = project.clone() {
 1286            get_unstaged_changes_for_buffers(
 1287                &project,
 1288                buffer.read(cx).all_buffers(),
 1289                buffer.clone(),
 1290                cx,
 1291            );
 1292            code_action_providers.push(Rc::new(project) as Rc<_>);
 1293        }
 1294
 1295        let mut this = Self {
 1296            focus_handle,
 1297            show_cursor_when_unfocused: false,
 1298            last_focused_descendant: None,
 1299            buffer: buffer.clone(),
 1300            display_map: display_map.clone(),
 1301            selections,
 1302            scroll_manager: ScrollManager::new(cx),
 1303            columnar_selection_tail: None,
 1304            add_selections_state: None,
 1305            select_next_state: None,
 1306            select_prev_state: None,
 1307            selection_history: Default::default(),
 1308            autoclose_regions: Default::default(),
 1309            snippet_stack: Default::default(),
 1310            select_larger_syntax_node_stack: Vec::new(),
 1311            ime_transaction: Default::default(),
 1312            active_diagnostics: None,
 1313            soft_wrap_mode_override,
 1314            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1315            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1316            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1317            project,
 1318            blink_manager: blink_manager.clone(),
 1319            show_local_selections: true,
 1320            show_scrollbars: true,
 1321            mode,
 1322            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1323            show_gutter: mode == EditorMode::Full,
 1324            show_line_numbers: None,
 1325            use_relative_line_numbers: None,
 1326            show_git_diff_gutter: None,
 1327            show_code_actions: None,
 1328            show_runnables: None,
 1329            show_wrap_guides: None,
 1330            show_indent_guides,
 1331            placeholder_text: None,
 1332            highlight_order: 0,
 1333            highlighted_rows: HashMap::default(),
 1334            background_highlights: Default::default(),
 1335            gutter_highlights: TreeMap::default(),
 1336            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1337            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1338            nav_history: None,
 1339            context_menu: RefCell::new(None),
 1340            mouse_context_menu: None,
 1341            completion_tasks: Default::default(),
 1342            signature_help_state: SignatureHelpState::default(),
 1343            auto_signature_help: None,
 1344            find_all_references_task_sources: Vec::new(),
 1345            next_completion_id: 0,
 1346            next_inlay_id: 0,
 1347            code_action_providers,
 1348            available_code_actions: Default::default(),
 1349            code_actions_task: Default::default(),
 1350            document_highlights_task: Default::default(),
 1351            linked_editing_range_task: Default::default(),
 1352            pending_rename: Default::default(),
 1353            searchable: true,
 1354            cursor_shape: EditorSettings::get_global(cx)
 1355                .cursor_shape
 1356                .unwrap_or_default(),
 1357            current_line_highlight: None,
 1358            autoindent_mode: Some(AutoindentMode::EachLine),
 1359            collapse_matches: false,
 1360            workspace: None,
 1361            input_enabled: true,
 1362            use_modal_editing: mode == EditorMode::Full,
 1363            read_only: false,
 1364            use_autoclose: true,
 1365            use_auto_surround: true,
 1366            auto_replace_emoji_shortcode: false,
 1367            leader_peer_id: None,
 1368            remote_id: None,
 1369            hover_state: Default::default(),
 1370            pending_mouse_down: None,
 1371            hovered_link_state: Default::default(),
 1372            inline_completion_provider: None,
 1373            active_inline_completion: None,
 1374            stale_inline_completion_in_menu: None,
 1375            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1376
 1377            gutter_hovered: false,
 1378            pixel_position_of_newest_cursor: None,
 1379            last_bounds: None,
 1380            expect_bounds_change: None,
 1381            gutter_dimensions: GutterDimensions::default(),
 1382            style: None,
 1383            show_cursor_names: false,
 1384            hovered_cursors: Default::default(),
 1385            next_editor_action_id: EditorActionId::default(),
 1386            editor_actions: Rc::default(),
 1387            show_inline_completions_override: None,
 1388            enable_inline_completions: true,
 1389            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1390            custom_context_menu: None,
 1391            show_git_blame_gutter: false,
 1392            show_git_blame_inline: false,
 1393            show_selection_menu: None,
 1394            show_git_blame_inline_delay_task: None,
 1395            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1396            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1397                .session
 1398                .restore_unsaved_buffers,
 1399            blame: None,
 1400            blame_subscription: None,
 1401            tasks: Default::default(),
 1402            _subscriptions: vec![
 1403                cx.observe(&buffer, Self::on_buffer_changed),
 1404                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1405                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1406                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1407                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1408                cx.observe_window_activation(window, |editor, window, cx| {
 1409                    let active = window.is_window_active();
 1410                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1411                        if active {
 1412                            blink_manager.enable(cx);
 1413                        } else {
 1414                            blink_manager.disable(cx);
 1415                        }
 1416                    });
 1417                }),
 1418            ],
 1419            tasks_update_task: None,
 1420            linked_edit_ranges: Default::default(),
 1421            in_project_search: false,
 1422            previous_search_ranges: None,
 1423            breadcrumb_header: None,
 1424            focused_block: None,
 1425            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1426            addons: HashMap::default(),
 1427            registered_buffers: HashMap::default(),
 1428            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1429            selection_mark_mode: false,
 1430            toggle_fold_multiple_buffers: Task::ready(()),
 1431            text_style_refinement: None,
 1432        };
 1433        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1434        this._subscriptions.extend(project_subscriptions);
 1435
 1436        this.end_selection(window, cx);
 1437        this.scroll_manager.show_scrollbar(window, cx);
 1438
 1439        if mode == EditorMode::Full {
 1440            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1441            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1442
 1443            if this.git_blame_inline_enabled {
 1444                this.git_blame_inline_enabled = true;
 1445                this.start_git_blame_inline(false, window, cx);
 1446            }
 1447
 1448            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1449                if let Some(project) = this.project.as_ref() {
 1450                    let lsp_store = project.read(cx).lsp_store();
 1451                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1452                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1453                    });
 1454                    this.registered_buffers
 1455                        .insert(buffer.read(cx).remote_id(), handle);
 1456                }
 1457            }
 1458        }
 1459
 1460        this.report_editor_event("Editor Opened", None, cx);
 1461        this
 1462    }
 1463
 1464    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1465        self.mouse_context_menu
 1466            .as_ref()
 1467            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1468    }
 1469
 1470    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1471        let mut key_context = KeyContext::new_with_defaults();
 1472        key_context.add("Editor");
 1473        let mode = match self.mode {
 1474            EditorMode::SingleLine { .. } => "single_line",
 1475            EditorMode::AutoHeight { .. } => "auto_height",
 1476            EditorMode::Full => "full",
 1477        };
 1478
 1479        if EditorSettings::jupyter_enabled(cx) {
 1480            key_context.add("jupyter");
 1481        }
 1482
 1483        key_context.set("mode", mode);
 1484        if self.pending_rename.is_some() {
 1485            key_context.add("renaming");
 1486        }
 1487        match self.context_menu.borrow().as_ref() {
 1488            Some(CodeContextMenu::Completions(_)) => {
 1489                key_context.add("menu");
 1490                key_context.add("showing_completions");
 1491            }
 1492            Some(CodeContextMenu::CodeActions(_)) => {
 1493                key_context.add("menu");
 1494                key_context.add("showing_code_actions")
 1495            }
 1496            None => {}
 1497        }
 1498
 1499        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1500        if !self.focus_handle(cx).contains_focused(window, cx)
 1501            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1502        {
 1503            for addon in self.addons.values() {
 1504                addon.extend_key_context(&mut key_context, cx)
 1505            }
 1506        }
 1507
 1508        if let Some(extension) = self
 1509            .buffer
 1510            .read(cx)
 1511            .as_singleton()
 1512            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1513        {
 1514            key_context.set("extension", extension.to_string());
 1515        }
 1516
 1517        if self.has_active_inline_completion() {
 1518            key_context.add("copilot_suggestion");
 1519            key_context.add("inline_completion");
 1520        }
 1521
 1522        if self.selection_mark_mode {
 1523            key_context.add("selection_mode");
 1524        }
 1525
 1526        key_context
 1527    }
 1528
 1529    pub fn new_file(
 1530        workspace: &mut Workspace,
 1531        _: &workspace::NewFile,
 1532        window: &mut Window,
 1533        cx: &mut Context<Workspace>,
 1534    ) {
 1535        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1536            "Failed to create buffer",
 1537            window,
 1538            cx,
 1539            |e, _, _| match e.error_code() {
 1540                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1541                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1542                e.error_tag("required").unwrap_or("the latest version")
 1543            )),
 1544                _ => None,
 1545            },
 1546        );
 1547    }
 1548
 1549    pub fn new_in_workspace(
 1550        workspace: &mut Workspace,
 1551        window: &mut Window,
 1552        cx: &mut Context<Workspace>,
 1553    ) -> Task<Result<Entity<Editor>>> {
 1554        let project = workspace.project().clone();
 1555        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1556
 1557        cx.spawn_in(window, |workspace, mut cx| async move {
 1558            let buffer = create.await?;
 1559            workspace.update_in(&mut cx, |workspace, window, cx| {
 1560                let editor =
 1561                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1562                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1563                editor
 1564            })
 1565        })
 1566    }
 1567
 1568    fn new_file_vertical(
 1569        workspace: &mut Workspace,
 1570        _: &workspace::NewFileSplitVertical,
 1571        window: &mut Window,
 1572        cx: &mut Context<Workspace>,
 1573    ) {
 1574        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1575    }
 1576
 1577    fn new_file_horizontal(
 1578        workspace: &mut Workspace,
 1579        _: &workspace::NewFileSplitHorizontal,
 1580        window: &mut Window,
 1581        cx: &mut Context<Workspace>,
 1582    ) {
 1583        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1584    }
 1585
 1586    fn new_file_in_direction(
 1587        workspace: &mut Workspace,
 1588        direction: SplitDirection,
 1589        window: &mut Window,
 1590        cx: &mut Context<Workspace>,
 1591    ) {
 1592        let project = workspace.project().clone();
 1593        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1594
 1595        cx.spawn_in(window, |workspace, mut cx| async move {
 1596            let buffer = create.await?;
 1597            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1598                workspace.split_item(
 1599                    direction,
 1600                    Box::new(
 1601                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1602                    ),
 1603                    window,
 1604                    cx,
 1605                )
 1606            })?;
 1607            anyhow::Ok(())
 1608        })
 1609        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1610            match e.error_code() {
 1611                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1612                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1613                e.error_tag("required").unwrap_or("the latest version")
 1614            )),
 1615                _ => None,
 1616            }
 1617        });
 1618    }
 1619
 1620    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1621        self.leader_peer_id
 1622    }
 1623
 1624    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1625        &self.buffer
 1626    }
 1627
 1628    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1629        self.workspace.as_ref()?.0.upgrade()
 1630    }
 1631
 1632    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1633        self.buffer().read(cx).title(cx)
 1634    }
 1635
 1636    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1637        let git_blame_gutter_max_author_length = self
 1638            .render_git_blame_gutter(cx)
 1639            .then(|| {
 1640                if let Some(blame) = self.blame.as_ref() {
 1641                    let max_author_length =
 1642                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1643                    Some(max_author_length)
 1644                } else {
 1645                    None
 1646                }
 1647            })
 1648            .flatten();
 1649
 1650        EditorSnapshot {
 1651            mode: self.mode,
 1652            show_gutter: self.show_gutter,
 1653            show_line_numbers: self.show_line_numbers,
 1654            show_git_diff_gutter: self.show_git_diff_gutter,
 1655            show_code_actions: self.show_code_actions,
 1656            show_runnables: self.show_runnables,
 1657            git_blame_gutter_max_author_length,
 1658            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1659            scroll_anchor: self.scroll_manager.anchor(),
 1660            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1661            placeholder_text: self.placeholder_text.clone(),
 1662            is_focused: self.focus_handle.is_focused(window),
 1663            current_line_highlight: self
 1664                .current_line_highlight
 1665                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1666            gutter_hovered: self.gutter_hovered,
 1667        }
 1668    }
 1669
 1670    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1671        self.buffer.read(cx).language_at(point, cx)
 1672    }
 1673
 1674    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1675        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1676    }
 1677
 1678    pub fn active_excerpt(
 1679        &self,
 1680        cx: &App,
 1681    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1682        self.buffer
 1683            .read(cx)
 1684            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1685    }
 1686
 1687    pub fn mode(&self) -> EditorMode {
 1688        self.mode
 1689    }
 1690
 1691    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1692        self.collaboration_hub.as_deref()
 1693    }
 1694
 1695    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1696        self.collaboration_hub = Some(hub);
 1697    }
 1698
 1699    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1700        self.in_project_search = in_project_search;
 1701    }
 1702
 1703    pub fn set_custom_context_menu(
 1704        &mut self,
 1705        f: impl 'static
 1706            + Fn(
 1707                &mut Self,
 1708                DisplayPoint,
 1709                &mut Window,
 1710                &mut Context<Self>,
 1711            ) -> Option<Entity<ui::ContextMenu>>,
 1712    ) {
 1713        self.custom_context_menu = Some(Box::new(f))
 1714    }
 1715
 1716    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1717        self.completion_provider = provider;
 1718    }
 1719
 1720    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1721        self.semantics_provider.clone()
 1722    }
 1723
 1724    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1725        self.semantics_provider = provider;
 1726    }
 1727
 1728    pub fn set_inline_completion_provider<T>(
 1729        &mut self,
 1730        provider: Option<Entity<T>>,
 1731        window: &mut Window,
 1732        cx: &mut Context<Self>,
 1733    ) where
 1734        T: InlineCompletionProvider,
 1735    {
 1736        self.inline_completion_provider =
 1737            provider.map(|provider| RegisteredInlineCompletionProvider {
 1738                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1739                    if this.focus_handle.is_focused(window) {
 1740                        this.update_visible_inline_completion(window, cx);
 1741                    }
 1742                }),
 1743                provider: Arc::new(provider),
 1744            });
 1745        self.refresh_inline_completion(false, false, window, cx);
 1746    }
 1747
 1748    pub fn placeholder_text(&self) -> Option<&str> {
 1749        self.placeholder_text.as_deref()
 1750    }
 1751
 1752    pub fn set_placeholder_text(
 1753        &mut self,
 1754        placeholder_text: impl Into<Arc<str>>,
 1755        cx: &mut Context<Self>,
 1756    ) {
 1757        let placeholder_text = Some(placeholder_text.into());
 1758        if self.placeholder_text != placeholder_text {
 1759            self.placeholder_text = placeholder_text;
 1760            cx.notify();
 1761        }
 1762    }
 1763
 1764    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1765        self.cursor_shape = cursor_shape;
 1766
 1767        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1768        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1769
 1770        cx.notify();
 1771    }
 1772
 1773    pub fn set_current_line_highlight(
 1774        &mut self,
 1775        current_line_highlight: Option<CurrentLineHighlight>,
 1776    ) {
 1777        self.current_line_highlight = current_line_highlight;
 1778    }
 1779
 1780    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1781        self.collapse_matches = collapse_matches;
 1782    }
 1783
 1784    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1785        let buffers = self.buffer.read(cx).all_buffers();
 1786        let Some(lsp_store) = self.lsp_store(cx) else {
 1787            return;
 1788        };
 1789        lsp_store.update(cx, |lsp_store, cx| {
 1790            for buffer in buffers {
 1791                self.registered_buffers
 1792                    .entry(buffer.read(cx).remote_id())
 1793                    .or_insert_with(|| {
 1794                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1795                    });
 1796            }
 1797        })
 1798    }
 1799
 1800    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1801        if self.collapse_matches {
 1802            return range.start..range.start;
 1803        }
 1804        range.clone()
 1805    }
 1806
 1807    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1808        if self.display_map.read(cx).clip_at_line_ends != clip {
 1809            self.display_map
 1810                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1811        }
 1812    }
 1813
 1814    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1815        self.input_enabled = input_enabled;
 1816    }
 1817
 1818    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1819        self.enable_inline_completions = enabled;
 1820        if !self.enable_inline_completions {
 1821            self.take_active_inline_completion(cx);
 1822            cx.notify();
 1823        }
 1824    }
 1825
 1826    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1827        self.menu_inline_completions_policy = value;
 1828    }
 1829
 1830    pub fn set_autoindent(&mut self, autoindent: bool) {
 1831        if autoindent {
 1832            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1833        } else {
 1834            self.autoindent_mode = None;
 1835        }
 1836    }
 1837
 1838    pub fn read_only(&self, cx: &App) -> bool {
 1839        self.read_only || self.buffer.read(cx).read_only()
 1840    }
 1841
 1842    pub fn set_read_only(&mut self, read_only: bool) {
 1843        self.read_only = read_only;
 1844    }
 1845
 1846    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1847        self.use_autoclose = autoclose;
 1848    }
 1849
 1850    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1851        self.use_auto_surround = auto_surround;
 1852    }
 1853
 1854    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1855        self.auto_replace_emoji_shortcode = auto_replace;
 1856    }
 1857
 1858    pub fn toggle_inline_completions(
 1859        &mut self,
 1860        _: &ToggleInlineCompletions,
 1861        window: &mut Window,
 1862        cx: &mut Context<Self>,
 1863    ) {
 1864        if self.show_inline_completions_override.is_some() {
 1865            self.set_show_inline_completions(None, window, cx);
 1866        } else {
 1867            let cursor = self.selections.newest_anchor().head();
 1868            if let Some((buffer, cursor_buffer_position)) =
 1869                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1870            {
 1871                let show_inline_completions =
 1872                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1873                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1874            }
 1875        }
 1876    }
 1877
 1878    pub fn set_show_inline_completions(
 1879        &mut self,
 1880        show_inline_completions: Option<bool>,
 1881        window: &mut Window,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        self.show_inline_completions_override = show_inline_completions;
 1885        self.refresh_inline_completion(false, true, window, cx);
 1886    }
 1887
 1888    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1889        let cursor = self.selections.newest_anchor().head();
 1890        if let Some((buffer, buffer_position)) =
 1891            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1892        {
 1893            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1894        } else {
 1895            false
 1896        }
 1897    }
 1898
 1899    fn should_show_inline_completions(
 1900        &self,
 1901        buffer: &Entity<Buffer>,
 1902        buffer_position: language::Anchor,
 1903        cx: &App,
 1904    ) -> bool {
 1905        if !self.snippet_stack.is_empty() {
 1906            return false;
 1907        }
 1908
 1909        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1910            return false;
 1911        }
 1912
 1913        if let Some(provider) = self.inline_completion_provider() {
 1914            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1915                show_inline_completions
 1916            } else {
 1917                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1918            }
 1919        } else {
 1920            false
 1921        }
 1922    }
 1923
 1924    fn inline_completions_disabled_in_scope(
 1925        &self,
 1926        buffer: &Entity<Buffer>,
 1927        buffer_position: language::Anchor,
 1928        cx: &App,
 1929    ) -> bool {
 1930        let snapshot = buffer.read(cx).snapshot();
 1931        let settings = snapshot.settings_at(buffer_position, cx);
 1932
 1933        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1934            return false;
 1935        };
 1936
 1937        scope.override_name().map_or(false, |scope_name| {
 1938            settings
 1939                .inline_completions_disabled_in
 1940                .iter()
 1941                .any(|s| s == scope_name)
 1942        })
 1943    }
 1944
 1945    pub fn set_use_modal_editing(&mut self, to: bool) {
 1946        self.use_modal_editing = to;
 1947    }
 1948
 1949    pub fn use_modal_editing(&self) -> bool {
 1950        self.use_modal_editing
 1951    }
 1952
 1953    fn selections_did_change(
 1954        &mut self,
 1955        local: bool,
 1956        old_cursor_position: &Anchor,
 1957        show_completions: bool,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        window.invalidate_character_coordinates();
 1962
 1963        // Copy selections to primary selection buffer
 1964        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1965        if local {
 1966            let selections = self.selections.all::<usize>(cx);
 1967            let buffer_handle = self.buffer.read(cx).read(cx);
 1968
 1969            let mut text = String::new();
 1970            for (index, selection) in selections.iter().enumerate() {
 1971                let text_for_selection = buffer_handle
 1972                    .text_for_range(selection.start..selection.end)
 1973                    .collect::<String>();
 1974
 1975                text.push_str(&text_for_selection);
 1976                if index != selections.len() - 1 {
 1977                    text.push('\n');
 1978                }
 1979            }
 1980
 1981            if !text.is_empty() {
 1982                cx.write_to_primary(ClipboardItem::new_string(text));
 1983            }
 1984        }
 1985
 1986        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1987            self.buffer.update(cx, |buffer, cx| {
 1988                buffer.set_active_selections(
 1989                    &self.selections.disjoint_anchors(),
 1990                    self.selections.line_mode,
 1991                    self.cursor_shape,
 1992                    cx,
 1993                )
 1994            });
 1995        }
 1996        let display_map = self
 1997            .display_map
 1998            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1999        let buffer = &display_map.buffer_snapshot;
 2000        self.add_selections_state = None;
 2001        self.select_next_state = None;
 2002        self.select_prev_state = None;
 2003        self.select_larger_syntax_node_stack.clear();
 2004        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2005        self.snippet_stack
 2006            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2007        self.take_rename(false, window, cx);
 2008
 2009        let new_cursor_position = self.selections.newest_anchor().head();
 2010
 2011        self.push_to_nav_history(
 2012            *old_cursor_position,
 2013            Some(new_cursor_position.to_point(buffer)),
 2014            cx,
 2015        );
 2016
 2017        if local {
 2018            let new_cursor_position = self.selections.newest_anchor().head();
 2019            let mut context_menu = self.context_menu.borrow_mut();
 2020            let completion_menu = match context_menu.as_ref() {
 2021                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2022                _ => {
 2023                    *context_menu = None;
 2024                    None
 2025                }
 2026            };
 2027
 2028            if let Some(completion_menu) = completion_menu {
 2029                let cursor_position = new_cursor_position.to_offset(buffer);
 2030                let (word_range, kind) =
 2031                    buffer.surrounding_word(completion_menu.initial_position, true);
 2032                if kind == Some(CharKind::Word)
 2033                    && word_range.to_inclusive().contains(&cursor_position)
 2034                {
 2035                    let mut completion_menu = completion_menu.clone();
 2036                    drop(context_menu);
 2037
 2038                    let query = Self::completion_query(buffer, cursor_position);
 2039                    cx.spawn(move |this, mut cx| async move {
 2040                        completion_menu
 2041                            .filter(query.as_deref(), cx.background_executor().clone())
 2042                            .await;
 2043
 2044                        this.update(&mut cx, |this, cx| {
 2045                            let mut context_menu = this.context_menu.borrow_mut();
 2046                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2047                            else {
 2048                                return;
 2049                            };
 2050
 2051                            if menu.id > completion_menu.id {
 2052                                return;
 2053                            }
 2054
 2055                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2056                            drop(context_menu);
 2057                            cx.notify();
 2058                        })
 2059                    })
 2060                    .detach();
 2061
 2062                    if show_completions {
 2063                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2064                    }
 2065                } else {
 2066                    drop(context_menu);
 2067                    self.hide_context_menu(window, cx);
 2068                }
 2069            } else {
 2070                drop(context_menu);
 2071            }
 2072
 2073            hide_hover(self, cx);
 2074
 2075            if old_cursor_position.to_display_point(&display_map).row()
 2076                != new_cursor_position.to_display_point(&display_map).row()
 2077            {
 2078                self.available_code_actions.take();
 2079            }
 2080            self.refresh_code_actions(window, cx);
 2081            self.refresh_document_highlights(cx);
 2082            refresh_matching_bracket_highlights(self, window, cx);
 2083            self.update_visible_inline_completion(window, cx);
 2084            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2085            if self.git_blame_inline_enabled {
 2086                self.start_inline_blame_timer(window, cx);
 2087            }
 2088        }
 2089
 2090        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2091        cx.emit(EditorEvent::SelectionsChanged { local });
 2092
 2093        if self.selections.disjoint_anchors().len() == 1 {
 2094            cx.emit(SearchEvent::ActiveMatchChanged)
 2095        }
 2096        cx.notify();
 2097    }
 2098
 2099    pub fn change_selections<R>(
 2100        &mut self,
 2101        autoscroll: Option<Autoscroll>,
 2102        window: &mut Window,
 2103        cx: &mut Context<Self>,
 2104        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2105    ) -> R {
 2106        self.change_selections_inner(autoscroll, true, window, cx, change)
 2107    }
 2108
 2109    pub fn change_selections_inner<R>(
 2110        &mut self,
 2111        autoscroll: Option<Autoscroll>,
 2112        request_completions: bool,
 2113        window: &mut Window,
 2114        cx: &mut Context<Self>,
 2115        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2116    ) -> R {
 2117        let old_cursor_position = self.selections.newest_anchor().head();
 2118        self.push_to_selection_history();
 2119
 2120        let (changed, result) = self.selections.change_with(cx, change);
 2121
 2122        if changed {
 2123            if let Some(autoscroll) = autoscroll {
 2124                self.request_autoscroll(autoscroll, cx);
 2125            }
 2126            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2127
 2128            if self.should_open_signature_help_automatically(
 2129                &old_cursor_position,
 2130                self.signature_help_state.backspace_pressed(),
 2131                cx,
 2132            ) {
 2133                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2134            }
 2135            self.signature_help_state.set_backspace_pressed(false);
 2136        }
 2137
 2138        result
 2139    }
 2140
 2141    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2142    where
 2143        I: IntoIterator<Item = (Range<S>, T)>,
 2144        S: ToOffset,
 2145        T: Into<Arc<str>>,
 2146    {
 2147        if self.read_only(cx) {
 2148            return;
 2149        }
 2150
 2151        self.buffer
 2152            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2153    }
 2154
 2155    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2156    where
 2157        I: IntoIterator<Item = (Range<S>, T)>,
 2158        S: ToOffset,
 2159        T: Into<Arc<str>>,
 2160    {
 2161        if self.read_only(cx) {
 2162            return;
 2163        }
 2164
 2165        self.buffer.update(cx, |buffer, cx| {
 2166            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2167        });
 2168    }
 2169
 2170    pub fn edit_with_block_indent<I, S, T>(
 2171        &mut self,
 2172        edits: I,
 2173        original_indent_columns: Vec<u32>,
 2174        cx: &mut Context<Self>,
 2175    ) where
 2176        I: IntoIterator<Item = (Range<S>, T)>,
 2177        S: ToOffset,
 2178        T: Into<Arc<str>>,
 2179    {
 2180        if self.read_only(cx) {
 2181            return;
 2182        }
 2183
 2184        self.buffer.update(cx, |buffer, cx| {
 2185            buffer.edit(
 2186                edits,
 2187                Some(AutoindentMode::Block {
 2188                    original_indent_columns,
 2189                }),
 2190                cx,
 2191            )
 2192        });
 2193    }
 2194
 2195    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2196        self.hide_context_menu(window, cx);
 2197
 2198        match phase {
 2199            SelectPhase::Begin {
 2200                position,
 2201                add,
 2202                click_count,
 2203            } => self.begin_selection(position, add, click_count, window, cx),
 2204            SelectPhase::BeginColumnar {
 2205                position,
 2206                goal_column,
 2207                reset,
 2208            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2209            SelectPhase::Extend {
 2210                position,
 2211                click_count,
 2212            } => self.extend_selection(position, click_count, window, cx),
 2213            SelectPhase::Update {
 2214                position,
 2215                goal_column,
 2216                scroll_delta,
 2217            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2218            SelectPhase::End => self.end_selection(window, cx),
 2219        }
 2220    }
 2221
 2222    fn extend_selection(
 2223        &mut self,
 2224        position: DisplayPoint,
 2225        click_count: usize,
 2226        window: &mut Window,
 2227        cx: &mut Context<Self>,
 2228    ) {
 2229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2230        let tail = self.selections.newest::<usize>(cx).tail();
 2231        self.begin_selection(position, false, click_count, window, cx);
 2232
 2233        let position = position.to_offset(&display_map, Bias::Left);
 2234        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2235
 2236        let mut pending_selection = self
 2237            .selections
 2238            .pending_anchor()
 2239            .expect("extend_selection not called with pending selection");
 2240        if position >= tail {
 2241            pending_selection.start = tail_anchor;
 2242        } else {
 2243            pending_selection.end = tail_anchor;
 2244            pending_selection.reversed = true;
 2245        }
 2246
 2247        let mut pending_mode = self.selections.pending_mode().unwrap();
 2248        match &mut pending_mode {
 2249            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2250            _ => {}
 2251        }
 2252
 2253        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2254            s.set_pending(pending_selection, pending_mode)
 2255        });
 2256    }
 2257
 2258    fn begin_selection(
 2259        &mut self,
 2260        position: DisplayPoint,
 2261        add: bool,
 2262        click_count: usize,
 2263        window: &mut Window,
 2264        cx: &mut Context<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(window) {
 2267            self.last_focused_descendant = None;
 2268            window.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272        let buffer = &display_map.buffer_snapshot;
 2273        let newest_selection = self.selections.newest_anchor().clone();
 2274        let position = display_map.clip_point(position, Bias::Left);
 2275
 2276        let start;
 2277        let end;
 2278        let mode;
 2279        let mut auto_scroll;
 2280        match click_count {
 2281            1 => {
 2282                start = buffer.anchor_before(position.to_point(&display_map));
 2283                end = start;
 2284                mode = SelectMode::Character;
 2285                auto_scroll = true;
 2286            }
 2287            2 => {
 2288                let range = movement::surrounding_word(&display_map, position);
 2289                start = buffer.anchor_before(range.start.to_point(&display_map));
 2290                end = buffer.anchor_before(range.end.to_point(&display_map));
 2291                mode = SelectMode::Word(start..end);
 2292                auto_scroll = true;
 2293            }
 2294            3 => {
 2295                let position = display_map
 2296                    .clip_point(position, Bias::Left)
 2297                    .to_point(&display_map);
 2298                let line_start = display_map.prev_line_boundary(position).0;
 2299                let next_line_start = buffer.clip_point(
 2300                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2301                    Bias::Left,
 2302                );
 2303                start = buffer.anchor_before(line_start);
 2304                end = buffer.anchor_before(next_line_start);
 2305                mode = SelectMode::Line(start..end);
 2306                auto_scroll = true;
 2307            }
 2308            _ => {
 2309                start = buffer.anchor_before(0);
 2310                end = buffer.anchor_before(buffer.len());
 2311                mode = SelectMode::All;
 2312                auto_scroll = false;
 2313            }
 2314        }
 2315        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2316
 2317        let point_to_delete: Option<usize> = {
 2318            let selected_points: Vec<Selection<Point>> =
 2319                self.selections.disjoint_in_range(start..end, cx);
 2320
 2321            if !add || click_count > 1 {
 2322                None
 2323            } else if !selected_points.is_empty() {
 2324                Some(selected_points[0].id)
 2325            } else {
 2326                let clicked_point_already_selected =
 2327                    self.selections.disjoint.iter().find(|selection| {
 2328                        selection.start.to_point(buffer) == start.to_point(buffer)
 2329                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2330                    });
 2331
 2332                clicked_point_already_selected.map(|selection| selection.id)
 2333            }
 2334        };
 2335
 2336        let selections_count = self.selections.count();
 2337
 2338        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2339            if let Some(point_to_delete) = point_to_delete {
 2340                s.delete(point_to_delete);
 2341
 2342                if selections_count == 1 {
 2343                    s.set_pending_anchor_range(start..end, mode);
 2344                }
 2345            } else {
 2346                if !add {
 2347                    s.clear_disjoint();
 2348                } else if click_count > 1 {
 2349                    s.delete(newest_selection.id)
 2350                }
 2351
 2352                s.set_pending_anchor_range(start..end, mode);
 2353            }
 2354        });
 2355    }
 2356
 2357    fn begin_columnar_selection(
 2358        &mut self,
 2359        position: DisplayPoint,
 2360        goal_column: u32,
 2361        reset: bool,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        if !self.focus_handle.is_focused(window) {
 2366            self.last_focused_descendant = None;
 2367            window.focus(&self.focus_handle);
 2368        }
 2369
 2370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2371
 2372        if reset {
 2373            let pointer_position = display_map
 2374                .buffer_snapshot
 2375                .anchor_before(position.to_point(&display_map));
 2376
 2377            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2378                s.clear_disjoint();
 2379                s.set_pending_anchor_range(
 2380                    pointer_position..pointer_position,
 2381                    SelectMode::Character,
 2382                );
 2383            });
 2384        }
 2385
 2386        let tail = self.selections.newest::<Point>(cx).tail();
 2387        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2388
 2389        if !reset {
 2390            self.select_columns(
 2391                tail.to_display_point(&display_map),
 2392                position,
 2393                goal_column,
 2394                &display_map,
 2395                window,
 2396                cx,
 2397            );
 2398        }
 2399    }
 2400
 2401    fn update_selection(
 2402        &mut self,
 2403        position: DisplayPoint,
 2404        goal_column: u32,
 2405        scroll_delta: gpui::Point<f32>,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408    ) {
 2409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2410
 2411        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2412            let tail = tail.to_display_point(&display_map);
 2413            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2414        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2415            let buffer = self.buffer.read(cx).snapshot(cx);
 2416            let head;
 2417            let tail;
 2418            let mode = self.selections.pending_mode().unwrap();
 2419            match &mode {
 2420                SelectMode::Character => {
 2421                    head = position.to_point(&display_map);
 2422                    tail = pending.tail().to_point(&buffer);
 2423                }
 2424                SelectMode::Word(original_range) => {
 2425                    let original_display_range = original_range.start.to_display_point(&display_map)
 2426                        ..original_range.end.to_display_point(&display_map);
 2427                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2428                        ..original_display_range.end.to_point(&display_map);
 2429                    if movement::is_inside_word(&display_map, position)
 2430                        || original_display_range.contains(&position)
 2431                    {
 2432                        let word_range = movement::surrounding_word(&display_map, position);
 2433                        if word_range.start < original_display_range.start {
 2434                            head = word_range.start.to_point(&display_map);
 2435                        } else {
 2436                            head = word_range.end.to_point(&display_map);
 2437                        }
 2438                    } else {
 2439                        head = position.to_point(&display_map);
 2440                    }
 2441
 2442                    if head <= original_buffer_range.start {
 2443                        tail = original_buffer_range.end;
 2444                    } else {
 2445                        tail = original_buffer_range.start;
 2446                    }
 2447                }
 2448                SelectMode::Line(original_range) => {
 2449                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2450
 2451                    let position = display_map
 2452                        .clip_point(position, Bias::Left)
 2453                        .to_point(&display_map);
 2454                    let line_start = display_map.prev_line_boundary(position).0;
 2455                    let next_line_start = buffer.clip_point(
 2456                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2457                        Bias::Left,
 2458                    );
 2459
 2460                    if line_start < original_range.start {
 2461                        head = line_start
 2462                    } else {
 2463                        head = next_line_start
 2464                    }
 2465
 2466                    if head <= original_range.start {
 2467                        tail = original_range.end;
 2468                    } else {
 2469                        tail = original_range.start;
 2470                    }
 2471                }
 2472                SelectMode::All => {
 2473                    return;
 2474                }
 2475            };
 2476
 2477            if head < tail {
 2478                pending.start = buffer.anchor_before(head);
 2479                pending.end = buffer.anchor_before(tail);
 2480                pending.reversed = true;
 2481            } else {
 2482                pending.start = buffer.anchor_before(tail);
 2483                pending.end = buffer.anchor_before(head);
 2484                pending.reversed = false;
 2485            }
 2486
 2487            self.change_selections(None, window, cx, |s| {
 2488                s.set_pending(pending, mode);
 2489            });
 2490        } else {
 2491            log::error!("update_selection dispatched with no pending selection");
 2492            return;
 2493        }
 2494
 2495        self.apply_scroll_delta(scroll_delta, window, cx);
 2496        cx.notify();
 2497    }
 2498
 2499    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2500        self.columnar_selection_tail.take();
 2501        if self.selections.pending_anchor().is_some() {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            self.change_selections(None, window, cx, |s| {
 2504                s.select(selections);
 2505                s.clear_pending();
 2506            });
 2507        }
 2508    }
 2509
 2510    fn select_columns(
 2511        &mut self,
 2512        tail: DisplayPoint,
 2513        head: DisplayPoint,
 2514        goal_column: u32,
 2515        display_map: &DisplaySnapshot,
 2516        window: &mut Window,
 2517        cx: &mut Context<Self>,
 2518    ) {
 2519        let start_row = cmp::min(tail.row(), head.row());
 2520        let end_row = cmp::max(tail.row(), head.row());
 2521        let start_column = cmp::min(tail.column(), goal_column);
 2522        let end_column = cmp::max(tail.column(), goal_column);
 2523        let reversed = start_column < tail.column();
 2524
 2525        let selection_ranges = (start_row.0..=end_row.0)
 2526            .map(DisplayRow)
 2527            .filter_map(|row| {
 2528                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2529                    let start = display_map
 2530                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2531                        .to_point(display_map);
 2532                    let end = display_map
 2533                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2534                        .to_point(display_map);
 2535                    if reversed {
 2536                        Some(end..start)
 2537                    } else {
 2538                        Some(start..end)
 2539                    }
 2540                } else {
 2541                    None
 2542                }
 2543            })
 2544            .collect::<Vec<_>>();
 2545
 2546        self.change_selections(None, window, cx, |s| {
 2547            s.select_ranges(selection_ranges);
 2548        });
 2549        cx.notify();
 2550    }
 2551
 2552    pub fn has_pending_nonempty_selection(&self) -> bool {
 2553        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2554            Some(Selection { start, end, .. }) => start != end,
 2555            None => false,
 2556        };
 2557
 2558        pending_nonempty_selection
 2559            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2560    }
 2561
 2562    pub fn has_pending_selection(&self) -> bool {
 2563        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2564    }
 2565
 2566    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2567        self.selection_mark_mode = false;
 2568
 2569        if self.clear_expanded_diff_hunks(cx) {
 2570            cx.notify();
 2571            return;
 2572        }
 2573        if self.dismiss_menus_and_popups(true, window, cx) {
 2574            return;
 2575        }
 2576
 2577        if self.mode == EditorMode::Full
 2578            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2579        {
 2580            return;
 2581        }
 2582
 2583        cx.propagate();
 2584    }
 2585
 2586    pub fn dismiss_menus_and_popups(
 2587        &mut self,
 2588        should_report_inline_completion_event: bool,
 2589        window: &mut Window,
 2590        cx: &mut Context<Self>,
 2591    ) -> bool {
 2592        if self.take_rename(false, window, cx).is_some() {
 2593            return true;
 2594        }
 2595
 2596        if hide_hover(self, cx) {
 2597            return true;
 2598        }
 2599
 2600        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2601            return true;
 2602        }
 2603
 2604        if self.hide_context_menu(window, cx).is_some() {
 2605            return true;
 2606        }
 2607
 2608        if self.mouse_context_menu.take().is_some() {
 2609            return true;
 2610        }
 2611
 2612        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2613            return true;
 2614        }
 2615
 2616        if self.snippet_stack.pop().is_some() {
 2617            return true;
 2618        }
 2619
 2620        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2621            self.dismiss_diagnostics(cx);
 2622            return true;
 2623        }
 2624
 2625        false
 2626    }
 2627
 2628    fn linked_editing_ranges_for(
 2629        &self,
 2630        selection: Range<text::Anchor>,
 2631        cx: &App,
 2632    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2633        if self.linked_edit_ranges.is_empty() {
 2634            return None;
 2635        }
 2636        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2637            selection.end.buffer_id.and_then(|end_buffer_id| {
 2638                if selection.start.buffer_id != Some(end_buffer_id) {
 2639                    return None;
 2640                }
 2641                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2642                let snapshot = buffer.read(cx).snapshot();
 2643                self.linked_edit_ranges
 2644                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2645                    .map(|ranges| (ranges, snapshot, buffer))
 2646            })?;
 2647        use text::ToOffset as TO;
 2648        // find offset from the start of current range to current cursor position
 2649        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2650
 2651        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2652        let start_difference = start_offset - start_byte_offset;
 2653        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2654        let end_difference = end_offset - start_byte_offset;
 2655        // Current range has associated linked ranges.
 2656        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2657        for range in linked_ranges.iter() {
 2658            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2659            let end_offset = start_offset + end_difference;
 2660            let start_offset = start_offset + start_difference;
 2661            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2662                continue;
 2663            }
 2664            if self.selections.disjoint_anchor_ranges().any(|s| {
 2665                if s.start.buffer_id != selection.start.buffer_id
 2666                    || s.end.buffer_id != selection.end.buffer_id
 2667                {
 2668                    return false;
 2669                }
 2670                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2671                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2672            }) {
 2673                continue;
 2674            }
 2675            let start = buffer_snapshot.anchor_after(start_offset);
 2676            let end = buffer_snapshot.anchor_after(end_offset);
 2677            linked_edits
 2678                .entry(buffer.clone())
 2679                .or_default()
 2680                .push(start..end);
 2681        }
 2682        Some(linked_edits)
 2683    }
 2684
 2685    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2686        let text: Arc<str> = text.into();
 2687
 2688        if self.read_only(cx) {
 2689            return;
 2690        }
 2691
 2692        let selections = self.selections.all_adjusted(cx);
 2693        let mut bracket_inserted = false;
 2694        let mut edits = Vec::new();
 2695        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2696        let mut new_selections = Vec::with_capacity(selections.len());
 2697        let mut new_autoclose_regions = Vec::new();
 2698        let snapshot = self.buffer.read(cx).read(cx);
 2699
 2700        for (selection, autoclose_region) in
 2701            self.selections_with_autoclose_regions(selections, &snapshot)
 2702        {
 2703            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2704                // Determine if the inserted text matches the opening or closing
 2705                // bracket of any of this language's bracket pairs.
 2706                let mut bracket_pair = None;
 2707                let mut is_bracket_pair_start = false;
 2708                let mut is_bracket_pair_end = false;
 2709                if !text.is_empty() {
 2710                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2711                    //  and they are removing the character that triggered IME popup.
 2712                    for (pair, enabled) in scope.brackets() {
 2713                        if !pair.close && !pair.surround {
 2714                            continue;
 2715                        }
 2716
 2717                        if enabled && pair.start.ends_with(text.as_ref()) {
 2718                            let prefix_len = pair.start.len() - text.len();
 2719                            let preceding_text_matches_prefix = prefix_len == 0
 2720                                || (selection.start.column >= (prefix_len as u32)
 2721                                    && snapshot.contains_str_at(
 2722                                        Point::new(
 2723                                            selection.start.row,
 2724                                            selection.start.column - (prefix_len as u32),
 2725                                        ),
 2726                                        &pair.start[..prefix_len],
 2727                                    ));
 2728                            if preceding_text_matches_prefix {
 2729                                bracket_pair = Some(pair.clone());
 2730                                is_bracket_pair_start = true;
 2731                                break;
 2732                            }
 2733                        }
 2734                        if pair.end.as_str() == text.as_ref() {
 2735                            bracket_pair = Some(pair.clone());
 2736                            is_bracket_pair_end = true;
 2737                            break;
 2738                        }
 2739                    }
 2740                }
 2741
 2742                if let Some(bracket_pair) = bracket_pair {
 2743                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2744                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2745                    let auto_surround =
 2746                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2747                    if selection.is_empty() {
 2748                        if is_bracket_pair_start {
 2749                            // If the inserted text is a suffix of an opening bracket and the
 2750                            // selection is preceded by the rest of the opening bracket, then
 2751                            // insert the closing bracket.
 2752                            let following_text_allows_autoclose = snapshot
 2753                                .chars_at(selection.start)
 2754                                .next()
 2755                                .map_or(true, |c| scope.should_autoclose_before(c));
 2756
 2757                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2758                                && bracket_pair.start.len() == 1
 2759                            {
 2760                                let target = bracket_pair.start.chars().next().unwrap();
 2761                                let current_line_count = snapshot
 2762                                    .reversed_chars_at(selection.start)
 2763                                    .take_while(|&c| c != '\n')
 2764                                    .filter(|&c| c == target)
 2765                                    .count();
 2766                                current_line_count % 2 == 1
 2767                            } else {
 2768                                false
 2769                            };
 2770
 2771                            if autoclose
 2772                                && bracket_pair.close
 2773                                && following_text_allows_autoclose
 2774                                && !is_closing_quote
 2775                            {
 2776                                let anchor = snapshot.anchor_before(selection.end);
 2777                                new_selections.push((selection.map(|_| anchor), text.len()));
 2778                                new_autoclose_regions.push((
 2779                                    anchor,
 2780                                    text.len(),
 2781                                    selection.id,
 2782                                    bracket_pair.clone(),
 2783                                ));
 2784                                edits.push((
 2785                                    selection.range(),
 2786                                    format!("{}{}", text, bracket_pair.end).into(),
 2787                                ));
 2788                                bracket_inserted = true;
 2789                                continue;
 2790                            }
 2791                        }
 2792
 2793                        if let Some(region) = autoclose_region {
 2794                            // If the selection is followed by an auto-inserted closing bracket,
 2795                            // then don't insert that closing bracket again; just move the selection
 2796                            // past the closing bracket.
 2797                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2798                                && text.as_ref() == region.pair.end.as_str();
 2799                            if should_skip {
 2800                                let anchor = snapshot.anchor_after(selection.end);
 2801                                new_selections
 2802                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2803                                continue;
 2804                            }
 2805                        }
 2806
 2807                        let always_treat_brackets_as_autoclosed = snapshot
 2808                            .settings_at(selection.start, cx)
 2809                            .always_treat_brackets_as_autoclosed;
 2810                        if always_treat_brackets_as_autoclosed
 2811                            && is_bracket_pair_end
 2812                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2813                        {
 2814                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2815                            // and the inserted text is a closing bracket and the selection is followed
 2816                            // by the closing bracket then move the selection past the closing bracket.
 2817                            let anchor = snapshot.anchor_after(selection.end);
 2818                            new_selections.push((selection.map(|_| anchor), text.len()));
 2819                            continue;
 2820                        }
 2821                    }
 2822                    // If an opening bracket is 1 character long and is typed while
 2823                    // text is selected, then surround that text with the bracket pair.
 2824                    else if auto_surround
 2825                        && bracket_pair.surround
 2826                        && is_bracket_pair_start
 2827                        && bracket_pair.start.chars().count() == 1
 2828                    {
 2829                        edits.push((selection.start..selection.start, text.clone()));
 2830                        edits.push((
 2831                            selection.end..selection.end,
 2832                            bracket_pair.end.as_str().into(),
 2833                        ));
 2834                        bracket_inserted = true;
 2835                        new_selections.push((
 2836                            Selection {
 2837                                id: selection.id,
 2838                                start: snapshot.anchor_after(selection.start),
 2839                                end: snapshot.anchor_before(selection.end),
 2840                                reversed: selection.reversed,
 2841                                goal: selection.goal,
 2842                            },
 2843                            0,
 2844                        ));
 2845                        continue;
 2846                    }
 2847                }
 2848            }
 2849
 2850            if self.auto_replace_emoji_shortcode
 2851                && selection.is_empty()
 2852                && text.as_ref().ends_with(':')
 2853            {
 2854                if let Some(possible_emoji_short_code) =
 2855                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2856                {
 2857                    if !possible_emoji_short_code.is_empty() {
 2858                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2859                            let emoji_shortcode_start = Point::new(
 2860                                selection.start.row,
 2861                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2862                            );
 2863
 2864                            // Remove shortcode from buffer
 2865                            edits.push((
 2866                                emoji_shortcode_start..selection.start,
 2867                                "".to_string().into(),
 2868                            ));
 2869                            new_selections.push((
 2870                                Selection {
 2871                                    id: selection.id,
 2872                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2873                                    end: snapshot.anchor_before(selection.start),
 2874                                    reversed: selection.reversed,
 2875                                    goal: selection.goal,
 2876                                },
 2877                                0,
 2878                            ));
 2879
 2880                            // Insert emoji
 2881                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2882                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2883                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2884
 2885                            continue;
 2886                        }
 2887                    }
 2888                }
 2889            }
 2890
 2891            // If not handling any auto-close operation, then just replace the selected
 2892            // text with the given input and move the selection to the end of the
 2893            // newly inserted text.
 2894            let anchor = snapshot.anchor_after(selection.end);
 2895            if !self.linked_edit_ranges.is_empty() {
 2896                let start_anchor = snapshot.anchor_before(selection.start);
 2897
 2898                let is_word_char = text.chars().next().map_or(true, |char| {
 2899                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2900                    classifier.is_word(char)
 2901                });
 2902
 2903                if is_word_char {
 2904                    if let Some(ranges) = self
 2905                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2906                    {
 2907                        for (buffer, edits) in ranges {
 2908                            linked_edits
 2909                                .entry(buffer.clone())
 2910                                .or_default()
 2911                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2912                        }
 2913                    }
 2914                }
 2915            }
 2916
 2917            new_selections.push((selection.map(|_| anchor), 0));
 2918            edits.push((selection.start..selection.end, text.clone()));
 2919        }
 2920
 2921        drop(snapshot);
 2922
 2923        self.transact(window, cx, |this, window, cx| {
 2924            this.buffer.update(cx, |buffer, cx| {
 2925                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2926            });
 2927            for (buffer, edits) in linked_edits {
 2928                buffer.update(cx, |buffer, cx| {
 2929                    let snapshot = buffer.snapshot();
 2930                    let edits = edits
 2931                        .into_iter()
 2932                        .map(|(range, text)| {
 2933                            use text::ToPoint as TP;
 2934                            let end_point = TP::to_point(&range.end, &snapshot);
 2935                            let start_point = TP::to_point(&range.start, &snapshot);
 2936                            (start_point..end_point, text)
 2937                        })
 2938                        .sorted_by_key(|(range, _)| range.start)
 2939                        .collect::<Vec<_>>();
 2940                    buffer.edit(edits, None, cx);
 2941                })
 2942            }
 2943            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2944            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2945            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2946            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2947                .zip(new_selection_deltas)
 2948                .map(|(selection, delta)| Selection {
 2949                    id: selection.id,
 2950                    start: selection.start + delta,
 2951                    end: selection.end + delta,
 2952                    reversed: selection.reversed,
 2953                    goal: SelectionGoal::None,
 2954                })
 2955                .collect::<Vec<_>>();
 2956
 2957            let mut i = 0;
 2958            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2959                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2960                let start = map.buffer_snapshot.anchor_before(position);
 2961                let end = map.buffer_snapshot.anchor_after(position);
 2962                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2963                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2964                        Ordering::Less => i += 1,
 2965                        Ordering::Greater => break,
 2966                        Ordering::Equal => {
 2967                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2968                                Ordering::Less => i += 1,
 2969                                Ordering::Equal => break,
 2970                                Ordering::Greater => break,
 2971                            }
 2972                        }
 2973                    }
 2974                }
 2975                this.autoclose_regions.insert(
 2976                    i,
 2977                    AutocloseRegion {
 2978                        selection_id,
 2979                        range: start..end,
 2980                        pair,
 2981                    },
 2982                );
 2983            }
 2984
 2985            let had_active_inline_completion = this.has_active_inline_completion();
 2986            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2987                s.select(new_selections)
 2988            });
 2989
 2990            if !bracket_inserted {
 2991                if let Some(on_type_format_task) =
 2992                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2993                {
 2994                    on_type_format_task.detach_and_log_err(cx);
 2995                }
 2996            }
 2997
 2998            let editor_settings = EditorSettings::get_global(cx);
 2999            if bracket_inserted
 3000                && (editor_settings.auto_signature_help
 3001                    || editor_settings.show_signature_help_after_edits)
 3002            {
 3003                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3004            }
 3005
 3006            let trigger_in_words =
 3007                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3008            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3009            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3010            this.refresh_inline_completion(true, false, window, cx);
 3011        });
 3012    }
 3013
 3014    fn find_possible_emoji_shortcode_at_position(
 3015        snapshot: &MultiBufferSnapshot,
 3016        position: Point,
 3017    ) -> Option<String> {
 3018        let mut chars = Vec::new();
 3019        let mut found_colon = false;
 3020        for char in snapshot.reversed_chars_at(position).take(100) {
 3021            // Found a possible emoji shortcode in the middle of the buffer
 3022            if found_colon {
 3023                if char.is_whitespace() {
 3024                    chars.reverse();
 3025                    return Some(chars.iter().collect());
 3026                }
 3027                // If the previous character is not a whitespace, we are in the middle of a word
 3028                // and we only want to complete the shortcode if the word is made up of other emojis
 3029                let mut containing_word = String::new();
 3030                for ch in snapshot
 3031                    .reversed_chars_at(position)
 3032                    .skip(chars.len() + 1)
 3033                    .take(100)
 3034                {
 3035                    if ch.is_whitespace() {
 3036                        break;
 3037                    }
 3038                    containing_word.push(ch);
 3039                }
 3040                let containing_word = containing_word.chars().rev().collect::<String>();
 3041                if util::word_consists_of_emojis(containing_word.as_str()) {
 3042                    chars.reverse();
 3043                    return Some(chars.iter().collect());
 3044                }
 3045            }
 3046
 3047            if char.is_whitespace() || !char.is_ascii() {
 3048                return None;
 3049            }
 3050            if char == ':' {
 3051                found_colon = true;
 3052            } else {
 3053                chars.push(char);
 3054            }
 3055        }
 3056        // Found a possible emoji shortcode at the beginning of the buffer
 3057        chars.reverse();
 3058        Some(chars.iter().collect())
 3059    }
 3060
 3061    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3062        self.transact(window, cx, |this, window, cx| {
 3063            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3064                let selections = this.selections.all::<usize>(cx);
 3065                let multi_buffer = this.buffer.read(cx);
 3066                let buffer = multi_buffer.snapshot(cx);
 3067                selections
 3068                    .iter()
 3069                    .map(|selection| {
 3070                        let start_point = selection.start.to_point(&buffer);
 3071                        let mut indent =
 3072                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3073                        indent.len = cmp::min(indent.len, start_point.column);
 3074                        let start = selection.start;
 3075                        let end = selection.end;
 3076                        let selection_is_empty = start == end;
 3077                        let language_scope = buffer.language_scope_at(start);
 3078                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3079                            &language_scope
 3080                        {
 3081                            let leading_whitespace_len = buffer
 3082                                .reversed_chars_at(start)
 3083                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3084                                .map(|c| c.len_utf8())
 3085                                .sum::<usize>();
 3086
 3087                            let trailing_whitespace_len = buffer
 3088                                .chars_at(end)
 3089                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3090                                .map(|c| c.len_utf8())
 3091                                .sum::<usize>();
 3092
 3093                            let insert_extra_newline =
 3094                                language.brackets().any(|(pair, enabled)| {
 3095                                    let pair_start = pair.start.trim_end();
 3096                                    let pair_end = pair.end.trim_start();
 3097
 3098                                    enabled
 3099                                        && pair.newline
 3100                                        && buffer.contains_str_at(
 3101                                            end + trailing_whitespace_len,
 3102                                            pair_end,
 3103                                        )
 3104                                        && buffer.contains_str_at(
 3105                                            (start - leading_whitespace_len)
 3106                                                .saturating_sub(pair_start.len()),
 3107                                            pair_start,
 3108                                        )
 3109                                });
 3110
 3111                            // Comment extension on newline is allowed only for cursor selections
 3112                            let comment_delimiter = maybe!({
 3113                                if !selection_is_empty {
 3114                                    return None;
 3115                                }
 3116
 3117                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3118                                    return None;
 3119                                }
 3120
 3121                                let delimiters = language.line_comment_prefixes();
 3122                                let max_len_of_delimiter =
 3123                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3124                                let (snapshot, range) =
 3125                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3126
 3127                                let mut index_of_first_non_whitespace = 0;
 3128                                let comment_candidate = snapshot
 3129                                    .chars_for_range(range)
 3130                                    .skip_while(|c| {
 3131                                        let should_skip = c.is_whitespace();
 3132                                        if should_skip {
 3133                                            index_of_first_non_whitespace += 1;
 3134                                        }
 3135                                        should_skip
 3136                                    })
 3137                                    .take(max_len_of_delimiter)
 3138                                    .collect::<String>();
 3139                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3140                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3141                                })?;
 3142                                let cursor_is_placed_after_comment_marker =
 3143                                    index_of_first_non_whitespace + comment_prefix.len()
 3144                                        <= start_point.column as usize;
 3145                                if cursor_is_placed_after_comment_marker {
 3146                                    Some(comment_prefix.clone())
 3147                                } else {
 3148                                    None
 3149                                }
 3150                            });
 3151                            (comment_delimiter, insert_extra_newline)
 3152                        } else {
 3153                            (None, false)
 3154                        };
 3155
 3156                        let capacity_for_delimiter = comment_delimiter
 3157                            .as_deref()
 3158                            .map(str::len)
 3159                            .unwrap_or_default();
 3160                        let mut new_text =
 3161                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3162                        new_text.push('\n');
 3163                        new_text.extend(indent.chars());
 3164                        if let Some(delimiter) = &comment_delimiter {
 3165                            new_text.push_str(delimiter);
 3166                        }
 3167                        if insert_extra_newline {
 3168                            new_text = new_text.repeat(2);
 3169                        }
 3170
 3171                        let anchor = buffer.anchor_after(end);
 3172                        let new_selection = selection.map(|_| anchor);
 3173                        (
 3174                            (start..end, new_text),
 3175                            (insert_extra_newline, new_selection),
 3176                        )
 3177                    })
 3178                    .unzip()
 3179            };
 3180
 3181            this.edit_with_autoindent(edits, cx);
 3182            let buffer = this.buffer.read(cx).snapshot(cx);
 3183            let new_selections = selection_fixup_info
 3184                .into_iter()
 3185                .map(|(extra_newline_inserted, new_selection)| {
 3186                    let mut cursor = new_selection.end.to_point(&buffer);
 3187                    if extra_newline_inserted {
 3188                        cursor.row -= 1;
 3189                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3190                    }
 3191                    new_selection.map(|_| cursor)
 3192                })
 3193                .collect();
 3194
 3195            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3196                s.select(new_selections)
 3197            });
 3198            this.refresh_inline_completion(true, false, window, cx);
 3199        });
 3200    }
 3201
 3202    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3203        let buffer = self.buffer.read(cx);
 3204        let snapshot = buffer.snapshot(cx);
 3205
 3206        let mut edits = Vec::new();
 3207        let mut rows = Vec::new();
 3208
 3209        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3210            let cursor = selection.head();
 3211            let row = cursor.row;
 3212
 3213            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3214
 3215            let newline = "\n".to_string();
 3216            edits.push((start_of_line..start_of_line, newline));
 3217
 3218            rows.push(row + rows_inserted as u32);
 3219        }
 3220
 3221        self.transact(window, cx, |editor, window, cx| {
 3222            editor.edit(edits, cx);
 3223
 3224            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3225                let mut index = 0;
 3226                s.move_cursors_with(|map, _, _| {
 3227                    let row = rows[index];
 3228                    index += 1;
 3229
 3230                    let point = Point::new(row, 0);
 3231                    let boundary = map.next_line_boundary(point).1;
 3232                    let clipped = map.clip_point(boundary, Bias::Left);
 3233
 3234                    (clipped, SelectionGoal::None)
 3235                });
 3236            });
 3237
 3238            let mut indent_edits = Vec::new();
 3239            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3240            for row in rows {
 3241                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3242                for (row, indent) in indents {
 3243                    if indent.len == 0 {
 3244                        continue;
 3245                    }
 3246
 3247                    let text = match indent.kind {
 3248                        IndentKind::Space => " ".repeat(indent.len as usize),
 3249                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3250                    };
 3251                    let point = Point::new(row.0, 0);
 3252                    indent_edits.push((point..point, text));
 3253                }
 3254            }
 3255            editor.edit(indent_edits, cx);
 3256        });
 3257    }
 3258
 3259    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3260        let buffer = self.buffer.read(cx);
 3261        let snapshot = buffer.snapshot(cx);
 3262
 3263        let mut edits = Vec::new();
 3264        let mut rows = Vec::new();
 3265        let mut rows_inserted = 0;
 3266
 3267        for selection in self.selections.all_adjusted(cx) {
 3268            let cursor = selection.head();
 3269            let row = cursor.row;
 3270
 3271            let point = Point::new(row + 1, 0);
 3272            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3273
 3274            let newline = "\n".to_string();
 3275            edits.push((start_of_line..start_of_line, newline));
 3276
 3277            rows_inserted += 1;
 3278            rows.push(row + rows_inserted);
 3279        }
 3280
 3281        self.transact(window, cx, |editor, window, cx| {
 3282            editor.edit(edits, cx);
 3283
 3284            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3285                let mut index = 0;
 3286                s.move_cursors_with(|map, _, _| {
 3287                    let row = rows[index];
 3288                    index += 1;
 3289
 3290                    let point = Point::new(row, 0);
 3291                    let boundary = map.next_line_boundary(point).1;
 3292                    let clipped = map.clip_point(boundary, Bias::Left);
 3293
 3294                    (clipped, SelectionGoal::None)
 3295                });
 3296            });
 3297
 3298            let mut indent_edits = Vec::new();
 3299            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3300            for row in rows {
 3301                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3302                for (row, indent) in indents {
 3303                    if indent.len == 0 {
 3304                        continue;
 3305                    }
 3306
 3307                    let text = match indent.kind {
 3308                        IndentKind::Space => " ".repeat(indent.len as usize),
 3309                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3310                    };
 3311                    let point = Point::new(row.0, 0);
 3312                    indent_edits.push((point..point, text));
 3313                }
 3314            }
 3315            editor.edit(indent_edits, cx);
 3316        });
 3317    }
 3318
 3319    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3320        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3321            original_indent_columns: Vec::new(),
 3322        });
 3323        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3324    }
 3325
 3326    fn insert_with_autoindent_mode(
 3327        &mut self,
 3328        text: &str,
 3329        autoindent_mode: Option<AutoindentMode>,
 3330        window: &mut Window,
 3331        cx: &mut Context<Self>,
 3332    ) {
 3333        if self.read_only(cx) {
 3334            return;
 3335        }
 3336
 3337        let text: Arc<str> = text.into();
 3338        self.transact(window, cx, |this, window, cx| {
 3339            let old_selections = this.selections.all_adjusted(cx);
 3340            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3341                let anchors = {
 3342                    let snapshot = buffer.read(cx);
 3343                    old_selections
 3344                        .iter()
 3345                        .map(|s| {
 3346                            let anchor = snapshot.anchor_after(s.head());
 3347                            s.map(|_| anchor)
 3348                        })
 3349                        .collect::<Vec<_>>()
 3350                };
 3351                buffer.edit(
 3352                    old_selections
 3353                        .iter()
 3354                        .map(|s| (s.start..s.end, text.clone())),
 3355                    autoindent_mode,
 3356                    cx,
 3357                );
 3358                anchors
 3359            });
 3360
 3361            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                s.select_anchors(selection_anchors);
 3363            });
 3364
 3365            cx.notify();
 3366        });
 3367    }
 3368
 3369    fn trigger_completion_on_input(
 3370        &mut self,
 3371        text: &str,
 3372        trigger_in_words: bool,
 3373        window: &mut Window,
 3374        cx: &mut Context<Self>,
 3375    ) {
 3376        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3377            self.show_completions(
 3378                &ShowCompletions {
 3379                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3380                },
 3381                window,
 3382                cx,
 3383            );
 3384        } else {
 3385            self.hide_context_menu(window, cx);
 3386        }
 3387    }
 3388
 3389    fn is_completion_trigger(
 3390        &self,
 3391        text: &str,
 3392        trigger_in_words: bool,
 3393        cx: &mut Context<Self>,
 3394    ) -> bool {
 3395        let position = self.selections.newest_anchor().head();
 3396        let multibuffer = self.buffer.read(cx);
 3397        let Some(buffer) = position
 3398            .buffer_id
 3399            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3400        else {
 3401            return false;
 3402        };
 3403
 3404        if let Some(completion_provider) = &self.completion_provider {
 3405            completion_provider.is_completion_trigger(
 3406                &buffer,
 3407                position.text_anchor,
 3408                text,
 3409                trigger_in_words,
 3410                cx,
 3411            )
 3412        } else {
 3413            false
 3414        }
 3415    }
 3416
 3417    /// If any empty selections is touching the start of its innermost containing autoclose
 3418    /// region, expand it to select the brackets.
 3419    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3420        let selections = self.selections.all::<usize>(cx);
 3421        let buffer = self.buffer.read(cx).read(cx);
 3422        let new_selections = self
 3423            .selections_with_autoclose_regions(selections, &buffer)
 3424            .map(|(mut selection, region)| {
 3425                if !selection.is_empty() {
 3426                    return selection;
 3427                }
 3428
 3429                if let Some(region) = region {
 3430                    let mut range = region.range.to_offset(&buffer);
 3431                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3432                        range.start -= region.pair.start.len();
 3433                        if buffer.contains_str_at(range.start, &region.pair.start)
 3434                            && buffer.contains_str_at(range.end, &region.pair.end)
 3435                        {
 3436                            range.end += region.pair.end.len();
 3437                            selection.start = range.start;
 3438                            selection.end = range.end;
 3439
 3440                            return selection;
 3441                        }
 3442                    }
 3443                }
 3444
 3445                let always_treat_brackets_as_autoclosed = buffer
 3446                    .settings_at(selection.start, cx)
 3447                    .always_treat_brackets_as_autoclosed;
 3448
 3449                if !always_treat_brackets_as_autoclosed {
 3450                    return selection;
 3451                }
 3452
 3453                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3454                    for (pair, enabled) in scope.brackets() {
 3455                        if !enabled || !pair.close {
 3456                            continue;
 3457                        }
 3458
 3459                        if buffer.contains_str_at(selection.start, &pair.end) {
 3460                            let pair_start_len = pair.start.len();
 3461                            if buffer.contains_str_at(
 3462                                selection.start.saturating_sub(pair_start_len),
 3463                                &pair.start,
 3464                            ) {
 3465                                selection.start -= pair_start_len;
 3466                                selection.end += pair.end.len();
 3467
 3468                                return selection;
 3469                            }
 3470                        }
 3471                    }
 3472                }
 3473
 3474                selection
 3475            })
 3476            .collect();
 3477
 3478        drop(buffer);
 3479        self.change_selections(None, window, cx, |selections| {
 3480            selections.select(new_selections)
 3481        });
 3482    }
 3483
 3484    /// Iterate the given selections, and for each one, find the smallest surrounding
 3485    /// autoclose region. This uses the ordering of the selections and the autoclose
 3486    /// regions to avoid repeated comparisons.
 3487    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3488        &'a self,
 3489        selections: impl IntoIterator<Item = Selection<D>>,
 3490        buffer: &'a MultiBufferSnapshot,
 3491    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3492        let mut i = 0;
 3493        let mut regions = self.autoclose_regions.as_slice();
 3494        selections.into_iter().map(move |selection| {
 3495            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3496
 3497            let mut enclosing = None;
 3498            while let Some(pair_state) = regions.get(i) {
 3499                if pair_state.range.end.to_offset(buffer) < range.start {
 3500                    regions = &regions[i + 1..];
 3501                    i = 0;
 3502                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3503                    break;
 3504                } else {
 3505                    if pair_state.selection_id == selection.id {
 3506                        enclosing = Some(pair_state);
 3507                    }
 3508                    i += 1;
 3509                }
 3510            }
 3511
 3512            (selection, enclosing)
 3513        })
 3514    }
 3515
 3516    /// Remove any autoclose regions that no longer contain their selection.
 3517    fn invalidate_autoclose_regions(
 3518        &mut self,
 3519        mut selections: &[Selection<Anchor>],
 3520        buffer: &MultiBufferSnapshot,
 3521    ) {
 3522        self.autoclose_regions.retain(|state| {
 3523            let mut i = 0;
 3524            while let Some(selection) = selections.get(i) {
 3525                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3526                    selections = &selections[1..];
 3527                    continue;
 3528                }
 3529                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3530                    break;
 3531                }
 3532                if selection.id == state.selection_id {
 3533                    return true;
 3534                } else {
 3535                    i += 1;
 3536                }
 3537            }
 3538            false
 3539        });
 3540    }
 3541
 3542    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3543        let offset = position.to_offset(buffer);
 3544        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3545        if offset > word_range.start && kind == Some(CharKind::Word) {
 3546            Some(
 3547                buffer
 3548                    .text_for_range(word_range.start..offset)
 3549                    .collect::<String>(),
 3550            )
 3551        } else {
 3552            None
 3553        }
 3554    }
 3555
 3556    pub fn toggle_inlay_hints(
 3557        &mut self,
 3558        _: &ToggleInlayHints,
 3559        _: &mut Window,
 3560        cx: &mut Context<Self>,
 3561    ) {
 3562        self.refresh_inlay_hints(
 3563            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3564            cx,
 3565        );
 3566    }
 3567
 3568    pub fn inlay_hints_enabled(&self) -> bool {
 3569        self.inlay_hint_cache.enabled
 3570    }
 3571
 3572    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3573        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3574            return;
 3575        }
 3576
 3577        let reason_description = reason.description();
 3578        let ignore_debounce = matches!(
 3579            reason,
 3580            InlayHintRefreshReason::SettingsChange(_)
 3581                | InlayHintRefreshReason::Toggle(_)
 3582                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3583        );
 3584        let (invalidate_cache, required_languages) = match reason {
 3585            InlayHintRefreshReason::Toggle(enabled) => {
 3586                self.inlay_hint_cache.enabled = enabled;
 3587                if enabled {
 3588                    (InvalidationStrategy::RefreshRequested, None)
 3589                } else {
 3590                    self.inlay_hint_cache.clear();
 3591                    self.splice_inlays(
 3592                        &self
 3593                            .visible_inlay_hints(cx)
 3594                            .iter()
 3595                            .map(|inlay| inlay.id)
 3596                            .collect::<Vec<InlayId>>(),
 3597                        Vec::new(),
 3598                        cx,
 3599                    );
 3600                    return;
 3601                }
 3602            }
 3603            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3604                match self.inlay_hint_cache.update_settings(
 3605                    &self.buffer,
 3606                    new_settings,
 3607                    self.visible_inlay_hints(cx),
 3608                    cx,
 3609                ) {
 3610                    ControlFlow::Break(Some(InlaySplice {
 3611                        to_remove,
 3612                        to_insert,
 3613                    })) => {
 3614                        self.splice_inlays(&to_remove, to_insert, cx);
 3615                        return;
 3616                    }
 3617                    ControlFlow::Break(None) => return,
 3618                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3619                }
 3620            }
 3621            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3622                if let Some(InlaySplice {
 3623                    to_remove,
 3624                    to_insert,
 3625                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3626                {
 3627                    self.splice_inlays(&to_remove, to_insert, cx);
 3628                }
 3629                return;
 3630            }
 3631            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3632            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3633                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3634            }
 3635            InlayHintRefreshReason::RefreshRequested => {
 3636                (InvalidationStrategy::RefreshRequested, None)
 3637            }
 3638        };
 3639
 3640        if let Some(InlaySplice {
 3641            to_remove,
 3642            to_insert,
 3643        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3644            reason_description,
 3645            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3646            invalidate_cache,
 3647            ignore_debounce,
 3648            cx,
 3649        ) {
 3650            self.splice_inlays(&to_remove, to_insert, cx);
 3651        }
 3652    }
 3653
 3654    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3655        self.display_map
 3656            .read(cx)
 3657            .current_inlays()
 3658            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3659            .cloned()
 3660            .collect()
 3661    }
 3662
 3663    pub fn excerpts_for_inlay_hints_query(
 3664        &self,
 3665        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3666        cx: &mut Context<Editor>,
 3667    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3668        let Some(project) = self.project.as_ref() else {
 3669            return HashMap::default();
 3670        };
 3671        let project = project.read(cx);
 3672        let multi_buffer = self.buffer().read(cx);
 3673        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3674        let multi_buffer_visible_start = self
 3675            .scroll_manager
 3676            .anchor()
 3677            .anchor
 3678            .to_point(&multi_buffer_snapshot);
 3679        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3680            multi_buffer_visible_start
 3681                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3682            Bias::Left,
 3683        );
 3684        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3685        multi_buffer_snapshot
 3686            .range_to_buffer_ranges(multi_buffer_visible_range)
 3687            .into_iter()
 3688            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3689            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3690                let buffer_file = project::File::from_dyn(buffer.file())?;
 3691                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3692                let worktree_entry = buffer_worktree
 3693                    .read(cx)
 3694                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3695                if worktree_entry.is_ignored {
 3696                    return None;
 3697                }
 3698
 3699                let language = buffer.language()?;
 3700                if let Some(restrict_to_languages) = restrict_to_languages {
 3701                    if !restrict_to_languages.contains(language) {
 3702                        return None;
 3703                    }
 3704                }
 3705                Some((
 3706                    excerpt_id,
 3707                    (
 3708                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3709                        buffer.version().clone(),
 3710                        excerpt_visible_range,
 3711                    ),
 3712                ))
 3713            })
 3714            .collect()
 3715    }
 3716
 3717    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3718        TextLayoutDetails {
 3719            text_system: window.text_system().clone(),
 3720            editor_style: self.style.clone().unwrap(),
 3721            rem_size: window.rem_size(),
 3722            scroll_anchor: self.scroll_manager.anchor(),
 3723            visible_rows: self.visible_line_count(),
 3724            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3725        }
 3726    }
 3727
 3728    pub fn splice_inlays(
 3729        &self,
 3730        to_remove: &[InlayId],
 3731        to_insert: Vec<Inlay>,
 3732        cx: &mut Context<Self>,
 3733    ) {
 3734        self.display_map.update(cx, |display_map, cx| {
 3735            display_map.splice_inlays(to_remove, to_insert, cx)
 3736        });
 3737        cx.notify();
 3738    }
 3739
 3740    fn trigger_on_type_formatting(
 3741        &self,
 3742        input: String,
 3743        window: &mut Window,
 3744        cx: &mut Context<Self>,
 3745    ) -> Option<Task<Result<()>>> {
 3746        if input.len() != 1 {
 3747            return None;
 3748        }
 3749
 3750        let project = self.project.as_ref()?;
 3751        let position = self.selections.newest_anchor().head();
 3752        let (buffer, buffer_position) = self
 3753            .buffer
 3754            .read(cx)
 3755            .text_anchor_for_position(position, cx)?;
 3756
 3757        let settings = language_settings::language_settings(
 3758            buffer
 3759                .read(cx)
 3760                .language_at(buffer_position)
 3761                .map(|l| l.name()),
 3762            buffer.read(cx).file(),
 3763            cx,
 3764        );
 3765        if !settings.use_on_type_format {
 3766            return None;
 3767        }
 3768
 3769        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3770        // hence we do LSP request & edit on host side only — add formats to host's history.
 3771        let push_to_lsp_host_history = true;
 3772        // If this is not the host, append its history with new edits.
 3773        let push_to_client_history = project.read(cx).is_via_collab();
 3774
 3775        let on_type_formatting = project.update(cx, |project, cx| {
 3776            project.on_type_format(
 3777                buffer.clone(),
 3778                buffer_position,
 3779                input,
 3780                push_to_lsp_host_history,
 3781                cx,
 3782            )
 3783        });
 3784        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3785            if let Some(transaction) = on_type_formatting.await? {
 3786                if push_to_client_history {
 3787                    buffer
 3788                        .update(&mut cx, |buffer, _| {
 3789                            buffer.push_transaction(transaction, Instant::now());
 3790                        })
 3791                        .ok();
 3792                }
 3793                editor.update(&mut cx, |editor, cx| {
 3794                    editor.refresh_document_highlights(cx);
 3795                })?;
 3796            }
 3797            Ok(())
 3798        }))
 3799    }
 3800
 3801    pub fn show_completions(
 3802        &mut self,
 3803        options: &ShowCompletions,
 3804        window: &mut Window,
 3805        cx: &mut Context<Self>,
 3806    ) {
 3807        if self.pending_rename.is_some() {
 3808            return;
 3809        }
 3810
 3811        let Some(provider) = self.completion_provider.as_ref() else {
 3812            return;
 3813        };
 3814
 3815        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3816            return;
 3817        }
 3818
 3819        let position = self.selections.newest_anchor().head();
 3820        if position.diff_base_anchor.is_some() {
 3821            return;
 3822        }
 3823        let (buffer, buffer_position) =
 3824            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3825                output
 3826            } else {
 3827                return;
 3828            };
 3829        let show_completion_documentation = buffer
 3830            .read(cx)
 3831            .snapshot()
 3832            .settings_at(buffer_position, cx)
 3833            .show_completion_documentation;
 3834
 3835        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3836
 3837        let trigger_kind = match &options.trigger {
 3838            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3839                CompletionTriggerKind::TRIGGER_CHARACTER
 3840            }
 3841            _ => CompletionTriggerKind::INVOKED,
 3842        };
 3843        let completion_context = CompletionContext {
 3844            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3845                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3846                    Some(String::from(trigger))
 3847                } else {
 3848                    None
 3849                }
 3850            }),
 3851            trigger_kind,
 3852        };
 3853        let completions =
 3854            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3855        let sort_completions = provider.sort_completions();
 3856
 3857        let id = post_inc(&mut self.next_completion_id);
 3858        let task = cx.spawn_in(window, |editor, mut cx| {
 3859            async move {
 3860                editor.update(&mut cx, |this, _| {
 3861                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3862                })?;
 3863                let completions = completions.await.log_err();
 3864                let menu = if let Some(completions) = completions {
 3865                    let mut menu = CompletionsMenu::new(
 3866                        id,
 3867                        sort_completions,
 3868                        show_completion_documentation,
 3869                        position,
 3870                        buffer.clone(),
 3871                        completions.into(),
 3872                    );
 3873
 3874                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3875                        .await;
 3876
 3877                    menu.visible().then_some(menu)
 3878                } else {
 3879                    None
 3880                };
 3881
 3882                editor.update_in(&mut cx, |editor, window, cx| {
 3883                    match editor.context_menu.borrow().as_ref() {
 3884                        None => {}
 3885                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3886                            if prev_menu.id > id {
 3887                                return;
 3888                            }
 3889                        }
 3890                        _ => return,
 3891                    }
 3892
 3893                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3894                        let mut menu = menu.unwrap();
 3895                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3896
 3897                        *editor.context_menu.borrow_mut() =
 3898                            Some(CodeContextMenu::Completions(menu));
 3899
 3900                        if editor.show_inline_completions_in_menu(cx) {
 3901                            editor.update_visible_inline_completion(window, cx);
 3902                        } else {
 3903                            editor.discard_inline_completion(false, cx);
 3904                        }
 3905
 3906                        cx.notify();
 3907                    } else if editor.completion_tasks.len() <= 1 {
 3908                        // If there are no more completion tasks and the last menu was
 3909                        // empty, we should hide it.
 3910                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3911                        // If it was already hidden and we don't show inline
 3912                        // completions in the menu, we should also show the
 3913                        // inline-completion when available.
 3914                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3915                            editor.update_visible_inline_completion(window, cx);
 3916                        }
 3917                    }
 3918                })?;
 3919
 3920                Ok::<_, anyhow::Error>(())
 3921            }
 3922            .log_err()
 3923        });
 3924
 3925        self.completion_tasks.push((id, task));
 3926    }
 3927
 3928    pub fn confirm_completion(
 3929        &mut self,
 3930        action: &ConfirmCompletion,
 3931        window: &mut Window,
 3932        cx: &mut Context<Self>,
 3933    ) -> Option<Task<Result<()>>> {
 3934        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3935    }
 3936
 3937    pub fn compose_completion(
 3938        &mut self,
 3939        action: &ComposeCompletion,
 3940        window: &mut Window,
 3941        cx: &mut Context<Self>,
 3942    ) -> Option<Task<Result<()>>> {
 3943        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3944    }
 3945
 3946    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3947        window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
 3948    }
 3949
 3950    fn do_completion(
 3951        &mut self,
 3952        item_ix: Option<usize>,
 3953        intent: CompletionIntent,
 3954        window: &mut Window,
 3955        cx: &mut Context<Editor>,
 3956    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3957        use language::ToOffset as _;
 3958
 3959        let completions_menu =
 3960            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3961                menu
 3962            } else {
 3963                return None;
 3964            };
 3965
 3966        let entries = completions_menu.entries.borrow();
 3967        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3968        if self.show_inline_completions_in_menu(cx) {
 3969            self.discard_inline_completion(true, cx);
 3970        }
 3971        let candidate_id = mat.candidate_id;
 3972        drop(entries);
 3973
 3974        let buffer_handle = completions_menu.buffer;
 3975        let completion = completions_menu
 3976            .completions
 3977            .borrow()
 3978            .get(candidate_id)?
 3979            .clone();
 3980        cx.stop_propagation();
 3981
 3982        let snippet;
 3983        let text;
 3984
 3985        if completion.is_snippet() {
 3986            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3987            text = snippet.as_ref().unwrap().text.clone();
 3988        } else {
 3989            snippet = None;
 3990            text = completion.new_text.clone();
 3991        };
 3992        let selections = self.selections.all::<usize>(cx);
 3993        let buffer = buffer_handle.read(cx);
 3994        let old_range = completion.old_range.to_offset(buffer);
 3995        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3996
 3997        let newest_selection = self.selections.newest_anchor();
 3998        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3999            return None;
 4000        }
 4001
 4002        let lookbehind = newest_selection
 4003            .start
 4004            .text_anchor
 4005            .to_offset(buffer)
 4006            .saturating_sub(old_range.start);
 4007        let lookahead = old_range
 4008            .end
 4009            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4010        let mut common_prefix_len = old_text
 4011            .bytes()
 4012            .zip(text.bytes())
 4013            .take_while(|(a, b)| a == b)
 4014            .count();
 4015
 4016        let snapshot = self.buffer.read(cx).snapshot(cx);
 4017        let mut range_to_replace: Option<Range<isize>> = None;
 4018        let mut ranges = Vec::new();
 4019        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4020        for selection in &selections {
 4021            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4022                let start = selection.start.saturating_sub(lookbehind);
 4023                let end = selection.end + lookahead;
 4024                if selection.id == newest_selection.id {
 4025                    range_to_replace = Some(
 4026                        ((start + common_prefix_len) as isize - selection.start as isize)
 4027                            ..(end as isize - selection.start as isize),
 4028                    );
 4029                }
 4030                ranges.push(start + common_prefix_len..end);
 4031            } else {
 4032                common_prefix_len = 0;
 4033                ranges.clear();
 4034                ranges.extend(selections.iter().map(|s| {
 4035                    if s.id == newest_selection.id {
 4036                        range_to_replace = Some(
 4037                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4038                                - selection.start as isize
 4039                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4040                                    - selection.start as isize,
 4041                        );
 4042                        old_range.clone()
 4043                    } else {
 4044                        s.start..s.end
 4045                    }
 4046                }));
 4047                break;
 4048            }
 4049            if !self.linked_edit_ranges.is_empty() {
 4050                let start_anchor = snapshot.anchor_before(selection.head());
 4051                let end_anchor = snapshot.anchor_after(selection.tail());
 4052                if let Some(ranges) = self
 4053                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4054                {
 4055                    for (buffer, edits) in ranges {
 4056                        linked_edits.entry(buffer.clone()).or_default().extend(
 4057                            edits
 4058                                .into_iter()
 4059                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4060                        );
 4061                    }
 4062                }
 4063            }
 4064        }
 4065        let text = &text[common_prefix_len..];
 4066
 4067        cx.emit(EditorEvent::InputHandled {
 4068            utf16_range_to_replace: range_to_replace,
 4069            text: text.into(),
 4070        });
 4071
 4072        self.transact(window, cx, |this, window, cx| {
 4073            if let Some(mut snippet) = snippet {
 4074                snippet.text = text.to_string();
 4075                for tabstop in snippet
 4076                    .tabstops
 4077                    .iter_mut()
 4078                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4079                {
 4080                    tabstop.start -= common_prefix_len as isize;
 4081                    tabstop.end -= common_prefix_len as isize;
 4082                }
 4083
 4084                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4085            } else {
 4086                this.buffer.update(cx, |buffer, cx| {
 4087                    buffer.edit(
 4088                        ranges.iter().map(|range| (range.clone(), text)),
 4089                        this.autoindent_mode.clone(),
 4090                        cx,
 4091                    );
 4092                });
 4093            }
 4094            for (buffer, edits) in linked_edits {
 4095                buffer.update(cx, |buffer, cx| {
 4096                    let snapshot = buffer.snapshot();
 4097                    let edits = edits
 4098                        .into_iter()
 4099                        .map(|(range, text)| {
 4100                            use text::ToPoint as TP;
 4101                            let end_point = TP::to_point(&range.end, &snapshot);
 4102                            let start_point = TP::to_point(&range.start, &snapshot);
 4103                            (start_point..end_point, text)
 4104                        })
 4105                        .sorted_by_key(|(range, _)| range.start)
 4106                        .collect::<Vec<_>>();
 4107                    buffer.edit(edits, None, cx);
 4108                })
 4109            }
 4110
 4111            this.refresh_inline_completion(true, false, window, cx);
 4112        });
 4113
 4114        let show_new_completions_on_confirm = completion
 4115            .confirm
 4116            .as_ref()
 4117            .map_or(false, |confirm| confirm(intent, window, cx));
 4118        if show_new_completions_on_confirm {
 4119            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4120        }
 4121
 4122        let provider = self.completion_provider.as_ref()?;
 4123        drop(completion);
 4124        let apply_edits = provider.apply_additional_edits_for_completion(
 4125            buffer_handle,
 4126            completions_menu.completions.clone(),
 4127            candidate_id,
 4128            true,
 4129            cx,
 4130        );
 4131
 4132        let editor_settings = EditorSettings::get_global(cx);
 4133        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4134            // After the code completion is finished, users often want to know what signatures are needed.
 4135            // so we should automatically call signature_help
 4136            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4137        }
 4138
 4139        Some(cx.foreground_executor().spawn(async move {
 4140            apply_edits.await?;
 4141            Ok(())
 4142        }))
 4143    }
 4144
 4145    pub fn toggle_code_actions(
 4146        &mut self,
 4147        action: &ToggleCodeActions,
 4148        window: &mut Window,
 4149        cx: &mut Context<Self>,
 4150    ) {
 4151        let mut context_menu = self.context_menu.borrow_mut();
 4152        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4153            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4154                // Toggle if we're selecting the same one
 4155                *context_menu = None;
 4156                cx.notify();
 4157                return;
 4158            } else {
 4159                // Otherwise, clear it and start a new one
 4160                *context_menu = None;
 4161                cx.notify();
 4162            }
 4163        }
 4164        drop(context_menu);
 4165        let snapshot = self.snapshot(window, cx);
 4166        let deployed_from_indicator = action.deployed_from_indicator;
 4167        let mut task = self.code_actions_task.take();
 4168        let action = action.clone();
 4169        cx.spawn_in(window, |editor, mut cx| async move {
 4170            while let Some(prev_task) = task {
 4171                prev_task.await.log_err();
 4172                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4173            }
 4174
 4175            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4176                if editor.focus_handle.is_focused(window) {
 4177                    let multibuffer_point = action
 4178                        .deployed_from_indicator
 4179                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4180                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4181                    let (buffer, buffer_row) = snapshot
 4182                        .buffer_snapshot
 4183                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4184                        .and_then(|(buffer_snapshot, range)| {
 4185                            editor
 4186                                .buffer
 4187                                .read(cx)
 4188                                .buffer(buffer_snapshot.remote_id())
 4189                                .map(|buffer| (buffer, range.start.row))
 4190                        })?;
 4191                    let (_, code_actions) = editor
 4192                        .available_code_actions
 4193                        .clone()
 4194                        .and_then(|(location, code_actions)| {
 4195                            let snapshot = location.buffer.read(cx).snapshot();
 4196                            let point_range = location.range.to_point(&snapshot);
 4197                            let point_range = point_range.start.row..=point_range.end.row;
 4198                            if point_range.contains(&buffer_row) {
 4199                                Some((location, code_actions))
 4200                            } else {
 4201                                None
 4202                            }
 4203                        })
 4204                        .unzip();
 4205                    let buffer_id = buffer.read(cx).remote_id();
 4206                    let tasks = editor
 4207                        .tasks
 4208                        .get(&(buffer_id, buffer_row))
 4209                        .map(|t| Arc::new(t.to_owned()));
 4210                    if tasks.is_none() && code_actions.is_none() {
 4211                        return None;
 4212                    }
 4213
 4214                    editor.completion_tasks.clear();
 4215                    editor.discard_inline_completion(false, cx);
 4216                    let task_context =
 4217                        tasks
 4218                            .as_ref()
 4219                            .zip(editor.project.clone())
 4220                            .map(|(tasks, project)| {
 4221                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4222                            });
 4223
 4224                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4225                        let task_context = match task_context {
 4226                            Some(task_context) => task_context.await,
 4227                            None => None,
 4228                        };
 4229                        let resolved_tasks =
 4230                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4231                                Rc::new(ResolvedTasks {
 4232                                    templates: tasks.resolve(&task_context).collect(),
 4233                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4234                                        multibuffer_point.row,
 4235                                        tasks.column,
 4236                                    )),
 4237                                })
 4238                            });
 4239                        let spawn_straight_away = resolved_tasks
 4240                            .as_ref()
 4241                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4242                            && code_actions
 4243                                .as_ref()
 4244                                .map_or(true, |actions| actions.is_empty());
 4245                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4246                            *editor.context_menu.borrow_mut() =
 4247                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4248                                    buffer,
 4249                                    actions: CodeActionContents {
 4250                                        tasks: resolved_tasks,
 4251                                        actions: code_actions,
 4252                                    },
 4253                                    selected_item: Default::default(),
 4254                                    scroll_handle: UniformListScrollHandle::default(),
 4255                                    deployed_from_indicator,
 4256                                }));
 4257                            if spawn_straight_away {
 4258                                if let Some(task) = editor.confirm_code_action(
 4259                                    &ConfirmCodeAction { item_ix: Some(0) },
 4260                                    window,
 4261                                    cx,
 4262                                ) {
 4263                                    cx.notify();
 4264                                    return task;
 4265                                }
 4266                            }
 4267                            cx.notify();
 4268                            Task::ready(Ok(()))
 4269                        }) {
 4270                            task.await
 4271                        } else {
 4272                            Ok(())
 4273                        }
 4274                    }))
 4275                } else {
 4276                    Some(Task::ready(Ok(())))
 4277                }
 4278            })?;
 4279            if let Some(task) = spawned_test_task {
 4280                task.await?;
 4281            }
 4282
 4283            Ok::<_, anyhow::Error>(())
 4284        })
 4285        .detach_and_log_err(cx);
 4286    }
 4287
 4288    pub fn confirm_code_action(
 4289        &mut self,
 4290        action: &ConfirmCodeAction,
 4291        window: &mut Window,
 4292        cx: &mut Context<Self>,
 4293    ) -> Option<Task<Result<()>>> {
 4294        let actions_menu =
 4295            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4296                menu
 4297            } else {
 4298                return None;
 4299            };
 4300        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4301        let action = actions_menu.actions.get(action_ix)?;
 4302        let title = action.label();
 4303        let buffer = actions_menu.buffer;
 4304        let workspace = self.workspace()?;
 4305
 4306        match action {
 4307            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4308                workspace.update(cx, |workspace, cx| {
 4309                    workspace::tasks::schedule_resolved_task(
 4310                        workspace,
 4311                        task_source_kind,
 4312                        resolved_task,
 4313                        false,
 4314                        cx,
 4315                    );
 4316
 4317                    Some(Task::ready(Ok(())))
 4318                })
 4319            }
 4320            CodeActionsItem::CodeAction {
 4321                excerpt_id,
 4322                action,
 4323                provider,
 4324            } => {
 4325                let apply_code_action =
 4326                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4327                let workspace = workspace.downgrade();
 4328                Some(cx.spawn_in(window, |editor, cx| async move {
 4329                    let project_transaction = apply_code_action.await?;
 4330                    Self::open_project_transaction(
 4331                        &editor,
 4332                        workspace,
 4333                        project_transaction,
 4334                        title,
 4335                        cx,
 4336                    )
 4337                    .await
 4338                }))
 4339            }
 4340        }
 4341    }
 4342
 4343    pub async fn open_project_transaction(
 4344        this: &WeakEntity<Editor>,
 4345        workspace: WeakEntity<Workspace>,
 4346        transaction: ProjectTransaction,
 4347        title: String,
 4348        mut cx: AsyncWindowContext,
 4349    ) -> Result<()> {
 4350        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4351        cx.update(|_, cx| {
 4352            entries.sort_unstable_by_key(|(buffer, _)| {
 4353                buffer.read(cx).file().map(|f| f.path().clone())
 4354            });
 4355        })?;
 4356
 4357        // If the project transaction's edits are all contained within this editor, then
 4358        // avoid opening a new editor to display them.
 4359
 4360        if let Some((buffer, transaction)) = entries.first() {
 4361            if entries.len() == 1 {
 4362                let excerpt = this.update(&mut cx, |editor, cx| {
 4363                    editor
 4364                        .buffer()
 4365                        .read(cx)
 4366                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4367                })?;
 4368                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4369                    if excerpted_buffer == *buffer {
 4370                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4371                            let excerpt_range = excerpt_range.to_offset(buffer);
 4372                            buffer
 4373                                .edited_ranges_for_transaction::<usize>(transaction)
 4374                                .all(|range| {
 4375                                    excerpt_range.start <= range.start
 4376                                        && excerpt_range.end >= range.end
 4377                                })
 4378                        })?;
 4379
 4380                        if all_edits_within_excerpt {
 4381                            return Ok(());
 4382                        }
 4383                    }
 4384                }
 4385            }
 4386        } else {
 4387            return Ok(());
 4388        }
 4389
 4390        let mut ranges_to_highlight = Vec::new();
 4391        let excerpt_buffer = cx.new(|cx| {
 4392            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4393            for (buffer_handle, transaction) in &entries {
 4394                let buffer = buffer_handle.read(cx);
 4395                ranges_to_highlight.extend(
 4396                    multibuffer.push_excerpts_with_context_lines(
 4397                        buffer_handle.clone(),
 4398                        buffer
 4399                            .edited_ranges_for_transaction::<usize>(transaction)
 4400                            .collect(),
 4401                        DEFAULT_MULTIBUFFER_CONTEXT,
 4402                        cx,
 4403                    ),
 4404                );
 4405            }
 4406            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4407            multibuffer
 4408        })?;
 4409
 4410        workspace.update_in(&mut cx, |workspace, window, cx| {
 4411            let project = workspace.project().clone();
 4412            let editor = cx
 4413                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4414            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4415            editor.update(cx, |editor, cx| {
 4416                editor.highlight_background::<Self>(
 4417                    &ranges_to_highlight,
 4418                    |theme| theme.editor_highlighted_line_background,
 4419                    cx,
 4420                );
 4421            });
 4422        })?;
 4423
 4424        Ok(())
 4425    }
 4426
 4427    pub fn clear_code_action_providers(&mut self) {
 4428        self.code_action_providers.clear();
 4429        self.available_code_actions.take();
 4430    }
 4431
 4432    pub fn add_code_action_provider(
 4433        &mut self,
 4434        provider: Rc<dyn CodeActionProvider>,
 4435        window: &mut Window,
 4436        cx: &mut Context<Self>,
 4437    ) {
 4438        if self
 4439            .code_action_providers
 4440            .iter()
 4441            .any(|existing_provider| existing_provider.id() == provider.id())
 4442        {
 4443            return;
 4444        }
 4445
 4446        self.code_action_providers.push(provider);
 4447        self.refresh_code_actions(window, cx);
 4448    }
 4449
 4450    pub fn remove_code_action_provider(
 4451        &mut self,
 4452        id: Arc<str>,
 4453        window: &mut Window,
 4454        cx: &mut Context<Self>,
 4455    ) {
 4456        self.code_action_providers
 4457            .retain(|provider| provider.id() != id);
 4458        self.refresh_code_actions(window, cx);
 4459    }
 4460
 4461    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4462        let buffer = self.buffer.read(cx);
 4463        let newest_selection = self.selections.newest_anchor().clone();
 4464        if newest_selection.head().diff_base_anchor.is_some() {
 4465            return None;
 4466        }
 4467        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4468        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4469        if start_buffer != end_buffer {
 4470            return None;
 4471        }
 4472
 4473        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4474            cx.background_executor()
 4475                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4476                .await;
 4477
 4478            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4479                let providers = this.code_action_providers.clone();
 4480                let tasks = this
 4481                    .code_action_providers
 4482                    .iter()
 4483                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4484                    .collect::<Vec<_>>();
 4485                (providers, tasks)
 4486            })?;
 4487
 4488            let mut actions = Vec::new();
 4489            for (provider, provider_actions) in
 4490                providers.into_iter().zip(future::join_all(tasks).await)
 4491            {
 4492                if let Some(provider_actions) = provider_actions.log_err() {
 4493                    actions.extend(provider_actions.into_iter().map(|action| {
 4494                        AvailableCodeAction {
 4495                            excerpt_id: newest_selection.start.excerpt_id,
 4496                            action,
 4497                            provider: provider.clone(),
 4498                        }
 4499                    }));
 4500                }
 4501            }
 4502
 4503            this.update(&mut cx, |this, cx| {
 4504                this.available_code_actions = if actions.is_empty() {
 4505                    None
 4506                } else {
 4507                    Some((
 4508                        Location {
 4509                            buffer: start_buffer,
 4510                            range: start..end,
 4511                        },
 4512                        actions.into(),
 4513                    ))
 4514                };
 4515                cx.notify();
 4516            })
 4517        }));
 4518        None
 4519    }
 4520
 4521    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4522        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4523            self.show_git_blame_inline = false;
 4524
 4525            self.show_git_blame_inline_delay_task =
 4526                Some(cx.spawn_in(window, |this, mut cx| async move {
 4527                    cx.background_executor().timer(delay).await;
 4528
 4529                    this.update(&mut cx, |this, cx| {
 4530                        this.show_git_blame_inline = true;
 4531                        cx.notify();
 4532                    })
 4533                    .log_err();
 4534                }));
 4535        }
 4536    }
 4537
 4538    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4539        if self.pending_rename.is_some() {
 4540            return None;
 4541        }
 4542
 4543        let provider = self.semantics_provider.clone()?;
 4544        let buffer = self.buffer.read(cx);
 4545        let newest_selection = self.selections.newest_anchor().clone();
 4546        let cursor_position = newest_selection.head();
 4547        let (cursor_buffer, cursor_buffer_position) =
 4548            buffer.text_anchor_for_position(cursor_position, cx)?;
 4549        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4550        if cursor_buffer != tail_buffer {
 4551            return None;
 4552        }
 4553        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4554        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4555            cx.background_executor()
 4556                .timer(Duration::from_millis(debounce))
 4557                .await;
 4558
 4559            let highlights = if let Some(highlights) = cx
 4560                .update(|cx| {
 4561                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4562                })
 4563                .ok()
 4564                .flatten()
 4565            {
 4566                highlights.await.log_err()
 4567            } else {
 4568                None
 4569            };
 4570
 4571            if let Some(highlights) = highlights {
 4572                this.update(&mut cx, |this, cx| {
 4573                    if this.pending_rename.is_some() {
 4574                        return;
 4575                    }
 4576
 4577                    let buffer_id = cursor_position.buffer_id;
 4578                    let buffer = this.buffer.read(cx);
 4579                    if !buffer
 4580                        .text_anchor_for_position(cursor_position, cx)
 4581                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4582                    {
 4583                        return;
 4584                    }
 4585
 4586                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4587                    let mut write_ranges = Vec::new();
 4588                    let mut read_ranges = Vec::new();
 4589                    for highlight in highlights {
 4590                        for (excerpt_id, excerpt_range) in
 4591                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4592                        {
 4593                            let start = highlight
 4594                                .range
 4595                                .start
 4596                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4597                            let end = highlight
 4598                                .range
 4599                                .end
 4600                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4601                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4602                                continue;
 4603                            }
 4604
 4605                            let range = Anchor {
 4606                                buffer_id,
 4607                                excerpt_id,
 4608                                text_anchor: start,
 4609                                diff_base_anchor: None,
 4610                            }..Anchor {
 4611                                buffer_id,
 4612                                excerpt_id,
 4613                                text_anchor: end,
 4614                                diff_base_anchor: None,
 4615                            };
 4616                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4617                                write_ranges.push(range);
 4618                            } else {
 4619                                read_ranges.push(range);
 4620                            }
 4621                        }
 4622                    }
 4623
 4624                    this.highlight_background::<DocumentHighlightRead>(
 4625                        &read_ranges,
 4626                        |theme| theme.editor_document_highlight_read_background,
 4627                        cx,
 4628                    );
 4629                    this.highlight_background::<DocumentHighlightWrite>(
 4630                        &write_ranges,
 4631                        |theme| theme.editor_document_highlight_write_background,
 4632                        cx,
 4633                    );
 4634                    cx.notify();
 4635                })
 4636                .log_err();
 4637            }
 4638        }));
 4639        None
 4640    }
 4641
 4642    pub fn refresh_inline_completion(
 4643        &mut self,
 4644        debounce: bool,
 4645        user_requested: bool,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) -> Option<()> {
 4649        let provider = self.inline_completion_provider()?;
 4650        let cursor = self.selections.newest_anchor().head();
 4651        let (buffer, cursor_buffer_position) =
 4652            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4653
 4654        if !user_requested
 4655            && (!self.enable_inline_completions
 4656                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4657                || !self.is_focused(window)
 4658                || buffer.read(cx).is_empty())
 4659        {
 4660            self.discard_inline_completion(false, cx);
 4661            return None;
 4662        }
 4663
 4664        self.update_visible_inline_completion(window, cx);
 4665        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4666        Some(())
 4667    }
 4668
 4669    fn cycle_inline_completion(
 4670        &mut self,
 4671        direction: Direction,
 4672        window: &mut Window,
 4673        cx: &mut Context<Self>,
 4674    ) -> Option<()> {
 4675        let provider = self.inline_completion_provider()?;
 4676        let cursor = self.selections.newest_anchor().head();
 4677        let (buffer, cursor_buffer_position) =
 4678            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4679        if !self.enable_inline_completions
 4680            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4681        {
 4682            return None;
 4683        }
 4684
 4685        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4686        self.update_visible_inline_completion(window, cx);
 4687
 4688        Some(())
 4689    }
 4690
 4691    pub fn show_inline_completion(
 4692        &mut self,
 4693        _: &ShowInlineCompletion,
 4694        window: &mut Window,
 4695        cx: &mut Context<Self>,
 4696    ) {
 4697        if !self.has_active_inline_completion() {
 4698            self.refresh_inline_completion(false, true, window, cx);
 4699            return;
 4700        }
 4701
 4702        self.update_visible_inline_completion(window, cx);
 4703    }
 4704
 4705    pub fn display_cursor_names(
 4706        &mut self,
 4707        _: &DisplayCursorNames,
 4708        window: &mut Window,
 4709        cx: &mut Context<Self>,
 4710    ) {
 4711        self.show_cursor_names(window, cx);
 4712    }
 4713
 4714    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4715        self.show_cursor_names = true;
 4716        cx.notify();
 4717        cx.spawn_in(window, |this, mut cx| async move {
 4718            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4719            this.update(&mut cx, |this, cx| {
 4720                this.show_cursor_names = false;
 4721                cx.notify()
 4722            })
 4723            .ok()
 4724        })
 4725        .detach();
 4726    }
 4727
 4728    pub fn next_inline_completion(
 4729        &mut self,
 4730        _: &NextInlineCompletion,
 4731        window: &mut Window,
 4732        cx: &mut Context<Self>,
 4733    ) {
 4734        if self.has_active_inline_completion() {
 4735            self.cycle_inline_completion(Direction::Next, window, cx);
 4736        } else {
 4737            let is_copilot_disabled = self
 4738                .refresh_inline_completion(false, true, window, cx)
 4739                .is_none();
 4740            if is_copilot_disabled {
 4741                cx.propagate();
 4742            }
 4743        }
 4744    }
 4745
 4746    pub fn previous_inline_completion(
 4747        &mut self,
 4748        _: &PreviousInlineCompletion,
 4749        window: &mut Window,
 4750        cx: &mut Context<Self>,
 4751    ) {
 4752        if self.has_active_inline_completion() {
 4753            self.cycle_inline_completion(Direction::Prev, window, cx);
 4754        } else {
 4755            let is_copilot_disabled = self
 4756                .refresh_inline_completion(false, true, window, cx)
 4757                .is_none();
 4758            if is_copilot_disabled {
 4759                cx.propagate();
 4760            }
 4761        }
 4762    }
 4763
 4764    pub fn accept_inline_completion(
 4765        &mut self,
 4766        _: &AcceptInlineCompletion,
 4767        window: &mut Window,
 4768        cx: &mut Context<Self>,
 4769    ) {
 4770        let buffer = self.buffer.read(cx);
 4771        let snapshot = buffer.snapshot(cx);
 4772        let selection = self.selections.newest_adjusted(cx);
 4773        let cursor = selection.head();
 4774        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4775        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4776        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4777        {
 4778            if cursor.column < suggested_indent.len
 4779                && cursor.column <= current_indent.len
 4780                && current_indent.len <= suggested_indent.len
 4781            {
 4782                self.tab(&Default::default(), window, cx);
 4783                return;
 4784            }
 4785        }
 4786
 4787        if self.show_inline_completions_in_menu(cx) {
 4788            self.hide_context_menu(window, cx);
 4789        }
 4790
 4791        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4792            return;
 4793        };
 4794
 4795        self.report_inline_completion_event(true, cx);
 4796
 4797        match &active_inline_completion.completion {
 4798            InlineCompletion::Move { target, .. } => {
 4799                let target = *target;
 4800                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4801                    selections.select_anchor_ranges([target..target]);
 4802                });
 4803            }
 4804            InlineCompletion::Edit { edits, .. } => {
 4805                if let Some(provider) = self.inline_completion_provider() {
 4806                    provider.accept(cx);
 4807                }
 4808
 4809                let snapshot = self.buffer.read(cx).snapshot(cx);
 4810                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4811
 4812                self.buffer.update(cx, |buffer, cx| {
 4813                    buffer.edit(edits.iter().cloned(), None, cx)
 4814                });
 4815
 4816                self.change_selections(None, window, cx, |s| {
 4817                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4818                });
 4819
 4820                self.update_visible_inline_completion(window, cx);
 4821                if self.active_inline_completion.is_none() {
 4822                    self.refresh_inline_completion(true, true, window, cx);
 4823                }
 4824
 4825                cx.notify();
 4826            }
 4827        }
 4828    }
 4829
 4830    pub fn accept_partial_inline_completion(
 4831        &mut self,
 4832        _: &AcceptPartialInlineCompletion,
 4833        window: &mut Window,
 4834        cx: &mut Context<Self>,
 4835    ) {
 4836        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4837            return;
 4838        };
 4839        if self.selections.count() != 1 {
 4840            return;
 4841        }
 4842
 4843        self.report_inline_completion_event(true, cx);
 4844
 4845        match &active_inline_completion.completion {
 4846            InlineCompletion::Move { target, .. } => {
 4847                let target = *target;
 4848                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4849                    selections.select_anchor_ranges([target..target]);
 4850                });
 4851            }
 4852            InlineCompletion::Edit { edits, .. } => {
 4853                // Find an insertion that starts at the cursor position.
 4854                let snapshot = self.buffer.read(cx).snapshot(cx);
 4855                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4856                let insertion = edits.iter().find_map(|(range, text)| {
 4857                    let range = range.to_offset(&snapshot);
 4858                    if range.is_empty() && range.start == cursor_offset {
 4859                        Some(text)
 4860                    } else {
 4861                        None
 4862                    }
 4863                });
 4864
 4865                if let Some(text) = insertion {
 4866                    let mut partial_completion = text
 4867                        .chars()
 4868                        .by_ref()
 4869                        .take_while(|c| c.is_alphabetic())
 4870                        .collect::<String>();
 4871                    if partial_completion.is_empty() {
 4872                        partial_completion = text
 4873                            .chars()
 4874                            .by_ref()
 4875                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4876                            .collect::<String>();
 4877                    }
 4878
 4879                    cx.emit(EditorEvent::InputHandled {
 4880                        utf16_range_to_replace: None,
 4881                        text: partial_completion.clone().into(),
 4882                    });
 4883
 4884                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4885
 4886                    self.refresh_inline_completion(true, true, window, cx);
 4887                    cx.notify();
 4888                } else {
 4889                    self.accept_inline_completion(&Default::default(), window, cx);
 4890                }
 4891            }
 4892        }
 4893    }
 4894
 4895    fn discard_inline_completion(
 4896        &mut self,
 4897        should_report_inline_completion_event: bool,
 4898        cx: &mut Context<Self>,
 4899    ) -> bool {
 4900        if should_report_inline_completion_event {
 4901            self.report_inline_completion_event(false, cx);
 4902        }
 4903
 4904        if let Some(provider) = self.inline_completion_provider() {
 4905            provider.discard(cx);
 4906        }
 4907
 4908        self.take_active_inline_completion(cx)
 4909    }
 4910
 4911    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4912        let Some(provider) = self.inline_completion_provider() else {
 4913            return;
 4914        };
 4915
 4916        let Some((_, buffer, _)) = self
 4917            .buffer
 4918            .read(cx)
 4919            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4920        else {
 4921            return;
 4922        };
 4923
 4924        let extension = buffer
 4925            .read(cx)
 4926            .file()
 4927            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4928
 4929        let event_type = match accepted {
 4930            true => "Edit Prediction Accepted",
 4931            false => "Edit Prediction Discarded",
 4932        };
 4933        telemetry::event!(
 4934            event_type,
 4935            provider = provider.name(),
 4936            suggestion_accepted = accepted,
 4937            file_extension = extension,
 4938        );
 4939    }
 4940
 4941    pub fn has_active_inline_completion(&self) -> bool {
 4942        self.active_inline_completion.is_some()
 4943    }
 4944
 4945    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 4946        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 4947            return false;
 4948        };
 4949
 4950        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 4951        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4952        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 4953        true
 4954    }
 4955
 4956    pub fn is_previewing_inline_completion(&self) -> bool {
 4957        matches!(
 4958            self.context_menu.borrow().as_ref(),
 4959            Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
 4960        )
 4961    }
 4962
 4963    fn update_inline_completion_preview(
 4964        &mut self,
 4965        modifiers: &Modifiers,
 4966        window: &mut Window,
 4967        cx: &mut Context<Self>,
 4968    ) {
 4969        // Moves jump directly with a preview step
 4970
 4971        if self
 4972            .active_inline_completion
 4973            .as_ref()
 4974            .map_or(true, |c| c.is_move())
 4975        {
 4976            cx.notify();
 4977            return;
 4978        }
 4979
 4980        if !self.show_inline_completions_in_menu(cx) {
 4981            return;
 4982        }
 4983
 4984        let mut menu_borrow = self.context_menu.borrow_mut();
 4985
 4986        let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
 4987            return;
 4988        };
 4989
 4990        if completions_menu.is_empty()
 4991            || completions_menu.previewing_inline_completion == modifiers.alt
 4992        {
 4993            return;
 4994        }
 4995
 4996        completions_menu.set_previewing_inline_completion(modifiers.alt);
 4997        drop(menu_borrow);
 4998        self.update_visible_inline_completion(window, cx);
 4999    }
 5000
 5001    fn update_visible_inline_completion(
 5002        &mut self,
 5003        _window: &mut Window,
 5004        cx: &mut Context<Self>,
 5005    ) -> Option<()> {
 5006        let selection = self.selections.newest_anchor();
 5007        let cursor = selection.head();
 5008        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5009        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5010        let excerpt_id = cursor.excerpt_id;
 5011
 5012        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5013        let completions_menu_has_precedence = !show_in_menu
 5014            && (self.context_menu.borrow().is_some()
 5015                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5016        if completions_menu_has_precedence
 5017            || !offset_selection.is_empty()
 5018            || !self.enable_inline_completions
 5019            || self
 5020                .active_inline_completion
 5021                .as_ref()
 5022                .map_or(false, |completion| {
 5023                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5024                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5025                    !invalidation_range.contains(&offset_selection.head())
 5026                })
 5027        {
 5028            self.discard_inline_completion(false, cx);
 5029            return None;
 5030        }
 5031
 5032        self.take_active_inline_completion(cx);
 5033        let provider = self.inline_completion_provider()?;
 5034
 5035        let (buffer, cursor_buffer_position) =
 5036            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5037
 5038        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5039        let edits = inline_completion
 5040            .edits
 5041            .into_iter()
 5042            .flat_map(|(range, new_text)| {
 5043                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5044                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5045                Some((start..end, new_text))
 5046            })
 5047            .collect::<Vec<_>>();
 5048        if edits.is_empty() {
 5049            return None;
 5050        }
 5051
 5052        let first_edit_start = edits.first().unwrap().0.start;
 5053        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5054        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5055
 5056        let last_edit_end = edits.last().unwrap().0.end;
 5057        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5058        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5059
 5060        let cursor_row = cursor.to_point(&multibuffer).row;
 5061
 5062        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5063
 5064        let mut inlay_ids = Vec::new();
 5065        let invalidation_row_range;
 5066        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5067            Some(cursor_row..edit_end_row)
 5068        } else if cursor_row > edit_end_row {
 5069            Some(edit_start_row..cursor_row)
 5070        } else {
 5071            None
 5072        };
 5073        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5074            invalidation_row_range = move_invalidation_row_range;
 5075            let target = first_edit_start;
 5076            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5077            // TODO: Base this off of TreeSitter or word boundaries?
 5078            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5079                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5080                Bias::Left,
 5081            ));
 5082            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5083                Point::new(target_point.row, target_point.column + 20),
 5084                Bias::Right,
 5085            ));
 5086            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5087            InlineCompletion::Move {
 5088                target,
 5089                range_around_target,
 5090                snapshot,
 5091            }
 5092        } else {
 5093            if !show_in_menu || !self.has_active_completions_menu() {
 5094                if edits
 5095                    .iter()
 5096                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5097                {
 5098                    let mut inlays = Vec::new();
 5099                    for (range, new_text) in &edits {
 5100                        let inlay = Inlay::inline_completion(
 5101                            post_inc(&mut self.next_inlay_id),
 5102                            range.start,
 5103                            new_text.as_str(),
 5104                        );
 5105                        inlay_ids.push(inlay.id);
 5106                        inlays.push(inlay);
 5107                    }
 5108
 5109                    self.splice_inlays(&[], inlays, cx);
 5110                } else {
 5111                    let background_color = cx.theme().status().deleted_background;
 5112                    self.highlight_text::<InlineCompletionHighlight>(
 5113                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5114                        HighlightStyle {
 5115                            background_color: Some(background_color),
 5116                            ..Default::default()
 5117                        },
 5118                        cx,
 5119                    );
 5120                }
 5121            }
 5122
 5123            invalidation_row_range = edit_start_row..edit_end_row;
 5124
 5125            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5126                if provider.show_tab_accept_marker() {
 5127                    EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
 5128                } else {
 5129                    EditDisplayMode::Inline
 5130                }
 5131            } else {
 5132                EditDisplayMode::DiffPopover
 5133            };
 5134
 5135            InlineCompletion::Edit {
 5136                edits,
 5137                edit_preview: inline_completion.edit_preview,
 5138                display_mode,
 5139                snapshot,
 5140            }
 5141        };
 5142
 5143        let invalidation_range = multibuffer
 5144            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5145            ..multibuffer.anchor_after(Point::new(
 5146                invalidation_row_range.end,
 5147                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5148            ));
 5149
 5150        self.stale_inline_completion_in_menu = None;
 5151        self.active_inline_completion = Some(InlineCompletionState {
 5152            inlay_ids,
 5153            completion,
 5154            invalidation_range,
 5155        });
 5156
 5157        cx.notify();
 5158
 5159        Some(())
 5160    }
 5161
 5162    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5163        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5164    }
 5165
 5166    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5167        let by_provider = matches!(
 5168            self.menu_inline_completions_policy,
 5169            MenuInlineCompletionsPolicy::ByProvider
 5170        );
 5171
 5172        by_provider
 5173            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5174            && self
 5175                .inline_completion_provider()
 5176                .map_or(false, |provider| provider.show_completions_in_menu())
 5177    }
 5178
 5179    fn render_code_actions_indicator(
 5180        &self,
 5181        _style: &EditorStyle,
 5182        row: DisplayRow,
 5183        is_active: bool,
 5184        cx: &mut Context<Self>,
 5185    ) -> Option<IconButton> {
 5186        if self.available_code_actions.is_some() {
 5187            Some(
 5188                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5189                    .shape(ui::IconButtonShape::Square)
 5190                    .icon_size(IconSize::XSmall)
 5191                    .icon_color(Color::Muted)
 5192                    .toggle_state(is_active)
 5193                    .tooltip({
 5194                        let focus_handle = self.focus_handle.clone();
 5195                        move |window, cx| {
 5196                            Tooltip::for_action_in(
 5197                                "Toggle Code Actions",
 5198                                &ToggleCodeActions {
 5199                                    deployed_from_indicator: None,
 5200                                },
 5201                                &focus_handle,
 5202                                window,
 5203                                cx,
 5204                            )
 5205                        }
 5206                    })
 5207                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5208                        window.focus(&editor.focus_handle(cx));
 5209                        editor.toggle_code_actions(
 5210                            &ToggleCodeActions {
 5211                                deployed_from_indicator: Some(row),
 5212                            },
 5213                            window,
 5214                            cx,
 5215                        );
 5216                    })),
 5217            )
 5218        } else {
 5219            None
 5220        }
 5221    }
 5222
 5223    fn clear_tasks(&mut self) {
 5224        self.tasks.clear()
 5225    }
 5226
 5227    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5228        if self.tasks.insert(key, value).is_some() {
 5229            // This case should hopefully be rare, but just in case...
 5230            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5231        }
 5232    }
 5233
 5234    fn build_tasks_context(
 5235        project: &Entity<Project>,
 5236        buffer: &Entity<Buffer>,
 5237        buffer_row: u32,
 5238        tasks: &Arc<RunnableTasks>,
 5239        cx: &mut Context<Self>,
 5240    ) -> Task<Option<task::TaskContext>> {
 5241        let position = Point::new(buffer_row, tasks.column);
 5242        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5243        let location = Location {
 5244            buffer: buffer.clone(),
 5245            range: range_start..range_start,
 5246        };
 5247        // Fill in the environmental variables from the tree-sitter captures
 5248        let mut captured_task_variables = TaskVariables::default();
 5249        for (capture_name, value) in tasks.extra_variables.clone() {
 5250            captured_task_variables.insert(
 5251                task::VariableName::Custom(capture_name.into()),
 5252                value.clone(),
 5253            );
 5254        }
 5255        project.update(cx, |project, cx| {
 5256            project.task_store().update(cx, |task_store, cx| {
 5257                task_store.task_context_for_location(captured_task_variables, location, cx)
 5258            })
 5259        })
 5260    }
 5261
 5262    pub fn spawn_nearest_task(
 5263        &mut self,
 5264        action: &SpawnNearestTask,
 5265        window: &mut Window,
 5266        cx: &mut Context<Self>,
 5267    ) {
 5268        let Some((workspace, _)) = self.workspace.clone() else {
 5269            return;
 5270        };
 5271        let Some(project) = self.project.clone() else {
 5272            return;
 5273        };
 5274
 5275        // Try to find a closest, enclosing node using tree-sitter that has a
 5276        // task
 5277        let Some((buffer, buffer_row, tasks)) = self
 5278            .find_enclosing_node_task(cx)
 5279            // Or find the task that's closest in row-distance.
 5280            .or_else(|| self.find_closest_task(cx))
 5281        else {
 5282            return;
 5283        };
 5284
 5285        let reveal_strategy = action.reveal;
 5286        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5287        cx.spawn_in(window, |_, mut cx| async move {
 5288            let context = task_context.await?;
 5289            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5290
 5291            let resolved = resolved_task.resolved.as_mut()?;
 5292            resolved.reveal = reveal_strategy;
 5293
 5294            workspace
 5295                .update(&mut cx, |workspace, cx| {
 5296                    workspace::tasks::schedule_resolved_task(
 5297                        workspace,
 5298                        task_source_kind,
 5299                        resolved_task,
 5300                        false,
 5301                        cx,
 5302                    );
 5303                })
 5304                .ok()
 5305        })
 5306        .detach();
 5307    }
 5308
 5309    fn find_closest_task(
 5310        &mut self,
 5311        cx: &mut Context<Self>,
 5312    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5313        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5314
 5315        let ((buffer_id, row), tasks) = self
 5316            .tasks
 5317            .iter()
 5318            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5319
 5320        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5321        let tasks = Arc::new(tasks.to_owned());
 5322        Some((buffer, *row, tasks))
 5323    }
 5324
 5325    fn find_enclosing_node_task(
 5326        &mut self,
 5327        cx: &mut Context<Self>,
 5328    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5329        let snapshot = self.buffer.read(cx).snapshot(cx);
 5330        let offset = self.selections.newest::<usize>(cx).head();
 5331        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5332        let buffer_id = excerpt.buffer().remote_id();
 5333
 5334        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5335        let mut cursor = layer.node().walk();
 5336
 5337        while cursor.goto_first_child_for_byte(offset).is_some() {
 5338            if cursor.node().end_byte() == offset {
 5339                cursor.goto_next_sibling();
 5340            }
 5341        }
 5342
 5343        // Ascend to the smallest ancestor that contains the range and has a task.
 5344        loop {
 5345            let node = cursor.node();
 5346            let node_range = node.byte_range();
 5347            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5348
 5349            // Check if this node contains our offset
 5350            if node_range.start <= offset && node_range.end >= offset {
 5351                // If it contains offset, check for task
 5352                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5353                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5354                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5355                }
 5356            }
 5357
 5358            if !cursor.goto_parent() {
 5359                break;
 5360            }
 5361        }
 5362        None
 5363    }
 5364
 5365    fn render_run_indicator(
 5366        &self,
 5367        _style: &EditorStyle,
 5368        is_active: bool,
 5369        row: DisplayRow,
 5370        cx: &mut Context<Self>,
 5371    ) -> IconButton {
 5372        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5373            .shape(ui::IconButtonShape::Square)
 5374            .icon_size(IconSize::XSmall)
 5375            .icon_color(Color::Muted)
 5376            .toggle_state(is_active)
 5377            .on_click(cx.listener(move |editor, _e, window, cx| {
 5378                window.focus(&editor.focus_handle(cx));
 5379                editor.toggle_code_actions(
 5380                    &ToggleCodeActions {
 5381                        deployed_from_indicator: Some(row),
 5382                    },
 5383                    window,
 5384                    cx,
 5385                );
 5386            }))
 5387    }
 5388
 5389    pub fn context_menu_visible(&self) -> bool {
 5390        self.context_menu
 5391            .borrow()
 5392            .as_ref()
 5393            .map_or(false, |menu| menu.visible())
 5394    }
 5395
 5396    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5397        self.context_menu
 5398            .borrow()
 5399            .as_ref()
 5400            .map(|menu| menu.origin())
 5401    }
 5402
 5403    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5404        px(32.)
 5405    }
 5406
 5407    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5408        if self.read_only(cx) {
 5409            cx.theme().players().read_only()
 5410        } else {
 5411            self.style.as_ref().unwrap().local_player
 5412        }
 5413    }
 5414
 5415    #[allow(clippy::too_many_arguments)]
 5416    fn render_edit_prediction_cursor_popover(
 5417        &self,
 5418        min_width: Pixels,
 5419        max_width: Pixels,
 5420        cursor_point: Point,
 5421        start_row: DisplayRow,
 5422        line_layouts: &[LineWithInvisibles],
 5423        style: &EditorStyle,
 5424        accept_keystroke: &gpui::Keystroke,
 5425        window: &Window,
 5426        cx: &mut Context<Editor>,
 5427    ) -> Option<AnyElement> {
 5428        let provider = self.inline_completion_provider.as_ref()?;
 5429
 5430        if provider.provider.needs_terms_acceptance(cx) {
 5431            return Some(
 5432                h_flex()
 5433                    .h(self.edit_prediction_cursor_popover_height())
 5434                    .min_w(min_width)
 5435                    .flex_1()
 5436                    .px_2()
 5437                    .gap_3()
 5438                    .elevation_2(cx)
 5439                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5440                    .id("accept-terms")
 5441                    .cursor_pointer()
 5442                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5443                    .on_click(cx.listener(|this, _event, window, cx| {
 5444                        cx.stop_propagation();
 5445                        this.toggle_zed_predict_onboarding(window, cx)
 5446                    }))
 5447                    .child(
 5448                        h_flex()
 5449                            .w_full()
 5450                            .gap_2()
 5451                            .child(Icon::new(IconName::ZedPredict))
 5452                            .child(Label::new("Accept Terms of Service"))
 5453                            .child(div().w_full())
 5454                            .child(Icon::new(IconName::ArrowUpRight))
 5455                            .into_any_element(),
 5456                    )
 5457                    .into_any(),
 5458            );
 5459        }
 5460
 5461        let is_refreshing = provider.provider.is_refreshing(cx);
 5462
 5463        fn pending_completion_container() -> Div {
 5464            h_flex()
 5465                .flex_1()
 5466                .gap_3()
 5467                .child(Icon::new(IconName::ZedPredict))
 5468        }
 5469
 5470        let completion = match &self.active_inline_completion {
 5471            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5472                completion,
 5473                cursor_point,
 5474                start_row,
 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                    start_row,
 5485                    line_layouts,
 5486                    style,
 5487                    cx,
 5488                )?,
 5489
 5490                None => {
 5491                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5492                }
 5493            },
 5494
 5495            None => pending_completion_container().child(Label::new("No Prediction")),
 5496        };
 5497
 5498        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5499        let completion = completion.font(buffer_font.clone());
 5500
 5501        let completion = if is_refreshing {
 5502            completion
 5503                .with_animation(
 5504                    "loading-completion",
 5505                    Animation::new(Duration::from_secs(2))
 5506                        .repeat()
 5507                        .with_easing(pulsating_between(0.4, 0.8)),
 5508                    |label, delta| label.opacity(delta),
 5509                )
 5510                .into_any_element()
 5511        } else {
 5512            completion.into_any_element()
 5513        };
 5514
 5515        let has_completion = self.active_inline_completion.is_some();
 5516
 5517        let is_move = self
 5518            .active_inline_completion
 5519            .as_ref()
 5520            .map_or(false, |c| c.is_move());
 5521
 5522        Some(
 5523            h_flex()
 5524                .h(self.edit_prediction_cursor_popover_height())
 5525                .min_w(min_width)
 5526                .max_w(max_width)
 5527                .flex_1()
 5528                .px_2()
 5529                .gap_3()
 5530                .elevation_2(cx)
 5531                .child(completion)
 5532                .child(
 5533                    h_flex()
 5534                        .border_l_1()
 5535                        .border_color(cx.theme().colors().border_variant)
 5536                        .pl_2()
 5537                        .child(
 5538                            h_flex()
 5539                                .font(buffer_font.clone())
 5540                                .p_1()
 5541                                .rounded_sm()
 5542                                .children(ui::render_modifiers(
 5543                                    &accept_keystroke.modifiers,
 5544                                    PlatformStyle::platform(),
 5545                                    if window.modifiers() == accept_keystroke.modifiers {
 5546                                        Some(Color::Accent)
 5547                                    } else {
 5548                                        None
 5549                                    },
 5550                                    !is_move,
 5551                                )),
 5552                        )
 5553                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5554                        .child(if is_move {
 5555                            div()
 5556                                .child(ui::Key::new(&accept_keystroke.key, None))
 5557                                .font(buffer_font.clone())
 5558                                .into_any()
 5559                        } else {
 5560                            Label::new("Preview").color(Color::Muted).into_any_element()
 5561                        }),
 5562                )
 5563                .into_any(),
 5564        )
 5565    }
 5566
 5567    fn render_edit_prediction_cursor_popover_preview(
 5568        &self,
 5569        completion: &InlineCompletionState,
 5570        cursor_point: Point,
 5571        start_row: DisplayRow,
 5572        line_layouts: &[LineWithInvisibles],
 5573        style: &EditorStyle,
 5574        cx: &mut Context<Editor>,
 5575    ) -> Option<Div> {
 5576        use text::ToPoint as _;
 5577
 5578        fn render_relative_row_jump(
 5579            prefix: impl Into<String>,
 5580            current_row: u32,
 5581            target_row: u32,
 5582        ) -> Div {
 5583            let (row_diff, arrow) = if target_row < current_row {
 5584                (current_row - target_row, IconName::ArrowUp)
 5585            } else {
 5586                (target_row - current_row, IconName::ArrowDown)
 5587            };
 5588
 5589            h_flex()
 5590                .child(
 5591                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5592                        .color(Color::Muted)
 5593                        .size(LabelSize::Small),
 5594                )
 5595                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5596        }
 5597
 5598        match &completion.completion {
 5599            InlineCompletion::Edit {
 5600                edits,
 5601                edit_preview,
 5602                snapshot,
 5603                display_mode: _,
 5604            } => {
 5605                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5606
 5607                let highlighted_edits = crate::inline_completion_edit_text(
 5608                    &snapshot,
 5609                    &edits,
 5610                    edit_preview.as_ref()?,
 5611                    true,
 5612                    cx,
 5613                );
 5614
 5615                let len_total = highlighted_edits.text.len();
 5616                let first_line = &highlighted_edits.text
 5617                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5618                let first_line_len = first_line.len();
 5619
 5620                let first_highlight_start = highlighted_edits
 5621                    .highlights
 5622                    .first()
 5623                    .map_or(0, |(range, _)| range.start);
 5624                let drop_prefix_len = first_line
 5625                    .char_indices()
 5626                    .find(|(_, c)| !c.is_whitespace())
 5627                    .map_or(first_highlight_start, |(ix, _)| {
 5628                        ix.min(first_highlight_start)
 5629                    });
 5630
 5631                let preview_text = &first_line[drop_prefix_len..];
 5632                let preview_len = preview_text.len();
 5633                let highlights = highlighted_edits
 5634                    .highlights
 5635                    .into_iter()
 5636                    .take_until(|(range, _)| range.start > first_line_len)
 5637                    .map(|(range, style)| {
 5638                        (
 5639                            range.start - drop_prefix_len
 5640                                ..(range.end - drop_prefix_len).min(preview_len),
 5641                            style,
 5642                        )
 5643                    });
 5644
 5645                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5646                    .with_highlights(&style.text, highlights);
 5647
 5648                let preview = h_flex()
 5649                    .gap_1()
 5650                    .child(styled_text)
 5651                    .when(len_total > first_line_len, |parent| parent.child(""));
 5652
 5653                let left = if first_edit_row != cursor_point.row {
 5654                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5655                        .into_any_element()
 5656                } else {
 5657                    Icon::new(IconName::ZedPredict).into_any_element()
 5658                };
 5659
 5660                Some(h_flex().flex_1().gap_3().child(left).child(preview))
 5661            }
 5662
 5663            InlineCompletion::Move {
 5664                target,
 5665                range_around_target,
 5666                snapshot,
 5667            } => {
 5668                let highlighted_text = snapshot.highlighted_text_for_range(
 5669                    range_around_target.clone(),
 5670                    None,
 5671                    &style.syntax,
 5672                );
 5673                let cursor_color = self.current_user_player_color(cx).cursor;
 5674
 5675                let start_point = range_around_target.start.to_point(&snapshot);
 5676                let end_point = range_around_target.end.to_point(&snapshot);
 5677                let target_point = target.text_anchor.to_point(&snapshot);
 5678
 5679                let cursor_relative_position = line_layouts
 5680                    .get(start_point.row.saturating_sub(start_row.0) as usize)
 5681                    .map(|line| {
 5682                        let start_column_x = line.x_for_index(start_point.column as usize);
 5683                        let target_column_x = line.x_for_index(target_point.column as usize);
 5684                        target_column_x - start_column_x
 5685                    });
 5686
 5687                let fade_before = start_point.column > 0;
 5688                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5689
 5690                let background = cx.theme().colors().elevated_surface_background;
 5691
 5692                Some(
 5693                    h_flex()
 5694                        .gap_3()
 5695                        .flex_1()
 5696                        .child(render_relative_row_jump(
 5697                            "Jump ",
 5698                            cursor_point.row,
 5699                            target.text_anchor.to_point(&snapshot).row,
 5700                        ))
 5701                        .when(!highlighted_text.text.is_empty(), |parent| {
 5702                            parent.child(
 5703                                h_flex()
 5704                                    .relative()
 5705                                    .child(highlighted_text.to_styled_text(&style.text))
 5706                                    .when(fade_before, |parent| {
 5707                                        parent.child(
 5708                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5709                                                linear_gradient(
 5710                                                    90.,
 5711                                                    linear_color_stop(background, 0.),
 5712                                                    linear_color_stop(background.opacity(0.), 1.),
 5713                                                ),
 5714                                            ),
 5715                                        )
 5716                                    })
 5717                                    .when(fade_after, |parent| {
 5718                                        parent.child(
 5719                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5720                                                linear_gradient(
 5721                                                    -90.,
 5722                                                    linear_color_stop(background, 0.),
 5723                                                    linear_color_stop(background.opacity(0.), 1.),
 5724                                                ),
 5725                                            ),
 5726                                        )
 5727                                    })
 5728                                    .when_some(cursor_relative_position, |parent, position| {
 5729                                        parent.child(
 5730                                            div()
 5731                                                .w(px(2.))
 5732                                                .h_full()
 5733                                                .bg(cursor_color)
 5734                                                .absolute()
 5735                                                .top_0()
 5736                                                .left(position),
 5737                                        )
 5738                                    }),
 5739                            )
 5740                        }),
 5741                )
 5742            }
 5743        }
 5744    }
 5745
 5746    fn render_context_menu(
 5747        &self,
 5748        style: &EditorStyle,
 5749        max_height_in_lines: u32,
 5750        y_flipped: bool,
 5751        window: &mut Window,
 5752        cx: &mut Context<Editor>,
 5753    ) -> Option<AnyElement> {
 5754        let menu = self.context_menu.borrow();
 5755        let menu = menu.as_ref()?;
 5756        if !menu.visible() {
 5757            return None;
 5758        };
 5759        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5760    }
 5761
 5762    fn render_context_menu_aside(
 5763        &self,
 5764        style: &EditorStyle,
 5765        max_size: Size<Pixels>,
 5766        cx: &mut Context<Editor>,
 5767    ) -> Option<AnyElement> {
 5768        self.context_menu.borrow().as_ref().and_then(|menu| {
 5769            if menu.visible() {
 5770                menu.render_aside(
 5771                    style,
 5772                    max_size,
 5773                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5774                    cx,
 5775                )
 5776            } else {
 5777                None
 5778            }
 5779        })
 5780    }
 5781
 5782    fn hide_context_menu(
 5783        &mut self,
 5784        window: &mut Window,
 5785        cx: &mut Context<Self>,
 5786    ) -> Option<CodeContextMenu> {
 5787        cx.notify();
 5788        self.completion_tasks.clear();
 5789        let context_menu = self.context_menu.borrow_mut().take();
 5790        self.stale_inline_completion_in_menu.take();
 5791        if context_menu.is_some() {
 5792            self.update_visible_inline_completion(window, cx);
 5793        }
 5794        context_menu
 5795    }
 5796
 5797    fn show_snippet_choices(
 5798        &mut self,
 5799        choices: &Vec<String>,
 5800        selection: Range<Anchor>,
 5801        cx: &mut Context<Self>,
 5802    ) {
 5803        if selection.start.buffer_id.is_none() {
 5804            return;
 5805        }
 5806        let buffer_id = selection.start.buffer_id.unwrap();
 5807        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5808        let id = post_inc(&mut self.next_completion_id);
 5809
 5810        if let Some(buffer) = buffer {
 5811            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5812                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5813            ));
 5814        }
 5815    }
 5816
 5817    pub fn insert_snippet(
 5818        &mut self,
 5819        insertion_ranges: &[Range<usize>],
 5820        snippet: Snippet,
 5821        window: &mut Window,
 5822        cx: &mut Context<Self>,
 5823    ) -> Result<()> {
 5824        struct Tabstop<T> {
 5825            is_end_tabstop: bool,
 5826            ranges: Vec<Range<T>>,
 5827            choices: Option<Vec<String>>,
 5828        }
 5829
 5830        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5831            let snippet_text: Arc<str> = snippet.text.clone().into();
 5832            buffer.edit(
 5833                insertion_ranges
 5834                    .iter()
 5835                    .cloned()
 5836                    .map(|range| (range, snippet_text.clone())),
 5837                Some(AutoindentMode::EachLine),
 5838                cx,
 5839            );
 5840
 5841            let snapshot = &*buffer.read(cx);
 5842            let snippet = &snippet;
 5843            snippet
 5844                .tabstops
 5845                .iter()
 5846                .map(|tabstop| {
 5847                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5848                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5849                    });
 5850                    let mut tabstop_ranges = tabstop
 5851                        .ranges
 5852                        .iter()
 5853                        .flat_map(|tabstop_range| {
 5854                            let mut delta = 0_isize;
 5855                            insertion_ranges.iter().map(move |insertion_range| {
 5856                                let insertion_start = insertion_range.start as isize + delta;
 5857                                delta +=
 5858                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5859
 5860                                let start = ((insertion_start + tabstop_range.start) as usize)
 5861                                    .min(snapshot.len());
 5862                                let end = ((insertion_start + tabstop_range.end) as usize)
 5863                                    .min(snapshot.len());
 5864                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5865                            })
 5866                        })
 5867                        .collect::<Vec<_>>();
 5868                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5869
 5870                    Tabstop {
 5871                        is_end_tabstop,
 5872                        ranges: tabstop_ranges,
 5873                        choices: tabstop.choices.clone(),
 5874                    }
 5875                })
 5876                .collect::<Vec<_>>()
 5877        });
 5878        if let Some(tabstop) = tabstops.first() {
 5879            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5880                s.select_ranges(tabstop.ranges.iter().cloned());
 5881            });
 5882
 5883            if let Some(choices) = &tabstop.choices {
 5884                if let Some(selection) = tabstop.ranges.first() {
 5885                    self.show_snippet_choices(choices, selection.clone(), cx)
 5886                }
 5887            }
 5888
 5889            // If we're already at the last tabstop and it's at the end of the snippet,
 5890            // we're done, we don't need to keep the state around.
 5891            if !tabstop.is_end_tabstop {
 5892                let choices = tabstops
 5893                    .iter()
 5894                    .map(|tabstop| tabstop.choices.clone())
 5895                    .collect();
 5896
 5897                let ranges = tabstops
 5898                    .into_iter()
 5899                    .map(|tabstop| tabstop.ranges)
 5900                    .collect::<Vec<_>>();
 5901
 5902                self.snippet_stack.push(SnippetState {
 5903                    active_index: 0,
 5904                    ranges,
 5905                    choices,
 5906                });
 5907            }
 5908
 5909            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5910            if self.autoclose_regions.is_empty() {
 5911                let snapshot = self.buffer.read(cx).snapshot(cx);
 5912                for selection in &mut self.selections.all::<Point>(cx) {
 5913                    let selection_head = selection.head();
 5914                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5915                        continue;
 5916                    };
 5917
 5918                    let mut bracket_pair = None;
 5919                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5920                    let prev_chars = snapshot
 5921                        .reversed_chars_at(selection_head)
 5922                        .collect::<String>();
 5923                    for (pair, enabled) in scope.brackets() {
 5924                        if enabled
 5925                            && pair.close
 5926                            && prev_chars.starts_with(pair.start.as_str())
 5927                            && next_chars.starts_with(pair.end.as_str())
 5928                        {
 5929                            bracket_pair = Some(pair.clone());
 5930                            break;
 5931                        }
 5932                    }
 5933                    if let Some(pair) = bracket_pair {
 5934                        let start = snapshot.anchor_after(selection_head);
 5935                        let end = snapshot.anchor_after(selection_head);
 5936                        self.autoclose_regions.push(AutocloseRegion {
 5937                            selection_id: selection.id,
 5938                            range: start..end,
 5939                            pair,
 5940                        });
 5941                    }
 5942                }
 5943            }
 5944        }
 5945        Ok(())
 5946    }
 5947
 5948    pub fn move_to_next_snippet_tabstop(
 5949        &mut self,
 5950        window: &mut Window,
 5951        cx: &mut Context<Self>,
 5952    ) -> bool {
 5953        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5954    }
 5955
 5956    pub fn move_to_prev_snippet_tabstop(
 5957        &mut self,
 5958        window: &mut Window,
 5959        cx: &mut Context<Self>,
 5960    ) -> bool {
 5961        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5962    }
 5963
 5964    pub fn move_to_snippet_tabstop(
 5965        &mut self,
 5966        bias: Bias,
 5967        window: &mut Window,
 5968        cx: &mut Context<Self>,
 5969    ) -> bool {
 5970        if let Some(mut snippet) = self.snippet_stack.pop() {
 5971            match bias {
 5972                Bias::Left => {
 5973                    if snippet.active_index > 0 {
 5974                        snippet.active_index -= 1;
 5975                    } else {
 5976                        self.snippet_stack.push(snippet);
 5977                        return false;
 5978                    }
 5979                }
 5980                Bias::Right => {
 5981                    if snippet.active_index + 1 < snippet.ranges.len() {
 5982                        snippet.active_index += 1;
 5983                    } else {
 5984                        self.snippet_stack.push(snippet);
 5985                        return false;
 5986                    }
 5987                }
 5988            }
 5989            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5990                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5991                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5992                });
 5993
 5994                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5995                    if let Some(selection) = current_ranges.first() {
 5996                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5997                    }
 5998                }
 5999
 6000                // If snippet state is not at the last tabstop, push it back on the stack
 6001                if snippet.active_index + 1 < snippet.ranges.len() {
 6002                    self.snippet_stack.push(snippet);
 6003                }
 6004                return true;
 6005            }
 6006        }
 6007
 6008        false
 6009    }
 6010
 6011    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6012        self.transact(window, cx, |this, window, cx| {
 6013            this.select_all(&SelectAll, window, cx);
 6014            this.insert("", window, cx);
 6015        });
 6016    }
 6017
 6018    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6019        self.transact(window, cx, |this, window, cx| {
 6020            this.select_autoclose_pair(window, cx);
 6021            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6022            if !this.linked_edit_ranges.is_empty() {
 6023                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6024                let snapshot = this.buffer.read(cx).snapshot(cx);
 6025
 6026                for selection in selections.iter() {
 6027                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6028                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6029                    if selection_start.buffer_id != selection_end.buffer_id {
 6030                        continue;
 6031                    }
 6032                    if let Some(ranges) =
 6033                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6034                    {
 6035                        for (buffer, entries) in ranges {
 6036                            linked_ranges.entry(buffer).or_default().extend(entries);
 6037                        }
 6038                    }
 6039                }
 6040            }
 6041
 6042            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6043            if !this.selections.line_mode {
 6044                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6045                for selection in &mut selections {
 6046                    if selection.is_empty() {
 6047                        let old_head = selection.head();
 6048                        let mut new_head =
 6049                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6050                                .to_point(&display_map);
 6051                        if let Some((buffer, line_buffer_range)) = display_map
 6052                            .buffer_snapshot
 6053                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6054                        {
 6055                            let indent_size =
 6056                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6057                            let indent_len = match indent_size.kind {
 6058                                IndentKind::Space => {
 6059                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6060                                }
 6061                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6062                            };
 6063                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6064                                let indent_len = indent_len.get();
 6065                                new_head = cmp::min(
 6066                                    new_head,
 6067                                    MultiBufferPoint::new(
 6068                                        old_head.row,
 6069                                        ((old_head.column - 1) / indent_len) * indent_len,
 6070                                    ),
 6071                                );
 6072                            }
 6073                        }
 6074
 6075                        selection.set_head(new_head, SelectionGoal::None);
 6076                    }
 6077                }
 6078            }
 6079
 6080            this.signature_help_state.set_backspace_pressed(true);
 6081            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6082                s.select(selections)
 6083            });
 6084            this.insert("", window, cx);
 6085            let empty_str: Arc<str> = Arc::from("");
 6086            for (buffer, edits) in linked_ranges {
 6087                let snapshot = buffer.read(cx).snapshot();
 6088                use text::ToPoint as TP;
 6089
 6090                let edits = edits
 6091                    .into_iter()
 6092                    .map(|range| {
 6093                        let end_point = TP::to_point(&range.end, &snapshot);
 6094                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6095
 6096                        if end_point == start_point {
 6097                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6098                                .saturating_sub(1);
 6099                            start_point =
 6100                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6101                        };
 6102
 6103                        (start_point..end_point, empty_str.clone())
 6104                    })
 6105                    .sorted_by_key(|(range, _)| range.start)
 6106                    .collect::<Vec<_>>();
 6107                buffer.update(cx, |this, cx| {
 6108                    this.edit(edits, None, cx);
 6109                })
 6110            }
 6111            this.refresh_inline_completion(true, false, window, cx);
 6112            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6113        });
 6114    }
 6115
 6116    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6117        self.transact(window, cx, |this, window, cx| {
 6118            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6119                let line_mode = s.line_mode;
 6120                s.move_with(|map, selection| {
 6121                    if selection.is_empty() && !line_mode {
 6122                        let cursor = movement::right(map, selection.head());
 6123                        selection.end = cursor;
 6124                        selection.reversed = true;
 6125                        selection.goal = SelectionGoal::None;
 6126                    }
 6127                })
 6128            });
 6129            this.insert("", window, cx);
 6130            this.refresh_inline_completion(true, false, window, cx);
 6131        });
 6132    }
 6133
 6134    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6135        if self.move_to_prev_snippet_tabstop(window, cx) {
 6136            return;
 6137        }
 6138
 6139        self.outdent(&Outdent, window, cx);
 6140    }
 6141
 6142    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6143        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6144            return;
 6145        }
 6146
 6147        let mut selections = self.selections.all_adjusted(cx);
 6148        let buffer = self.buffer.read(cx);
 6149        let snapshot = buffer.snapshot(cx);
 6150        let rows_iter = selections.iter().map(|s| s.head().row);
 6151        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6152
 6153        let mut edits = Vec::new();
 6154        let mut prev_edited_row = 0;
 6155        let mut row_delta = 0;
 6156        for selection in &mut selections {
 6157            if selection.start.row != prev_edited_row {
 6158                row_delta = 0;
 6159            }
 6160            prev_edited_row = selection.end.row;
 6161
 6162            // If the selection is non-empty, then increase the indentation of the selected lines.
 6163            if !selection.is_empty() {
 6164                row_delta =
 6165                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6166                continue;
 6167            }
 6168
 6169            // If the selection is empty and the cursor is in the leading whitespace before the
 6170            // suggested indentation, then auto-indent the line.
 6171            let cursor = selection.head();
 6172            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6173            if let Some(suggested_indent) =
 6174                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6175            {
 6176                if cursor.column < suggested_indent.len
 6177                    && cursor.column <= current_indent.len
 6178                    && current_indent.len <= suggested_indent.len
 6179                {
 6180                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6181                    selection.end = selection.start;
 6182                    if row_delta == 0 {
 6183                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6184                            cursor.row,
 6185                            current_indent,
 6186                            suggested_indent,
 6187                        ));
 6188                        row_delta = suggested_indent.len - current_indent.len;
 6189                    }
 6190                    continue;
 6191                }
 6192            }
 6193
 6194            // Otherwise, insert a hard or soft tab.
 6195            let settings = buffer.settings_at(cursor, cx);
 6196            let tab_size = if settings.hard_tabs {
 6197                IndentSize::tab()
 6198            } else {
 6199                let tab_size = settings.tab_size.get();
 6200                let char_column = snapshot
 6201                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6202                    .flat_map(str::chars)
 6203                    .count()
 6204                    + row_delta as usize;
 6205                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6206                IndentSize::spaces(chars_to_next_tab_stop)
 6207            };
 6208            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6209            selection.end = selection.start;
 6210            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6211            row_delta += tab_size.len;
 6212        }
 6213
 6214        self.transact(window, cx, |this, window, cx| {
 6215            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6216            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6217                s.select(selections)
 6218            });
 6219            this.refresh_inline_completion(true, false, window, cx);
 6220        });
 6221    }
 6222
 6223    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6224        if self.read_only(cx) {
 6225            return;
 6226        }
 6227        let mut selections = self.selections.all::<Point>(cx);
 6228        let mut prev_edited_row = 0;
 6229        let mut row_delta = 0;
 6230        let mut edits = Vec::new();
 6231        let buffer = self.buffer.read(cx);
 6232        let snapshot = buffer.snapshot(cx);
 6233        for selection in &mut selections {
 6234            if selection.start.row != prev_edited_row {
 6235                row_delta = 0;
 6236            }
 6237            prev_edited_row = selection.end.row;
 6238
 6239            row_delta =
 6240                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6241        }
 6242
 6243        self.transact(window, cx, |this, window, cx| {
 6244            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6245            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6246                s.select(selections)
 6247            });
 6248        });
 6249    }
 6250
 6251    fn indent_selection(
 6252        buffer: &MultiBuffer,
 6253        snapshot: &MultiBufferSnapshot,
 6254        selection: &mut Selection<Point>,
 6255        edits: &mut Vec<(Range<Point>, String)>,
 6256        delta_for_start_row: u32,
 6257        cx: &App,
 6258    ) -> u32 {
 6259        let settings = buffer.settings_at(selection.start, cx);
 6260        let tab_size = settings.tab_size.get();
 6261        let indent_kind = if settings.hard_tabs {
 6262            IndentKind::Tab
 6263        } else {
 6264            IndentKind::Space
 6265        };
 6266        let mut start_row = selection.start.row;
 6267        let mut end_row = selection.end.row + 1;
 6268
 6269        // If a selection ends at the beginning of a line, don't indent
 6270        // that last line.
 6271        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6272            end_row -= 1;
 6273        }
 6274
 6275        // Avoid re-indenting a row that has already been indented by a
 6276        // previous selection, but still update this selection's column
 6277        // to reflect that indentation.
 6278        if delta_for_start_row > 0 {
 6279            start_row += 1;
 6280            selection.start.column += delta_for_start_row;
 6281            if selection.end.row == selection.start.row {
 6282                selection.end.column += delta_for_start_row;
 6283            }
 6284        }
 6285
 6286        let mut delta_for_end_row = 0;
 6287        let has_multiple_rows = start_row + 1 != end_row;
 6288        for row in start_row..end_row {
 6289            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6290            let indent_delta = match (current_indent.kind, indent_kind) {
 6291                (IndentKind::Space, IndentKind::Space) => {
 6292                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6293                    IndentSize::spaces(columns_to_next_tab_stop)
 6294                }
 6295                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6296                (_, IndentKind::Tab) => IndentSize::tab(),
 6297            };
 6298
 6299            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6300                0
 6301            } else {
 6302                selection.start.column
 6303            };
 6304            let row_start = Point::new(row, start);
 6305            edits.push((
 6306                row_start..row_start,
 6307                indent_delta.chars().collect::<String>(),
 6308            ));
 6309
 6310            // Update this selection's endpoints to reflect the indentation.
 6311            if row == selection.start.row {
 6312                selection.start.column += indent_delta.len;
 6313            }
 6314            if row == selection.end.row {
 6315                selection.end.column += indent_delta.len;
 6316                delta_for_end_row = indent_delta.len;
 6317            }
 6318        }
 6319
 6320        if selection.start.row == selection.end.row {
 6321            delta_for_start_row + delta_for_end_row
 6322        } else {
 6323            delta_for_end_row
 6324        }
 6325    }
 6326
 6327    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6328        if self.read_only(cx) {
 6329            return;
 6330        }
 6331        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6332        let selections = self.selections.all::<Point>(cx);
 6333        let mut deletion_ranges = Vec::new();
 6334        let mut last_outdent = None;
 6335        {
 6336            let buffer = self.buffer.read(cx);
 6337            let snapshot = buffer.snapshot(cx);
 6338            for selection in &selections {
 6339                let settings = buffer.settings_at(selection.start, cx);
 6340                let tab_size = settings.tab_size.get();
 6341                let mut rows = selection.spanned_rows(false, &display_map);
 6342
 6343                // Avoid re-outdenting a row that has already been outdented by a
 6344                // previous selection.
 6345                if let Some(last_row) = last_outdent {
 6346                    if last_row == rows.start {
 6347                        rows.start = rows.start.next_row();
 6348                    }
 6349                }
 6350                let has_multiple_rows = rows.len() > 1;
 6351                for row in rows.iter_rows() {
 6352                    let indent_size = snapshot.indent_size_for_line(row);
 6353                    if indent_size.len > 0 {
 6354                        let deletion_len = match indent_size.kind {
 6355                            IndentKind::Space => {
 6356                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6357                                if columns_to_prev_tab_stop == 0 {
 6358                                    tab_size
 6359                                } else {
 6360                                    columns_to_prev_tab_stop
 6361                                }
 6362                            }
 6363                            IndentKind::Tab => 1,
 6364                        };
 6365                        let start = if has_multiple_rows
 6366                            || deletion_len > selection.start.column
 6367                            || indent_size.len < selection.start.column
 6368                        {
 6369                            0
 6370                        } else {
 6371                            selection.start.column - deletion_len
 6372                        };
 6373                        deletion_ranges.push(
 6374                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6375                        );
 6376                        last_outdent = Some(row);
 6377                    }
 6378                }
 6379            }
 6380        }
 6381
 6382        self.transact(window, cx, |this, window, cx| {
 6383            this.buffer.update(cx, |buffer, cx| {
 6384                let empty_str: Arc<str> = Arc::default();
 6385                buffer.edit(
 6386                    deletion_ranges
 6387                        .into_iter()
 6388                        .map(|range| (range, empty_str.clone())),
 6389                    None,
 6390                    cx,
 6391                );
 6392            });
 6393            let selections = this.selections.all::<usize>(cx);
 6394            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6395                s.select(selections)
 6396            });
 6397        });
 6398    }
 6399
 6400    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6401        if self.read_only(cx) {
 6402            return;
 6403        }
 6404        let selections = self
 6405            .selections
 6406            .all::<usize>(cx)
 6407            .into_iter()
 6408            .map(|s| s.range());
 6409
 6410        self.transact(window, cx, |this, window, cx| {
 6411            this.buffer.update(cx, |buffer, cx| {
 6412                buffer.autoindent_ranges(selections, cx);
 6413            });
 6414            let selections = this.selections.all::<usize>(cx);
 6415            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6416                s.select(selections)
 6417            });
 6418        });
 6419    }
 6420
 6421    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6423        let selections = self.selections.all::<Point>(cx);
 6424
 6425        let mut new_cursors = Vec::new();
 6426        let mut edit_ranges = Vec::new();
 6427        let mut selections = selections.iter().peekable();
 6428        while let Some(selection) = selections.next() {
 6429            let mut rows = selection.spanned_rows(false, &display_map);
 6430            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6431
 6432            // Accumulate contiguous regions of rows that we want to delete.
 6433            while let Some(next_selection) = selections.peek() {
 6434                let next_rows = next_selection.spanned_rows(false, &display_map);
 6435                if next_rows.start <= rows.end {
 6436                    rows.end = next_rows.end;
 6437                    selections.next().unwrap();
 6438                } else {
 6439                    break;
 6440                }
 6441            }
 6442
 6443            let buffer = &display_map.buffer_snapshot;
 6444            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6445            let edit_end;
 6446            let cursor_buffer_row;
 6447            if buffer.max_point().row >= rows.end.0 {
 6448                // If there's a line after the range, delete the \n from the end of the row range
 6449                // and position the cursor on the next line.
 6450                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6451                cursor_buffer_row = rows.end;
 6452            } else {
 6453                // If there isn't a line after the range, delete the \n from the line before the
 6454                // start of the row range and position the cursor there.
 6455                edit_start = edit_start.saturating_sub(1);
 6456                edit_end = buffer.len();
 6457                cursor_buffer_row = rows.start.previous_row();
 6458            }
 6459
 6460            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6461            *cursor.column_mut() =
 6462                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6463
 6464            new_cursors.push((
 6465                selection.id,
 6466                buffer.anchor_after(cursor.to_point(&display_map)),
 6467            ));
 6468            edit_ranges.push(edit_start..edit_end);
 6469        }
 6470
 6471        self.transact(window, cx, |this, window, cx| {
 6472            let buffer = this.buffer.update(cx, |buffer, cx| {
 6473                let empty_str: Arc<str> = Arc::default();
 6474                buffer.edit(
 6475                    edit_ranges
 6476                        .into_iter()
 6477                        .map(|range| (range, empty_str.clone())),
 6478                    None,
 6479                    cx,
 6480                );
 6481                buffer.snapshot(cx)
 6482            });
 6483            let new_selections = new_cursors
 6484                .into_iter()
 6485                .map(|(id, cursor)| {
 6486                    let cursor = cursor.to_point(&buffer);
 6487                    Selection {
 6488                        id,
 6489                        start: cursor,
 6490                        end: cursor,
 6491                        reversed: false,
 6492                        goal: SelectionGoal::None,
 6493                    }
 6494                })
 6495                .collect();
 6496
 6497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6498                s.select(new_selections);
 6499            });
 6500        });
 6501    }
 6502
 6503    pub fn join_lines_impl(
 6504        &mut self,
 6505        insert_whitespace: bool,
 6506        window: &mut Window,
 6507        cx: &mut Context<Self>,
 6508    ) {
 6509        if self.read_only(cx) {
 6510            return;
 6511        }
 6512        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6513        for selection in self.selections.all::<Point>(cx) {
 6514            let start = MultiBufferRow(selection.start.row);
 6515            // Treat single line selections as if they include the next line. Otherwise this action
 6516            // would do nothing for single line selections individual cursors.
 6517            let end = if selection.start.row == selection.end.row {
 6518                MultiBufferRow(selection.start.row + 1)
 6519            } else {
 6520                MultiBufferRow(selection.end.row)
 6521            };
 6522
 6523            if let Some(last_row_range) = row_ranges.last_mut() {
 6524                if start <= last_row_range.end {
 6525                    last_row_range.end = end;
 6526                    continue;
 6527                }
 6528            }
 6529            row_ranges.push(start..end);
 6530        }
 6531
 6532        let snapshot = self.buffer.read(cx).snapshot(cx);
 6533        let mut cursor_positions = Vec::new();
 6534        for row_range in &row_ranges {
 6535            let anchor = snapshot.anchor_before(Point::new(
 6536                row_range.end.previous_row().0,
 6537                snapshot.line_len(row_range.end.previous_row()),
 6538            ));
 6539            cursor_positions.push(anchor..anchor);
 6540        }
 6541
 6542        self.transact(window, cx, |this, window, cx| {
 6543            for row_range in row_ranges.into_iter().rev() {
 6544                for row in row_range.iter_rows().rev() {
 6545                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6546                    let next_line_row = row.next_row();
 6547                    let indent = snapshot.indent_size_for_line(next_line_row);
 6548                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6549
 6550                    let replace =
 6551                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6552                            " "
 6553                        } else {
 6554                            ""
 6555                        };
 6556
 6557                    this.buffer.update(cx, |buffer, cx| {
 6558                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6559                    });
 6560                }
 6561            }
 6562
 6563            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6564                s.select_anchor_ranges(cursor_positions)
 6565            });
 6566        });
 6567    }
 6568
 6569    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6570        self.join_lines_impl(true, window, cx);
 6571    }
 6572
 6573    pub fn sort_lines_case_sensitive(
 6574        &mut self,
 6575        _: &SortLinesCaseSensitive,
 6576        window: &mut Window,
 6577        cx: &mut Context<Self>,
 6578    ) {
 6579        self.manipulate_lines(window, cx, |lines| lines.sort())
 6580    }
 6581
 6582    pub fn sort_lines_case_insensitive(
 6583        &mut self,
 6584        _: &SortLinesCaseInsensitive,
 6585        window: &mut Window,
 6586        cx: &mut Context<Self>,
 6587    ) {
 6588        self.manipulate_lines(window, cx, |lines| {
 6589            lines.sort_by_key(|line| line.to_lowercase())
 6590        })
 6591    }
 6592
 6593    pub fn unique_lines_case_insensitive(
 6594        &mut self,
 6595        _: &UniqueLinesCaseInsensitive,
 6596        window: &mut Window,
 6597        cx: &mut Context<Self>,
 6598    ) {
 6599        self.manipulate_lines(window, cx, |lines| {
 6600            let mut seen = HashSet::default();
 6601            lines.retain(|line| seen.insert(line.to_lowercase()));
 6602        })
 6603    }
 6604
 6605    pub fn unique_lines_case_sensitive(
 6606        &mut self,
 6607        _: &UniqueLinesCaseSensitive,
 6608        window: &mut Window,
 6609        cx: &mut Context<Self>,
 6610    ) {
 6611        self.manipulate_lines(window, cx, |lines| {
 6612            let mut seen = HashSet::default();
 6613            lines.retain(|line| seen.insert(*line));
 6614        })
 6615    }
 6616
 6617    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6618        let mut revert_changes = HashMap::default();
 6619        let snapshot = self.snapshot(window, cx);
 6620        for hunk in snapshot
 6621            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6622        {
 6623            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6624        }
 6625        if !revert_changes.is_empty() {
 6626            self.transact(window, cx, |editor, window, cx| {
 6627                editor.revert(revert_changes, window, cx);
 6628            });
 6629        }
 6630    }
 6631
 6632    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6633        let Some(project) = self.project.clone() else {
 6634            return;
 6635        };
 6636        self.reload(project, window, cx)
 6637            .detach_and_notify_err(window, cx);
 6638    }
 6639
 6640    pub fn revert_selected_hunks(
 6641        &mut self,
 6642        _: &RevertSelectedHunks,
 6643        window: &mut Window,
 6644        cx: &mut Context<Self>,
 6645    ) {
 6646        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6647        self.revert_hunks_in_ranges(selections, window, cx);
 6648    }
 6649
 6650    fn revert_hunks_in_ranges(
 6651        &mut self,
 6652        ranges: impl Iterator<Item = Range<Point>>,
 6653        window: &mut Window,
 6654        cx: &mut Context<Editor>,
 6655    ) {
 6656        let mut revert_changes = HashMap::default();
 6657        let snapshot = self.snapshot(window, cx);
 6658        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6659            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6660        }
 6661        if !revert_changes.is_empty() {
 6662            self.transact(window, cx, |editor, window, cx| {
 6663                editor.revert(revert_changes, window, cx);
 6664            });
 6665        }
 6666    }
 6667
 6668    pub fn open_active_item_in_terminal(
 6669        &mut self,
 6670        _: &OpenInTerminal,
 6671        window: &mut Window,
 6672        cx: &mut Context<Self>,
 6673    ) {
 6674        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6675            let project_path = buffer.read(cx).project_path(cx)?;
 6676            let project = self.project.as_ref()?.read(cx);
 6677            let entry = project.entry_for_path(&project_path, cx)?;
 6678            let parent = match &entry.canonical_path {
 6679                Some(canonical_path) => canonical_path.to_path_buf(),
 6680                None => project.absolute_path(&project_path, cx)?,
 6681            }
 6682            .parent()?
 6683            .to_path_buf();
 6684            Some(parent)
 6685        }) {
 6686            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6687        }
 6688    }
 6689
 6690    pub fn prepare_revert_change(
 6691        &self,
 6692        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6693        hunk: &MultiBufferDiffHunk,
 6694        cx: &mut App,
 6695    ) -> Option<()> {
 6696        let buffer = self.buffer.read(cx);
 6697        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6698        let buffer = buffer.buffer(hunk.buffer_id)?;
 6699        let buffer = buffer.read(cx);
 6700        let original_text = change_set
 6701            .read(cx)
 6702            .base_text
 6703            .as_ref()?
 6704            .as_rope()
 6705            .slice(hunk.diff_base_byte_range.clone());
 6706        let buffer_snapshot = buffer.snapshot();
 6707        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6708        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6709            probe
 6710                .0
 6711                .start
 6712                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6713                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6714        }) {
 6715            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6716            Some(())
 6717        } else {
 6718            None
 6719        }
 6720    }
 6721
 6722    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6723        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6724    }
 6725
 6726    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6727        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6728    }
 6729
 6730    fn manipulate_lines<Fn>(
 6731        &mut self,
 6732        window: &mut Window,
 6733        cx: &mut Context<Self>,
 6734        mut callback: Fn,
 6735    ) where
 6736        Fn: FnMut(&mut Vec<&str>),
 6737    {
 6738        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6739        let buffer = self.buffer.read(cx).snapshot(cx);
 6740
 6741        let mut edits = Vec::new();
 6742
 6743        let selections = self.selections.all::<Point>(cx);
 6744        let mut selections = selections.iter().peekable();
 6745        let mut contiguous_row_selections = Vec::new();
 6746        let mut new_selections = Vec::new();
 6747        let mut added_lines = 0;
 6748        let mut removed_lines = 0;
 6749
 6750        while let Some(selection) = selections.next() {
 6751            let (start_row, end_row) = consume_contiguous_rows(
 6752                &mut contiguous_row_selections,
 6753                selection,
 6754                &display_map,
 6755                &mut selections,
 6756            );
 6757
 6758            let start_point = Point::new(start_row.0, 0);
 6759            let end_point = Point::new(
 6760                end_row.previous_row().0,
 6761                buffer.line_len(end_row.previous_row()),
 6762            );
 6763            let text = buffer
 6764                .text_for_range(start_point..end_point)
 6765                .collect::<String>();
 6766
 6767            let mut lines = text.split('\n').collect_vec();
 6768
 6769            let lines_before = lines.len();
 6770            callback(&mut lines);
 6771            let lines_after = lines.len();
 6772
 6773            edits.push((start_point..end_point, lines.join("\n")));
 6774
 6775            // Selections must change based on added and removed line count
 6776            let start_row =
 6777                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6778            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6779            new_selections.push(Selection {
 6780                id: selection.id,
 6781                start: start_row,
 6782                end: end_row,
 6783                goal: SelectionGoal::None,
 6784                reversed: selection.reversed,
 6785            });
 6786
 6787            if lines_after > lines_before {
 6788                added_lines += lines_after - lines_before;
 6789            } else if lines_before > lines_after {
 6790                removed_lines += lines_before - lines_after;
 6791            }
 6792        }
 6793
 6794        self.transact(window, cx, |this, window, cx| {
 6795            let buffer = this.buffer.update(cx, |buffer, cx| {
 6796                buffer.edit(edits, None, cx);
 6797                buffer.snapshot(cx)
 6798            });
 6799
 6800            // Recalculate offsets on newly edited buffer
 6801            let new_selections = new_selections
 6802                .iter()
 6803                .map(|s| {
 6804                    let start_point = Point::new(s.start.0, 0);
 6805                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6806                    Selection {
 6807                        id: s.id,
 6808                        start: buffer.point_to_offset(start_point),
 6809                        end: buffer.point_to_offset(end_point),
 6810                        goal: s.goal,
 6811                        reversed: s.reversed,
 6812                    }
 6813                })
 6814                .collect();
 6815
 6816            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6817                s.select(new_selections);
 6818            });
 6819
 6820            this.request_autoscroll(Autoscroll::fit(), cx);
 6821        });
 6822    }
 6823
 6824    pub fn convert_to_upper_case(
 6825        &mut self,
 6826        _: &ConvertToUpperCase,
 6827        window: &mut Window,
 6828        cx: &mut Context<Self>,
 6829    ) {
 6830        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6831    }
 6832
 6833    pub fn convert_to_lower_case(
 6834        &mut self,
 6835        _: &ConvertToLowerCase,
 6836        window: &mut Window,
 6837        cx: &mut Context<Self>,
 6838    ) {
 6839        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6840    }
 6841
 6842    pub fn convert_to_title_case(
 6843        &mut self,
 6844        _: &ConvertToTitleCase,
 6845        window: &mut Window,
 6846        cx: &mut Context<Self>,
 6847    ) {
 6848        self.manipulate_text(window, cx, |text| {
 6849            text.split('\n')
 6850                .map(|line| line.to_case(Case::Title))
 6851                .join("\n")
 6852        })
 6853    }
 6854
 6855    pub fn convert_to_snake_case(
 6856        &mut self,
 6857        _: &ConvertToSnakeCase,
 6858        window: &mut Window,
 6859        cx: &mut Context<Self>,
 6860    ) {
 6861        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6862    }
 6863
 6864    pub fn convert_to_kebab_case(
 6865        &mut self,
 6866        _: &ConvertToKebabCase,
 6867        window: &mut Window,
 6868        cx: &mut Context<Self>,
 6869    ) {
 6870        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6871    }
 6872
 6873    pub fn convert_to_upper_camel_case(
 6874        &mut self,
 6875        _: &ConvertToUpperCamelCase,
 6876        window: &mut Window,
 6877        cx: &mut Context<Self>,
 6878    ) {
 6879        self.manipulate_text(window, cx, |text| {
 6880            text.split('\n')
 6881                .map(|line| line.to_case(Case::UpperCamel))
 6882                .join("\n")
 6883        })
 6884    }
 6885
 6886    pub fn convert_to_lower_camel_case(
 6887        &mut self,
 6888        _: &ConvertToLowerCamelCase,
 6889        window: &mut Window,
 6890        cx: &mut Context<Self>,
 6891    ) {
 6892        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6893    }
 6894
 6895    pub fn convert_to_opposite_case(
 6896        &mut self,
 6897        _: &ConvertToOppositeCase,
 6898        window: &mut Window,
 6899        cx: &mut Context<Self>,
 6900    ) {
 6901        self.manipulate_text(window, cx, |text| {
 6902            text.chars()
 6903                .fold(String::with_capacity(text.len()), |mut t, c| {
 6904                    if c.is_uppercase() {
 6905                        t.extend(c.to_lowercase());
 6906                    } else {
 6907                        t.extend(c.to_uppercase());
 6908                    }
 6909                    t
 6910                })
 6911        })
 6912    }
 6913
 6914    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6915    where
 6916        Fn: FnMut(&str) -> String,
 6917    {
 6918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6919        let buffer = self.buffer.read(cx).snapshot(cx);
 6920
 6921        let mut new_selections = Vec::new();
 6922        let mut edits = Vec::new();
 6923        let mut selection_adjustment = 0i32;
 6924
 6925        for selection in self.selections.all::<usize>(cx) {
 6926            let selection_is_empty = selection.is_empty();
 6927
 6928            let (start, end) = if selection_is_empty {
 6929                let word_range = movement::surrounding_word(
 6930                    &display_map,
 6931                    selection.start.to_display_point(&display_map),
 6932                );
 6933                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6934                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6935                (start, end)
 6936            } else {
 6937                (selection.start, selection.end)
 6938            };
 6939
 6940            let text = buffer.text_for_range(start..end).collect::<String>();
 6941            let old_length = text.len() as i32;
 6942            let text = callback(&text);
 6943
 6944            new_selections.push(Selection {
 6945                start: (start as i32 - selection_adjustment) as usize,
 6946                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6947                goal: SelectionGoal::None,
 6948                ..selection
 6949            });
 6950
 6951            selection_adjustment += old_length - text.len() as i32;
 6952
 6953            edits.push((start..end, text));
 6954        }
 6955
 6956        self.transact(window, cx, |this, window, cx| {
 6957            this.buffer.update(cx, |buffer, cx| {
 6958                buffer.edit(edits, None, cx);
 6959            });
 6960
 6961            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6962                s.select(new_selections);
 6963            });
 6964
 6965            this.request_autoscroll(Autoscroll::fit(), cx);
 6966        });
 6967    }
 6968
 6969    pub fn duplicate(
 6970        &mut self,
 6971        upwards: bool,
 6972        whole_lines: bool,
 6973        window: &mut Window,
 6974        cx: &mut Context<Self>,
 6975    ) {
 6976        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6977        let buffer = &display_map.buffer_snapshot;
 6978        let selections = self.selections.all::<Point>(cx);
 6979
 6980        let mut edits = Vec::new();
 6981        let mut selections_iter = selections.iter().peekable();
 6982        while let Some(selection) = selections_iter.next() {
 6983            let mut rows = selection.spanned_rows(false, &display_map);
 6984            // duplicate line-wise
 6985            if whole_lines || selection.start == selection.end {
 6986                // Avoid duplicating the same lines twice.
 6987                while let Some(next_selection) = selections_iter.peek() {
 6988                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6989                    if next_rows.start < rows.end {
 6990                        rows.end = next_rows.end;
 6991                        selections_iter.next().unwrap();
 6992                    } else {
 6993                        break;
 6994                    }
 6995                }
 6996
 6997                // Copy the text from the selected row region and splice it either at the start
 6998                // or end of the region.
 6999                let start = Point::new(rows.start.0, 0);
 7000                let end = Point::new(
 7001                    rows.end.previous_row().0,
 7002                    buffer.line_len(rows.end.previous_row()),
 7003                );
 7004                let text = buffer
 7005                    .text_for_range(start..end)
 7006                    .chain(Some("\n"))
 7007                    .collect::<String>();
 7008                let insert_location = if upwards {
 7009                    Point::new(rows.end.0, 0)
 7010                } else {
 7011                    start
 7012                };
 7013                edits.push((insert_location..insert_location, text));
 7014            } else {
 7015                // duplicate character-wise
 7016                let start = selection.start;
 7017                let end = selection.end;
 7018                let text = buffer.text_for_range(start..end).collect::<String>();
 7019                edits.push((selection.end..selection.end, text));
 7020            }
 7021        }
 7022
 7023        self.transact(window, cx, |this, _, cx| {
 7024            this.buffer.update(cx, |buffer, cx| {
 7025                buffer.edit(edits, None, cx);
 7026            });
 7027
 7028            this.request_autoscroll(Autoscroll::fit(), cx);
 7029        });
 7030    }
 7031
 7032    pub fn duplicate_line_up(
 7033        &mut self,
 7034        _: &DuplicateLineUp,
 7035        window: &mut Window,
 7036        cx: &mut Context<Self>,
 7037    ) {
 7038        self.duplicate(true, true, window, cx);
 7039    }
 7040
 7041    pub fn duplicate_line_down(
 7042        &mut self,
 7043        _: &DuplicateLineDown,
 7044        window: &mut Window,
 7045        cx: &mut Context<Self>,
 7046    ) {
 7047        self.duplicate(false, true, window, cx);
 7048    }
 7049
 7050    pub fn duplicate_selection(
 7051        &mut self,
 7052        _: &DuplicateSelection,
 7053        window: &mut Window,
 7054        cx: &mut Context<Self>,
 7055    ) {
 7056        self.duplicate(false, false, window, cx);
 7057    }
 7058
 7059    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7060        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7061        let buffer = self.buffer.read(cx).snapshot(cx);
 7062
 7063        let mut edits = Vec::new();
 7064        let mut unfold_ranges = Vec::new();
 7065        let mut refold_creases = Vec::new();
 7066
 7067        let selections = self.selections.all::<Point>(cx);
 7068        let mut selections = selections.iter().peekable();
 7069        let mut contiguous_row_selections = Vec::new();
 7070        let mut new_selections = Vec::new();
 7071
 7072        while let Some(selection) = selections.next() {
 7073            // Find all the selections that span a contiguous row range
 7074            let (start_row, end_row) = consume_contiguous_rows(
 7075                &mut contiguous_row_selections,
 7076                selection,
 7077                &display_map,
 7078                &mut selections,
 7079            );
 7080
 7081            // Move the text spanned by the row range to be before the line preceding the row range
 7082            if start_row.0 > 0 {
 7083                let range_to_move = Point::new(
 7084                    start_row.previous_row().0,
 7085                    buffer.line_len(start_row.previous_row()),
 7086                )
 7087                    ..Point::new(
 7088                        end_row.previous_row().0,
 7089                        buffer.line_len(end_row.previous_row()),
 7090                    );
 7091                let insertion_point = display_map
 7092                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7093                    .0;
 7094
 7095                // Don't move lines across excerpts
 7096                if buffer
 7097                    .excerpt_containing(insertion_point..range_to_move.end)
 7098                    .is_some()
 7099                {
 7100                    let text = buffer
 7101                        .text_for_range(range_to_move.clone())
 7102                        .flat_map(|s| s.chars())
 7103                        .skip(1)
 7104                        .chain(['\n'])
 7105                        .collect::<String>();
 7106
 7107                    edits.push((
 7108                        buffer.anchor_after(range_to_move.start)
 7109                            ..buffer.anchor_before(range_to_move.end),
 7110                        String::new(),
 7111                    ));
 7112                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7113                    edits.push((insertion_anchor..insertion_anchor, text));
 7114
 7115                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7116
 7117                    // Move selections up
 7118                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7119                        |mut selection| {
 7120                            selection.start.row -= row_delta;
 7121                            selection.end.row -= row_delta;
 7122                            selection
 7123                        },
 7124                    ));
 7125
 7126                    // Move folds up
 7127                    unfold_ranges.push(range_to_move.clone());
 7128                    for fold in display_map.folds_in_range(
 7129                        buffer.anchor_before(range_to_move.start)
 7130                            ..buffer.anchor_after(range_to_move.end),
 7131                    ) {
 7132                        let mut start = fold.range.start.to_point(&buffer);
 7133                        let mut end = fold.range.end.to_point(&buffer);
 7134                        start.row -= row_delta;
 7135                        end.row -= row_delta;
 7136                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7137                    }
 7138                }
 7139            }
 7140
 7141            // If we didn't move line(s), preserve the existing selections
 7142            new_selections.append(&mut contiguous_row_selections);
 7143        }
 7144
 7145        self.transact(window, cx, |this, window, cx| {
 7146            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7147            this.buffer.update(cx, |buffer, cx| {
 7148                for (range, text) in edits {
 7149                    buffer.edit([(range, text)], None, cx);
 7150                }
 7151            });
 7152            this.fold_creases(refold_creases, true, window, cx);
 7153            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7154                s.select(new_selections);
 7155            })
 7156        });
 7157    }
 7158
 7159    pub fn move_line_down(
 7160        &mut self,
 7161        _: &MoveLineDown,
 7162        window: &mut Window,
 7163        cx: &mut Context<Self>,
 7164    ) {
 7165        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7166        let buffer = self.buffer.read(cx).snapshot(cx);
 7167
 7168        let mut edits = Vec::new();
 7169        let mut unfold_ranges = Vec::new();
 7170        let mut refold_creases = Vec::new();
 7171
 7172        let selections = self.selections.all::<Point>(cx);
 7173        let mut selections = selections.iter().peekable();
 7174        let mut contiguous_row_selections = Vec::new();
 7175        let mut new_selections = Vec::new();
 7176
 7177        while let Some(selection) = selections.next() {
 7178            // Find all the selections that span a contiguous row range
 7179            let (start_row, end_row) = consume_contiguous_rows(
 7180                &mut contiguous_row_selections,
 7181                selection,
 7182                &display_map,
 7183                &mut selections,
 7184            );
 7185
 7186            // Move the text spanned by the row range to be after the last line of the row range
 7187            if end_row.0 <= buffer.max_point().row {
 7188                let range_to_move =
 7189                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7190                let insertion_point = display_map
 7191                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7192                    .0;
 7193
 7194                // Don't move lines across excerpt boundaries
 7195                if buffer
 7196                    .excerpt_containing(range_to_move.start..insertion_point)
 7197                    .is_some()
 7198                {
 7199                    let mut text = String::from("\n");
 7200                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7201                    text.pop(); // Drop trailing newline
 7202                    edits.push((
 7203                        buffer.anchor_after(range_to_move.start)
 7204                            ..buffer.anchor_before(range_to_move.end),
 7205                        String::new(),
 7206                    ));
 7207                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7208                    edits.push((insertion_anchor..insertion_anchor, text));
 7209
 7210                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7211
 7212                    // Move selections down
 7213                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7214                        |mut selection| {
 7215                            selection.start.row += row_delta;
 7216                            selection.end.row += row_delta;
 7217                            selection
 7218                        },
 7219                    ));
 7220
 7221                    // Move folds down
 7222                    unfold_ranges.push(range_to_move.clone());
 7223                    for fold in display_map.folds_in_range(
 7224                        buffer.anchor_before(range_to_move.start)
 7225                            ..buffer.anchor_after(range_to_move.end),
 7226                    ) {
 7227                        let mut start = fold.range.start.to_point(&buffer);
 7228                        let mut end = fold.range.end.to_point(&buffer);
 7229                        start.row += row_delta;
 7230                        end.row += row_delta;
 7231                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7232                    }
 7233                }
 7234            }
 7235
 7236            // If we didn't move line(s), preserve the existing selections
 7237            new_selections.append(&mut contiguous_row_selections);
 7238        }
 7239
 7240        self.transact(window, cx, |this, window, cx| {
 7241            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7242            this.buffer.update(cx, |buffer, cx| {
 7243                for (range, text) in edits {
 7244                    buffer.edit([(range, text)], None, cx);
 7245                }
 7246            });
 7247            this.fold_creases(refold_creases, true, window, cx);
 7248            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7249                s.select(new_selections)
 7250            });
 7251        });
 7252    }
 7253
 7254    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7255        let text_layout_details = &self.text_layout_details(window);
 7256        self.transact(window, cx, |this, window, cx| {
 7257            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7258                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7259                let line_mode = s.line_mode;
 7260                s.move_with(|display_map, selection| {
 7261                    if !selection.is_empty() || line_mode {
 7262                        return;
 7263                    }
 7264
 7265                    let mut head = selection.head();
 7266                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7267                    if head.column() == display_map.line_len(head.row()) {
 7268                        transpose_offset = display_map
 7269                            .buffer_snapshot
 7270                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7271                    }
 7272
 7273                    if transpose_offset == 0 {
 7274                        return;
 7275                    }
 7276
 7277                    *head.column_mut() += 1;
 7278                    head = display_map.clip_point(head, Bias::Right);
 7279                    let goal = SelectionGoal::HorizontalPosition(
 7280                        display_map
 7281                            .x_for_display_point(head, text_layout_details)
 7282                            .into(),
 7283                    );
 7284                    selection.collapse_to(head, goal);
 7285
 7286                    let transpose_start = display_map
 7287                        .buffer_snapshot
 7288                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7289                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7290                        let transpose_end = display_map
 7291                            .buffer_snapshot
 7292                            .clip_offset(transpose_offset + 1, Bias::Right);
 7293                        if let Some(ch) =
 7294                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7295                        {
 7296                            edits.push((transpose_start..transpose_offset, String::new()));
 7297                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7298                        }
 7299                    }
 7300                });
 7301                edits
 7302            });
 7303            this.buffer
 7304                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7305            let selections = this.selections.all::<usize>(cx);
 7306            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7307                s.select(selections);
 7308            });
 7309        });
 7310    }
 7311
 7312    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7313        self.rewrap_impl(IsVimMode::No, cx)
 7314    }
 7315
 7316    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7317        let buffer = self.buffer.read(cx).snapshot(cx);
 7318        let selections = self.selections.all::<Point>(cx);
 7319        let mut selections = selections.iter().peekable();
 7320
 7321        let mut edits = Vec::new();
 7322        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7323
 7324        while let Some(selection) = selections.next() {
 7325            let mut start_row = selection.start.row;
 7326            let mut end_row = selection.end.row;
 7327
 7328            // Skip selections that overlap with a range that has already been rewrapped.
 7329            let selection_range = start_row..end_row;
 7330            if rewrapped_row_ranges
 7331                .iter()
 7332                .any(|range| range.overlaps(&selection_range))
 7333            {
 7334                continue;
 7335            }
 7336
 7337            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7338
 7339            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7340                match language_scope.language_name().as_ref() {
 7341                    "Markdown" | "Plain Text" => {
 7342                        should_rewrap = true;
 7343                    }
 7344                    _ => {}
 7345                }
 7346            }
 7347
 7348            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7349
 7350            // Since not all lines in the selection may be at the same indent
 7351            // level, choose the indent size that is the most common between all
 7352            // of the lines.
 7353            //
 7354            // If there is a tie, we use the deepest indent.
 7355            let (indent_size, indent_end) = {
 7356                let mut indent_size_occurrences = HashMap::default();
 7357                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7358
 7359                for row in start_row..=end_row {
 7360                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7361                    rows_by_indent_size.entry(indent).or_default().push(row);
 7362                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7363                }
 7364
 7365                let indent_size = indent_size_occurrences
 7366                    .into_iter()
 7367                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7368                    .map(|(indent, _)| indent)
 7369                    .unwrap_or_default();
 7370                let row = rows_by_indent_size[&indent_size][0];
 7371                let indent_end = Point::new(row, indent_size.len);
 7372
 7373                (indent_size, indent_end)
 7374            };
 7375
 7376            let mut line_prefix = indent_size.chars().collect::<String>();
 7377
 7378            if let Some(comment_prefix) =
 7379                buffer
 7380                    .language_scope_at(selection.head())
 7381                    .and_then(|language| {
 7382                        language
 7383                            .line_comment_prefixes()
 7384                            .iter()
 7385                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7386                            .cloned()
 7387                    })
 7388            {
 7389                line_prefix.push_str(&comment_prefix);
 7390                should_rewrap = true;
 7391            }
 7392
 7393            if !should_rewrap {
 7394                continue;
 7395            }
 7396
 7397            if selection.is_empty() {
 7398                'expand_upwards: while start_row > 0 {
 7399                    let prev_row = start_row - 1;
 7400                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7401                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7402                    {
 7403                        start_row = prev_row;
 7404                    } else {
 7405                        break 'expand_upwards;
 7406                    }
 7407                }
 7408
 7409                'expand_downwards: while end_row < buffer.max_point().row {
 7410                    let next_row = end_row + 1;
 7411                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7412                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7413                    {
 7414                        end_row = next_row;
 7415                    } else {
 7416                        break 'expand_downwards;
 7417                    }
 7418                }
 7419            }
 7420
 7421            let start = Point::new(start_row, 0);
 7422            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7423            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7424            let Some(lines_without_prefixes) = selection_text
 7425                .lines()
 7426                .map(|line| {
 7427                    line.strip_prefix(&line_prefix)
 7428                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7429                        .ok_or_else(|| {
 7430                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7431                        })
 7432                })
 7433                .collect::<Result<Vec<_>, _>>()
 7434                .log_err()
 7435            else {
 7436                continue;
 7437            };
 7438
 7439            let wrap_column = buffer
 7440                .settings_at(Point::new(start_row, 0), cx)
 7441                .preferred_line_length as usize;
 7442            let wrapped_text = wrap_with_prefix(
 7443                line_prefix,
 7444                lines_without_prefixes.join(" "),
 7445                wrap_column,
 7446                tab_size,
 7447            );
 7448
 7449            // TODO: should always use char-based diff while still supporting cursor behavior that
 7450            // matches vim.
 7451            let diff = match is_vim_mode {
 7452                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7453                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7454            };
 7455            let mut offset = start.to_offset(&buffer);
 7456            let mut moved_since_edit = true;
 7457
 7458            for change in diff.iter_all_changes() {
 7459                let value = change.value();
 7460                match change.tag() {
 7461                    ChangeTag::Equal => {
 7462                        offset += value.len();
 7463                        moved_since_edit = true;
 7464                    }
 7465                    ChangeTag::Delete => {
 7466                        let start = buffer.anchor_after(offset);
 7467                        let end = buffer.anchor_before(offset + value.len());
 7468
 7469                        if moved_since_edit {
 7470                            edits.push((start..end, String::new()));
 7471                        } else {
 7472                            edits.last_mut().unwrap().0.end = end;
 7473                        }
 7474
 7475                        offset += value.len();
 7476                        moved_since_edit = false;
 7477                    }
 7478                    ChangeTag::Insert => {
 7479                        if moved_since_edit {
 7480                            let anchor = buffer.anchor_after(offset);
 7481                            edits.push((anchor..anchor, value.to_string()));
 7482                        } else {
 7483                            edits.last_mut().unwrap().1.push_str(value);
 7484                        }
 7485
 7486                        moved_since_edit = false;
 7487                    }
 7488                }
 7489            }
 7490
 7491            rewrapped_row_ranges.push(start_row..=end_row);
 7492        }
 7493
 7494        self.buffer
 7495            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7496    }
 7497
 7498    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7499        let mut text = String::new();
 7500        let buffer = self.buffer.read(cx).snapshot(cx);
 7501        let mut selections = self.selections.all::<Point>(cx);
 7502        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7503        {
 7504            let max_point = buffer.max_point();
 7505            let mut is_first = true;
 7506            for selection in &mut selections {
 7507                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7508                if is_entire_line {
 7509                    selection.start = Point::new(selection.start.row, 0);
 7510                    if !selection.is_empty() && selection.end.column == 0 {
 7511                        selection.end = cmp::min(max_point, selection.end);
 7512                    } else {
 7513                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7514                    }
 7515                    selection.goal = SelectionGoal::None;
 7516                }
 7517                if is_first {
 7518                    is_first = false;
 7519                } else {
 7520                    text += "\n";
 7521                }
 7522                let mut len = 0;
 7523                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7524                    text.push_str(chunk);
 7525                    len += chunk.len();
 7526                }
 7527                clipboard_selections.push(ClipboardSelection {
 7528                    len,
 7529                    is_entire_line,
 7530                    first_line_indent: buffer
 7531                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7532                        .len,
 7533                });
 7534            }
 7535        }
 7536
 7537        self.transact(window, cx, |this, window, cx| {
 7538            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7539                s.select(selections);
 7540            });
 7541            this.insert("", window, cx);
 7542        });
 7543        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7544    }
 7545
 7546    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7547        let item = self.cut_common(window, cx);
 7548        cx.write_to_clipboard(item);
 7549    }
 7550
 7551    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7552        self.change_selections(None, window, cx, |s| {
 7553            s.move_with(|snapshot, sel| {
 7554                if sel.is_empty() {
 7555                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7556                }
 7557            });
 7558        });
 7559        let item = self.cut_common(window, cx);
 7560        cx.set_global(KillRing(item))
 7561    }
 7562
 7563    pub fn kill_ring_yank(
 7564        &mut self,
 7565        _: &KillRingYank,
 7566        window: &mut Window,
 7567        cx: &mut Context<Self>,
 7568    ) {
 7569        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7570            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7571                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7572            } else {
 7573                return;
 7574            }
 7575        } else {
 7576            return;
 7577        };
 7578        self.do_paste(&text, metadata, false, window, cx);
 7579    }
 7580
 7581    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7582        let selections = self.selections.all::<Point>(cx);
 7583        let buffer = self.buffer.read(cx).read(cx);
 7584        let mut text = String::new();
 7585
 7586        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7587        {
 7588            let max_point = buffer.max_point();
 7589            let mut is_first = true;
 7590            for selection in selections.iter() {
 7591                let mut start = selection.start;
 7592                let mut end = selection.end;
 7593                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7594                if is_entire_line {
 7595                    start = Point::new(start.row, 0);
 7596                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7597                }
 7598                if is_first {
 7599                    is_first = false;
 7600                } else {
 7601                    text += "\n";
 7602                }
 7603                let mut len = 0;
 7604                for chunk in buffer.text_for_range(start..end) {
 7605                    text.push_str(chunk);
 7606                    len += chunk.len();
 7607                }
 7608                clipboard_selections.push(ClipboardSelection {
 7609                    len,
 7610                    is_entire_line,
 7611                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7612                });
 7613            }
 7614        }
 7615
 7616        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7617            text,
 7618            clipboard_selections,
 7619        ));
 7620    }
 7621
 7622    pub fn do_paste(
 7623        &mut self,
 7624        text: &String,
 7625        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7626        handle_entire_lines: bool,
 7627        window: &mut Window,
 7628        cx: &mut Context<Self>,
 7629    ) {
 7630        if self.read_only(cx) {
 7631            return;
 7632        }
 7633
 7634        let clipboard_text = Cow::Borrowed(text);
 7635
 7636        self.transact(window, cx, |this, window, cx| {
 7637            if let Some(mut clipboard_selections) = clipboard_selections {
 7638                let old_selections = this.selections.all::<usize>(cx);
 7639                let all_selections_were_entire_line =
 7640                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7641                let first_selection_indent_column =
 7642                    clipboard_selections.first().map(|s| s.first_line_indent);
 7643                if clipboard_selections.len() != old_selections.len() {
 7644                    clipboard_selections.drain(..);
 7645                }
 7646                let cursor_offset = this.selections.last::<usize>(cx).head();
 7647                let mut auto_indent_on_paste = true;
 7648
 7649                this.buffer.update(cx, |buffer, cx| {
 7650                    let snapshot = buffer.read(cx);
 7651                    auto_indent_on_paste =
 7652                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7653
 7654                    let mut start_offset = 0;
 7655                    let mut edits = Vec::new();
 7656                    let mut original_indent_columns = Vec::new();
 7657                    for (ix, selection) in old_selections.iter().enumerate() {
 7658                        let to_insert;
 7659                        let entire_line;
 7660                        let original_indent_column;
 7661                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7662                            let end_offset = start_offset + clipboard_selection.len;
 7663                            to_insert = &clipboard_text[start_offset..end_offset];
 7664                            entire_line = clipboard_selection.is_entire_line;
 7665                            start_offset = end_offset + 1;
 7666                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7667                        } else {
 7668                            to_insert = clipboard_text.as_str();
 7669                            entire_line = all_selections_were_entire_line;
 7670                            original_indent_column = first_selection_indent_column
 7671                        }
 7672
 7673                        // If the corresponding selection was empty when this slice of the
 7674                        // clipboard text was written, then the entire line containing the
 7675                        // selection was copied. If this selection is also currently empty,
 7676                        // then paste the line before the current line of the buffer.
 7677                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7678                            let column = selection.start.to_point(&snapshot).column as usize;
 7679                            let line_start = selection.start - column;
 7680                            line_start..line_start
 7681                        } else {
 7682                            selection.range()
 7683                        };
 7684
 7685                        edits.push((range, to_insert));
 7686                        original_indent_columns.extend(original_indent_column);
 7687                    }
 7688                    drop(snapshot);
 7689
 7690                    buffer.edit(
 7691                        edits,
 7692                        if auto_indent_on_paste {
 7693                            Some(AutoindentMode::Block {
 7694                                original_indent_columns,
 7695                            })
 7696                        } else {
 7697                            None
 7698                        },
 7699                        cx,
 7700                    );
 7701                });
 7702
 7703                let selections = this.selections.all::<usize>(cx);
 7704                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7705                    s.select(selections)
 7706                });
 7707            } else {
 7708                this.insert(&clipboard_text, window, cx);
 7709            }
 7710        });
 7711    }
 7712
 7713    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7714        if let Some(item) = cx.read_from_clipboard() {
 7715            let entries = item.entries();
 7716
 7717            match entries.first() {
 7718                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7719                // of all the pasted entries.
 7720                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7721                    .do_paste(
 7722                        clipboard_string.text(),
 7723                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7724                        true,
 7725                        window,
 7726                        cx,
 7727                    ),
 7728                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7729            }
 7730        }
 7731    }
 7732
 7733    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7734        if self.read_only(cx) {
 7735            return;
 7736        }
 7737
 7738        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7739            if let Some((selections, _)) =
 7740                self.selection_history.transaction(transaction_id).cloned()
 7741            {
 7742                self.change_selections(None, window, cx, |s| {
 7743                    s.select_anchors(selections.to_vec());
 7744                });
 7745            }
 7746            self.request_autoscroll(Autoscroll::fit(), cx);
 7747            self.unmark_text(window, cx);
 7748            self.refresh_inline_completion(true, false, window, cx);
 7749            cx.emit(EditorEvent::Edited { transaction_id });
 7750            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7751        }
 7752    }
 7753
 7754    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7755        if self.read_only(cx) {
 7756            return;
 7757        }
 7758
 7759        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7760            if let Some((_, Some(selections))) =
 7761                self.selection_history.transaction(transaction_id).cloned()
 7762            {
 7763                self.change_selections(None, window, cx, |s| {
 7764                    s.select_anchors(selections.to_vec());
 7765                });
 7766            }
 7767            self.request_autoscroll(Autoscroll::fit(), cx);
 7768            self.unmark_text(window, cx);
 7769            self.refresh_inline_completion(true, false, window, cx);
 7770            cx.emit(EditorEvent::Edited { transaction_id });
 7771        }
 7772    }
 7773
 7774    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7775        self.buffer
 7776            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7777    }
 7778
 7779    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7780        self.buffer
 7781            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7782    }
 7783
 7784    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7785        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7786            let line_mode = s.line_mode;
 7787            s.move_with(|map, selection| {
 7788                let cursor = if selection.is_empty() && !line_mode {
 7789                    movement::left(map, selection.start)
 7790                } else {
 7791                    selection.start
 7792                };
 7793                selection.collapse_to(cursor, SelectionGoal::None);
 7794            });
 7795        })
 7796    }
 7797
 7798    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7799        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7800            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7801        })
 7802    }
 7803
 7804    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7806            let line_mode = s.line_mode;
 7807            s.move_with(|map, selection| {
 7808                let cursor = if selection.is_empty() && !line_mode {
 7809                    movement::right(map, selection.end)
 7810                } else {
 7811                    selection.end
 7812                };
 7813                selection.collapse_to(cursor, SelectionGoal::None)
 7814            });
 7815        })
 7816    }
 7817
 7818    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7819        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7820            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7821        })
 7822    }
 7823
 7824    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7825        if self.take_rename(true, window, cx).is_some() {
 7826            return;
 7827        }
 7828
 7829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7830            cx.propagate();
 7831            return;
 7832        }
 7833
 7834        let text_layout_details = &self.text_layout_details(window);
 7835        let selection_count = self.selections.count();
 7836        let first_selection = self.selections.first_anchor();
 7837
 7838        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7839            let line_mode = s.line_mode;
 7840            s.move_with(|map, selection| {
 7841                if !selection.is_empty() && !line_mode {
 7842                    selection.goal = SelectionGoal::None;
 7843                }
 7844                let (cursor, goal) = movement::up(
 7845                    map,
 7846                    selection.start,
 7847                    selection.goal,
 7848                    false,
 7849                    text_layout_details,
 7850                );
 7851                selection.collapse_to(cursor, goal);
 7852            });
 7853        });
 7854
 7855        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7856        {
 7857            cx.propagate();
 7858        }
 7859    }
 7860
 7861    pub fn move_up_by_lines(
 7862        &mut self,
 7863        action: &MoveUpByLines,
 7864        window: &mut Window,
 7865        cx: &mut Context<Self>,
 7866    ) {
 7867        if self.take_rename(true, window, cx).is_some() {
 7868            return;
 7869        }
 7870
 7871        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7872            cx.propagate();
 7873            return;
 7874        }
 7875
 7876        let text_layout_details = &self.text_layout_details(window);
 7877
 7878        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7879            let line_mode = s.line_mode;
 7880            s.move_with(|map, selection| {
 7881                if !selection.is_empty() && !line_mode {
 7882                    selection.goal = SelectionGoal::None;
 7883                }
 7884                let (cursor, goal) = movement::up_by_rows(
 7885                    map,
 7886                    selection.start,
 7887                    action.lines,
 7888                    selection.goal,
 7889                    false,
 7890                    text_layout_details,
 7891                );
 7892                selection.collapse_to(cursor, goal);
 7893            });
 7894        })
 7895    }
 7896
 7897    pub fn move_down_by_lines(
 7898        &mut self,
 7899        action: &MoveDownByLines,
 7900        window: &mut Window,
 7901        cx: &mut Context<Self>,
 7902    ) {
 7903        if self.take_rename(true, window, cx).is_some() {
 7904            return;
 7905        }
 7906
 7907        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7908            cx.propagate();
 7909            return;
 7910        }
 7911
 7912        let text_layout_details = &self.text_layout_details(window);
 7913
 7914        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7915            let line_mode = s.line_mode;
 7916            s.move_with(|map, selection| {
 7917                if !selection.is_empty() && !line_mode {
 7918                    selection.goal = SelectionGoal::None;
 7919                }
 7920                let (cursor, goal) = movement::down_by_rows(
 7921                    map,
 7922                    selection.start,
 7923                    action.lines,
 7924                    selection.goal,
 7925                    false,
 7926                    text_layout_details,
 7927                );
 7928                selection.collapse_to(cursor, goal);
 7929            });
 7930        })
 7931    }
 7932
 7933    pub fn select_down_by_lines(
 7934        &mut self,
 7935        action: &SelectDownByLines,
 7936        window: &mut Window,
 7937        cx: &mut Context<Self>,
 7938    ) {
 7939        let text_layout_details = &self.text_layout_details(window);
 7940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7941            s.move_heads_with(|map, head, goal| {
 7942                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7943            })
 7944        })
 7945    }
 7946
 7947    pub fn select_up_by_lines(
 7948        &mut self,
 7949        action: &SelectUpByLines,
 7950        window: &mut Window,
 7951        cx: &mut Context<Self>,
 7952    ) {
 7953        let text_layout_details = &self.text_layout_details(window);
 7954        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7955            s.move_heads_with(|map, head, goal| {
 7956                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7957            })
 7958        })
 7959    }
 7960
 7961    pub fn select_page_up(
 7962        &mut self,
 7963        _: &SelectPageUp,
 7964        window: &mut Window,
 7965        cx: &mut Context<Self>,
 7966    ) {
 7967        let Some(row_count) = self.visible_row_count() else {
 7968            return;
 7969        };
 7970
 7971        let text_layout_details = &self.text_layout_details(window);
 7972
 7973        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7974            s.move_heads_with(|map, head, goal| {
 7975                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7976            })
 7977        })
 7978    }
 7979
 7980    pub fn move_page_up(
 7981        &mut self,
 7982        action: &MovePageUp,
 7983        window: &mut Window,
 7984        cx: &mut Context<Self>,
 7985    ) {
 7986        if self.take_rename(true, window, cx).is_some() {
 7987            return;
 7988        }
 7989
 7990        if self
 7991            .context_menu
 7992            .borrow_mut()
 7993            .as_mut()
 7994            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7995            .unwrap_or(false)
 7996        {
 7997            return;
 7998        }
 7999
 8000        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8001            cx.propagate();
 8002            return;
 8003        }
 8004
 8005        let Some(row_count) = self.visible_row_count() else {
 8006            return;
 8007        };
 8008
 8009        let autoscroll = if action.center_cursor {
 8010            Autoscroll::center()
 8011        } else {
 8012            Autoscroll::fit()
 8013        };
 8014
 8015        let text_layout_details = &self.text_layout_details(window);
 8016
 8017        self.change_selections(Some(autoscroll), window, cx, |s| {
 8018            let line_mode = s.line_mode;
 8019            s.move_with(|map, selection| {
 8020                if !selection.is_empty() && !line_mode {
 8021                    selection.goal = SelectionGoal::None;
 8022                }
 8023                let (cursor, goal) = movement::up_by_rows(
 8024                    map,
 8025                    selection.end,
 8026                    row_count,
 8027                    selection.goal,
 8028                    false,
 8029                    text_layout_details,
 8030                );
 8031                selection.collapse_to(cursor, goal);
 8032            });
 8033        });
 8034    }
 8035
 8036    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8037        let text_layout_details = &self.text_layout_details(window);
 8038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8039            s.move_heads_with(|map, head, goal| {
 8040                movement::up(map, head, goal, false, text_layout_details)
 8041            })
 8042        })
 8043    }
 8044
 8045    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8046        self.take_rename(true, window, cx);
 8047
 8048        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8049            cx.propagate();
 8050            return;
 8051        }
 8052
 8053        let text_layout_details = &self.text_layout_details(window);
 8054        let selection_count = self.selections.count();
 8055        let first_selection = self.selections.first_anchor();
 8056
 8057        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8058            let line_mode = s.line_mode;
 8059            s.move_with(|map, selection| {
 8060                if !selection.is_empty() && !line_mode {
 8061                    selection.goal = SelectionGoal::None;
 8062                }
 8063                let (cursor, goal) = movement::down(
 8064                    map,
 8065                    selection.end,
 8066                    selection.goal,
 8067                    false,
 8068                    text_layout_details,
 8069                );
 8070                selection.collapse_to(cursor, goal);
 8071            });
 8072        });
 8073
 8074        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8075        {
 8076            cx.propagate();
 8077        }
 8078    }
 8079
 8080    pub fn select_page_down(
 8081        &mut self,
 8082        _: &SelectPageDown,
 8083        window: &mut Window,
 8084        cx: &mut Context<Self>,
 8085    ) {
 8086        let Some(row_count) = self.visible_row_count() else {
 8087            return;
 8088        };
 8089
 8090        let text_layout_details = &self.text_layout_details(window);
 8091
 8092        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8093            s.move_heads_with(|map, head, goal| {
 8094                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8095            })
 8096        })
 8097    }
 8098
 8099    pub fn move_page_down(
 8100        &mut self,
 8101        action: &MovePageDown,
 8102        window: &mut Window,
 8103        cx: &mut Context<Self>,
 8104    ) {
 8105        if self.take_rename(true, window, cx).is_some() {
 8106            return;
 8107        }
 8108
 8109        if self
 8110            .context_menu
 8111            .borrow_mut()
 8112            .as_mut()
 8113            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8114            .unwrap_or(false)
 8115        {
 8116            return;
 8117        }
 8118
 8119        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8120            cx.propagate();
 8121            return;
 8122        }
 8123
 8124        let Some(row_count) = self.visible_row_count() else {
 8125            return;
 8126        };
 8127
 8128        let autoscroll = if action.center_cursor {
 8129            Autoscroll::center()
 8130        } else {
 8131            Autoscroll::fit()
 8132        };
 8133
 8134        let text_layout_details = &self.text_layout_details(window);
 8135        self.change_selections(Some(autoscroll), window, cx, |s| {
 8136            let line_mode = s.line_mode;
 8137            s.move_with(|map, selection| {
 8138                if !selection.is_empty() && !line_mode {
 8139                    selection.goal = SelectionGoal::None;
 8140                }
 8141                let (cursor, goal) = movement::down_by_rows(
 8142                    map,
 8143                    selection.end,
 8144                    row_count,
 8145                    selection.goal,
 8146                    false,
 8147                    text_layout_details,
 8148                );
 8149                selection.collapse_to(cursor, goal);
 8150            });
 8151        });
 8152    }
 8153
 8154    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8155        let text_layout_details = &self.text_layout_details(window);
 8156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8157            s.move_heads_with(|map, head, goal| {
 8158                movement::down(map, head, goal, false, text_layout_details)
 8159            })
 8160        });
 8161    }
 8162
 8163    pub fn context_menu_first(
 8164        &mut self,
 8165        _: &ContextMenuFirst,
 8166        _window: &mut Window,
 8167        cx: &mut Context<Self>,
 8168    ) {
 8169        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8170            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8171        }
 8172    }
 8173
 8174    pub fn context_menu_prev(
 8175        &mut self,
 8176        _: &ContextMenuPrev,
 8177        _window: &mut Window,
 8178        cx: &mut Context<Self>,
 8179    ) {
 8180        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8181            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8182        }
 8183    }
 8184
 8185    pub fn context_menu_next(
 8186        &mut self,
 8187        _: &ContextMenuNext,
 8188        _window: &mut Window,
 8189        cx: &mut Context<Self>,
 8190    ) {
 8191        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8192            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8193        }
 8194    }
 8195
 8196    pub fn context_menu_last(
 8197        &mut self,
 8198        _: &ContextMenuLast,
 8199        _window: &mut Window,
 8200        cx: &mut Context<Self>,
 8201    ) {
 8202        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8203            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8204        }
 8205    }
 8206
 8207    pub fn move_to_previous_word_start(
 8208        &mut self,
 8209        _: &MoveToPreviousWordStart,
 8210        window: &mut Window,
 8211        cx: &mut Context<Self>,
 8212    ) {
 8213        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8214            s.move_cursors_with(|map, head, _| {
 8215                (
 8216                    movement::previous_word_start(map, head),
 8217                    SelectionGoal::None,
 8218                )
 8219            });
 8220        })
 8221    }
 8222
 8223    pub fn move_to_previous_subword_start(
 8224        &mut self,
 8225        _: &MoveToPreviousSubwordStart,
 8226        window: &mut Window,
 8227        cx: &mut Context<Self>,
 8228    ) {
 8229        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8230            s.move_cursors_with(|map, head, _| {
 8231                (
 8232                    movement::previous_subword_start(map, head),
 8233                    SelectionGoal::None,
 8234                )
 8235            });
 8236        })
 8237    }
 8238
 8239    pub fn select_to_previous_word_start(
 8240        &mut self,
 8241        _: &SelectToPreviousWordStart,
 8242        window: &mut Window,
 8243        cx: &mut Context<Self>,
 8244    ) {
 8245        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8246            s.move_heads_with(|map, head, _| {
 8247                (
 8248                    movement::previous_word_start(map, head),
 8249                    SelectionGoal::None,
 8250                )
 8251            });
 8252        })
 8253    }
 8254
 8255    pub fn select_to_previous_subword_start(
 8256        &mut self,
 8257        _: &SelectToPreviousSubwordStart,
 8258        window: &mut Window,
 8259        cx: &mut Context<Self>,
 8260    ) {
 8261        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8262            s.move_heads_with(|map, head, _| {
 8263                (
 8264                    movement::previous_subword_start(map, head),
 8265                    SelectionGoal::None,
 8266                )
 8267            });
 8268        })
 8269    }
 8270
 8271    pub fn delete_to_previous_word_start(
 8272        &mut self,
 8273        action: &DeleteToPreviousWordStart,
 8274        window: &mut Window,
 8275        cx: &mut Context<Self>,
 8276    ) {
 8277        self.transact(window, cx, |this, window, cx| {
 8278            this.select_autoclose_pair(window, cx);
 8279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8280                let line_mode = s.line_mode;
 8281                s.move_with(|map, selection| {
 8282                    if selection.is_empty() && !line_mode {
 8283                        let cursor = if action.ignore_newlines {
 8284                            movement::previous_word_start(map, selection.head())
 8285                        } else {
 8286                            movement::previous_word_start_or_newline(map, selection.head())
 8287                        };
 8288                        selection.set_head(cursor, SelectionGoal::None);
 8289                    }
 8290                });
 8291            });
 8292            this.insert("", window, cx);
 8293        });
 8294    }
 8295
 8296    pub fn delete_to_previous_subword_start(
 8297        &mut self,
 8298        _: &DeleteToPreviousSubwordStart,
 8299        window: &mut Window,
 8300        cx: &mut Context<Self>,
 8301    ) {
 8302        self.transact(window, cx, |this, window, cx| {
 8303            this.select_autoclose_pair(window, cx);
 8304            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8305                let line_mode = s.line_mode;
 8306                s.move_with(|map, selection| {
 8307                    if selection.is_empty() && !line_mode {
 8308                        let cursor = movement::previous_subword_start(map, selection.head());
 8309                        selection.set_head(cursor, SelectionGoal::None);
 8310                    }
 8311                });
 8312            });
 8313            this.insert("", window, cx);
 8314        });
 8315    }
 8316
 8317    pub fn move_to_next_word_end(
 8318        &mut self,
 8319        _: &MoveToNextWordEnd,
 8320        window: &mut Window,
 8321        cx: &mut Context<Self>,
 8322    ) {
 8323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8324            s.move_cursors_with(|map, head, _| {
 8325                (movement::next_word_end(map, head), SelectionGoal::None)
 8326            });
 8327        })
 8328    }
 8329
 8330    pub fn move_to_next_subword_end(
 8331        &mut self,
 8332        _: &MoveToNextSubwordEnd,
 8333        window: &mut Window,
 8334        cx: &mut Context<Self>,
 8335    ) {
 8336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8337            s.move_cursors_with(|map, head, _| {
 8338                (movement::next_subword_end(map, head), SelectionGoal::None)
 8339            });
 8340        })
 8341    }
 8342
 8343    pub fn select_to_next_word_end(
 8344        &mut self,
 8345        _: &SelectToNextWordEnd,
 8346        window: &mut Window,
 8347        cx: &mut Context<Self>,
 8348    ) {
 8349        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8350            s.move_heads_with(|map, head, _| {
 8351                (movement::next_word_end(map, head), SelectionGoal::None)
 8352            });
 8353        })
 8354    }
 8355
 8356    pub fn select_to_next_subword_end(
 8357        &mut self,
 8358        _: &SelectToNextSubwordEnd,
 8359        window: &mut Window,
 8360        cx: &mut Context<Self>,
 8361    ) {
 8362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8363            s.move_heads_with(|map, head, _| {
 8364                (movement::next_subword_end(map, head), SelectionGoal::None)
 8365            });
 8366        })
 8367    }
 8368
 8369    pub fn delete_to_next_word_end(
 8370        &mut self,
 8371        action: &DeleteToNextWordEnd,
 8372        window: &mut Window,
 8373        cx: &mut Context<Self>,
 8374    ) {
 8375        self.transact(window, cx, |this, window, cx| {
 8376            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8377                let line_mode = s.line_mode;
 8378                s.move_with(|map, selection| {
 8379                    if selection.is_empty() && !line_mode {
 8380                        let cursor = if action.ignore_newlines {
 8381                            movement::next_word_end(map, selection.head())
 8382                        } else {
 8383                            movement::next_word_end_or_newline(map, selection.head())
 8384                        };
 8385                        selection.set_head(cursor, SelectionGoal::None);
 8386                    }
 8387                });
 8388            });
 8389            this.insert("", window, cx);
 8390        });
 8391    }
 8392
 8393    pub fn delete_to_next_subword_end(
 8394        &mut self,
 8395        _: &DeleteToNextSubwordEnd,
 8396        window: &mut Window,
 8397        cx: &mut Context<Self>,
 8398    ) {
 8399        self.transact(window, cx, |this, window, cx| {
 8400            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8401                s.move_with(|map, selection| {
 8402                    if selection.is_empty() {
 8403                        let cursor = movement::next_subword_end(map, selection.head());
 8404                        selection.set_head(cursor, SelectionGoal::None);
 8405                    }
 8406                });
 8407            });
 8408            this.insert("", window, cx);
 8409        });
 8410    }
 8411
 8412    pub fn move_to_beginning_of_line(
 8413        &mut self,
 8414        action: &MoveToBeginningOfLine,
 8415        window: &mut Window,
 8416        cx: &mut Context<Self>,
 8417    ) {
 8418        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8419            s.move_cursors_with(|map, head, _| {
 8420                (
 8421                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8422                    SelectionGoal::None,
 8423                )
 8424            });
 8425        })
 8426    }
 8427
 8428    pub fn select_to_beginning_of_line(
 8429        &mut self,
 8430        action: &SelectToBeginningOfLine,
 8431        window: &mut Window,
 8432        cx: &mut Context<Self>,
 8433    ) {
 8434        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8435            s.move_heads_with(|map, head, _| {
 8436                (
 8437                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8438                    SelectionGoal::None,
 8439                )
 8440            });
 8441        });
 8442    }
 8443
 8444    pub fn delete_to_beginning_of_line(
 8445        &mut self,
 8446        _: &DeleteToBeginningOfLine,
 8447        window: &mut Window,
 8448        cx: &mut Context<Self>,
 8449    ) {
 8450        self.transact(window, cx, |this, window, cx| {
 8451            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8452                s.move_with(|_, selection| {
 8453                    selection.reversed = true;
 8454                });
 8455            });
 8456
 8457            this.select_to_beginning_of_line(
 8458                &SelectToBeginningOfLine {
 8459                    stop_at_soft_wraps: false,
 8460                },
 8461                window,
 8462                cx,
 8463            );
 8464            this.backspace(&Backspace, window, cx);
 8465        });
 8466    }
 8467
 8468    pub fn move_to_end_of_line(
 8469        &mut self,
 8470        action: &MoveToEndOfLine,
 8471        window: &mut Window,
 8472        cx: &mut Context<Self>,
 8473    ) {
 8474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8475            s.move_cursors_with(|map, head, _| {
 8476                (
 8477                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8478                    SelectionGoal::None,
 8479                )
 8480            });
 8481        })
 8482    }
 8483
 8484    pub fn select_to_end_of_line(
 8485        &mut self,
 8486        action: &SelectToEndOfLine,
 8487        window: &mut Window,
 8488        cx: &mut Context<Self>,
 8489    ) {
 8490        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8491            s.move_heads_with(|map, head, _| {
 8492                (
 8493                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8494                    SelectionGoal::None,
 8495                )
 8496            });
 8497        })
 8498    }
 8499
 8500    pub fn delete_to_end_of_line(
 8501        &mut self,
 8502        _: &DeleteToEndOfLine,
 8503        window: &mut Window,
 8504        cx: &mut Context<Self>,
 8505    ) {
 8506        self.transact(window, cx, |this, window, cx| {
 8507            this.select_to_end_of_line(
 8508                &SelectToEndOfLine {
 8509                    stop_at_soft_wraps: false,
 8510                },
 8511                window,
 8512                cx,
 8513            );
 8514            this.delete(&Delete, window, cx);
 8515        });
 8516    }
 8517
 8518    pub fn cut_to_end_of_line(
 8519        &mut self,
 8520        _: &CutToEndOfLine,
 8521        window: &mut Window,
 8522        cx: &mut Context<Self>,
 8523    ) {
 8524        self.transact(window, cx, |this, window, cx| {
 8525            this.select_to_end_of_line(
 8526                &SelectToEndOfLine {
 8527                    stop_at_soft_wraps: false,
 8528                },
 8529                window,
 8530                cx,
 8531            );
 8532            this.cut(&Cut, window, cx);
 8533        });
 8534    }
 8535
 8536    pub fn move_to_start_of_paragraph(
 8537        &mut self,
 8538        _: &MoveToStartOfParagraph,
 8539        window: &mut Window,
 8540        cx: &mut Context<Self>,
 8541    ) {
 8542        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8543            cx.propagate();
 8544            return;
 8545        }
 8546
 8547        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8548            s.move_with(|map, selection| {
 8549                selection.collapse_to(
 8550                    movement::start_of_paragraph(map, selection.head(), 1),
 8551                    SelectionGoal::None,
 8552                )
 8553            });
 8554        })
 8555    }
 8556
 8557    pub fn move_to_end_of_paragraph(
 8558        &mut self,
 8559        _: &MoveToEndOfParagraph,
 8560        window: &mut Window,
 8561        cx: &mut Context<Self>,
 8562    ) {
 8563        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8564            cx.propagate();
 8565            return;
 8566        }
 8567
 8568        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8569            s.move_with(|map, selection| {
 8570                selection.collapse_to(
 8571                    movement::end_of_paragraph(map, selection.head(), 1),
 8572                    SelectionGoal::None,
 8573                )
 8574            });
 8575        })
 8576    }
 8577
 8578    pub fn select_to_start_of_paragraph(
 8579        &mut self,
 8580        _: &SelectToStartOfParagraph,
 8581        window: &mut Window,
 8582        cx: &mut Context<Self>,
 8583    ) {
 8584        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8585            cx.propagate();
 8586            return;
 8587        }
 8588
 8589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8590            s.move_heads_with(|map, head, _| {
 8591                (
 8592                    movement::start_of_paragraph(map, head, 1),
 8593                    SelectionGoal::None,
 8594                )
 8595            });
 8596        })
 8597    }
 8598
 8599    pub fn select_to_end_of_paragraph(
 8600        &mut self,
 8601        _: &SelectToEndOfParagraph,
 8602        window: &mut Window,
 8603        cx: &mut Context<Self>,
 8604    ) {
 8605        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8606            cx.propagate();
 8607            return;
 8608        }
 8609
 8610        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8611            s.move_heads_with(|map, head, _| {
 8612                (
 8613                    movement::end_of_paragraph(map, head, 1),
 8614                    SelectionGoal::None,
 8615                )
 8616            });
 8617        })
 8618    }
 8619
 8620    pub fn move_to_beginning(
 8621        &mut self,
 8622        _: &MoveToBeginning,
 8623        window: &mut Window,
 8624        cx: &mut Context<Self>,
 8625    ) {
 8626        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8627            cx.propagate();
 8628            return;
 8629        }
 8630
 8631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632            s.select_ranges(vec![0..0]);
 8633        });
 8634    }
 8635
 8636    pub fn select_to_beginning(
 8637        &mut self,
 8638        _: &SelectToBeginning,
 8639        window: &mut Window,
 8640        cx: &mut Context<Self>,
 8641    ) {
 8642        let mut selection = self.selections.last::<Point>(cx);
 8643        selection.set_head(Point::zero(), SelectionGoal::None);
 8644
 8645        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8646            s.select(vec![selection]);
 8647        });
 8648    }
 8649
 8650    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8651        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8652            cx.propagate();
 8653            return;
 8654        }
 8655
 8656        let cursor = self.buffer.read(cx).read(cx).len();
 8657        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8658            s.select_ranges(vec![cursor..cursor])
 8659        });
 8660    }
 8661
 8662    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8663        self.nav_history = nav_history;
 8664    }
 8665
 8666    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8667        self.nav_history.as_ref()
 8668    }
 8669
 8670    fn push_to_nav_history(
 8671        &mut self,
 8672        cursor_anchor: Anchor,
 8673        new_position: Option<Point>,
 8674        cx: &mut Context<Self>,
 8675    ) {
 8676        if let Some(nav_history) = self.nav_history.as_mut() {
 8677            let buffer = self.buffer.read(cx).read(cx);
 8678            let cursor_position = cursor_anchor.to_point(&buffer);
 8679            let scroll_state = self.scroll_manager.anchor();
 8680            let scroll_top_row = scroll_state.top_row(&buffer);
 8681            drop(buffer);
 8682
 8683            if let Some(new_position) = new_position {
 8684                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8685                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8686                    return;
 8687                }
 8688            }
 8689
 8690            nav_history.push(
 8691                Some(NavigationData {
 8692                    cursor_anchor,
 8693                    cursor_position,
 8694                    scroll_anchor: scroll_state,
 8695                    scroll_top_row,
 8696                }),
 8697                cx,
 8698            );
 8699        }
 8700    }
 8701
 8702    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8703        let buffer = self.buffer.read(cx).snapshot(cx);
 8704        let mut selection = self.selections.first::<usize>(cx);
 8705        selection.set_head(buffer.len(), SelectionGoal::None);
 8706        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8707            s.select(vec![selection]);
 8708        });
 8709    }
 8710
 8711    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8712        let end = self.buffer.read(cx).read(cx).len();
 8713        self.change_selections(None, window, cx, |s| {
 8714            s.select_ranges(vec![0..end]);
 8715        });
 8716    }
 8717
 8718    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8719        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8720        let mut selections = self.selections.all::<Point>(cx);
 8721        let max_point = display_map.buffer_snapshot.max_point();
 8722        for selection in &mut selections {
 8723            let rows = selection.spanned_rows(true, &display_map);
 8724            selection.start = Point::new(rows.start.0, 0);
 8725            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8726            selection.reversed = false;
 8727        }
 8728        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8729            s.select(selections);
 8730        });
 8731    }
 8732
 8733    pub fn split_selection_into_lines(
 8734        &mut self,
 8735        _: &SplitSelectionIntoLines,
 8736        window: &mut Window,
 8737        cx: &mut Context<Self>,
 8738    ) {
 8739        let mut to_unfold = Vec::new();
 8740        let mut new_selection_ranges = Vec::new();
 8741        {
 8742            let selections = self.selections.all::<Point>(cx);
 8743            let buffer = self.buffer.read(cx).read(cx);
 8744            for selection in selections {
 8745                for row in selection.start.row..selection.end.row {
 8746                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8747                    new_selection_ranges.push(cursor..cursor);
 8748                }
 8749                new_selection_ranges.push(selection.end..selection.end);
 8750                to_unfold.push(selection.start..selection.end);
 8751            }
 8752        }
 8753        self.unfold_ranges(&to_unfold, true, true, cx);
 8754        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8755            s.select_ranges(new_selection_ranges);
 8756        });
 8757    }
 8758
 8759    pub fn add_selection_above(
 8760        &mut self,
 8761        _: &AddSelectionAbove,
 8762        window: &mut Window,
 8763        cx: &mut Context<Self>,
 8764    ) {
 8765        self.add_selection(true, window, cx);
 8766    }
 8767
 8768    pub fn add_selection_below(
 8769        &mut self,
 8770        _: &AddSelectionBelow,
 8771        window: &mut Window,
 8772        cx: &mut Context<Self>,
 8773    ) {
 8774        self.add_selection(false, window, cx);
 8775    }
 8776
 8777    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8778        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8779        let mut selections = self.selections.all::<Point>(cx);
 8780        let text_layout_details = self.text_layout_details(window);
 8781        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8782            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8783            let range = oldest_selection.display_range(&display_map).sorted();
 8784
 8785            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8786            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8787            let positions = start_x.min(end_x)..start_x.max(end_x);
 8788
 8789            selections.clear();
 8790            let mut stack = Vec::new();
 8791            for row in range.start.row().0..=range.end.row().0 {
 8792                if let Some(selection) = self.selections.build_columnar_selection(
 8793                    &display_map,
 8794                    DisplayRow(row),
 8795                    &positions,
 8796                    oldest_selection.reversed,
 8797                    &text_layout_details,
 8798                ) {
 8799                    stack.push(selection.id);
 8800                    selections.push(selection);
 8801                }
 8802            }
 8803
 8804            if above {
 8805                stack.reverse();
 8806            }
 8807
 8808            AddSelectionsState { above, stack }
 8809        });
 8810
 8811        let last_added_selection = *state.stack.last().unwrap();
 8812        let mut new_selections = Vec::new();
 8813        if above == state.above {
 8814            let end_row = if above {
 8815                DisplayRow(0)
 8816            } else {
 8817                display_map.max_point().row()
 8818            };
 8819
 8820            'outer: for selection in selections {
 8821                if selection.id == last_added_selection {
 8822                    let range = selection.display_range(&display_map).sorted();
 8823                    debug_assert_eq!(range.start.row(), range.end.row());
 8824                    let mut row = range.start.row();
 8825                    let positions =
 8826                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8827                            px(start)..px(end)
 8828                        } else {
 8829                            let start_x =
 8830                                display_map.x_for_display_point(range.start, &text_layout_details);
 8831                            let end_x =
 8832                                display_map.x_for_display_point(range.end, &text_layout_details);
 8833                            start_x.min(end_x)..start_x.max(end_x)
 8834                        };
 8835
 8836                    while row != end_row {
 8837                        if above {
 8838                            row.0 -= 1;
 8839                        } else {
 8840                            row.0 += 1;
 8841                        }
 8842
 8843                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8844                            &display_map,
 8845                            row,
 8846                            &positions,
 8847                            selection.reversed,
 8848                            &text_layout_details,
 8849                        ) {
 8850                            state.stack.push(new_selection.id);
 8851                            if above {
 8852                                new_selections.push(new_selection);
 8853                                new_selections.push(selection);
 8854                            } else {
 8855                                new_selections.push(selection);
 8856                                new_selections.push(new_selection);
 8857                            }
 8858
 8859                            continue 'outer;
 8860                        }
 8861                    }
 8862                }
 8863
 8864                new_selections.push(selection);
 8865            }
 8866        } else {
 8867            new_selections = selections;
 8868            new_selections.retain(|s| s.id != last_added_selection);
 8869            state.stack.pop();
 8870        }
 8871
 8872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8873            s.select(new_selections);
 8874        });
 8875        if state.stack.len() > 1 {
 8876            self.add_selections_state = Some(state);
 8877        }
 8878    }
 8879
 8880    pub fn select_next_match_internal(
 8881        &mut self,
 8882        display_map: &DisplaySnapshot,
 8883        replace_newest: bool,
 8884        autoscroll: Option<Autoscroll>,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) -> Result<()> {
 8888        fn select_next_match_ranges(
 8889            this: &mut Editor,
 8890            range: Range<usize>,
 8891            replace_newest: bool,
 8892            auto_scroll: Option<Autoscroll>,
 8893            window: &mut Window,
 8894            cx: &mut Context<Editor>,
 8895        ) {
 8896            this.unfold_ranges(&[range.clone()], false, true, cx);
 8897            this.change_selections(auto_scroll, window, cx, |s| {
 8898                if replace_newest {
 8899                    s.delete(s.newest_anchor().id);
 8900                }
 8901                s.insert_range(range.clone());
 8902            });
 8903        }
 8904
 8905        let buffer = &display_map.buffer_snapshot;
 8906        let mut selections = self.selections.all::<usize>(cx);
 8907        if let Some(mut select_next_state) = self.select_next_state.take() {
 8908            let query = &select_next_state.query;
 8909            if !select_next_state.done {
 8910                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8911                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8912                let mut next_selected_range = None;
 8913
 8914                let bytes_after_last_selection =
 8915                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8916                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8917                let query_matches = query
 8918                    .stream_find_iter(bytes_after_last_selection)
 8919                    .map(|result| (last_selection.end, result))
 8920                    .chain(
 8921                        query
 8922                            .stream_find_iter(bytes_before_first_selection)
 8923                            .map(|result| (0, result)),
 8924                    );
 8925
 8926                for (start_offset, query_match) in query_matches {
 8927                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8928                    let offset_range =
 8929                        start_offset + query_match.start()..start_offset + query_match.end();
 8930                    let display_range = offset_range.start.to_display_point(display_map)
 8931                        ..offset_range.end.to_display_point(display_map);
 8932
 8933                    if !select_next_state.wordwise
 8934                        || (!movement::is_inside_word(display_map, display_range.start)
 8935                            && !movement::is_inside_word(display_map, display_range.end))
 8936                    {
 8937                        // TODO: This is n^2, because we might check all the selections
 8938                        if !selections
 8939                            .iter()
 8940                            .any(|selection| selection.range().overlaps(&offset_range))
 8941                        {
 8942                            next_selected_range = Some(offset_range);
 8943                            break;
 8944                        }
 8945                    }
 8946                }
 8947
 8948                if let Some(next_selected_range) = next_selected_range {
 8949                    select_next_match_ranges(
 8950                        self,
 8951                        next_selected_range,
 8952                        replace_newest,
 8953                        autoscroll,
 8954                        window,
 8955                        cx,
 8956                    );
 8957                } else {
 8958                    select_next_state.done = true;
 8959                }
 8960            }
 8961
 8962            self.select_next_state = Some(select_next_state);
 8963        } else {
 8964            let mut only_carets = true;
 8965            let mut same_text_selected = true;
 8966            let mut selected_text = None;
 8967
 8968            let mut selections_iter = selections.iter().peekable();
 8969            while let Some(selection) = selections_iter.next() {
 8970                if selection.start != selection.end {
 8971                    only_carets = false;
 8972                }
 8973
 8974                if same_text_selected {
 8975                    if selected_text.is_none() {
 8976                        selected_text =
 8977                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8978                    }
 8979
 8980                    if let Some(next_selection) = selections_iter.peek() {
 8981                        if next_selection.range().len() == selection.range().len() {
 8982                            let next_selected_text = buffer
 8983                                .text_for_range(next_selection.range())
 8984                                .collect::<String>();
 8985                            if Some(next_selected_text) != selected_text {
 8986                                same_text_selected = false;
 8987                                selected_text = None;
 8988                            }
 8989                        } else {
 8990                            same_text_selected = false;
 8991                            selected_text = None;
 8992                        }
 8993                    }
 8994                }
 8995            }
 8996
 8997            if only_carets {
 8998                for selection in &mut selections {
 8999                    let word_range = movement::surrounding_word(
 9000                        display_map,
 9001                        selection.start.to_display_point(display_map),
 9002                    );
 9003                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9004                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9005                    selection.goal = SelectionGoal::None;
 9006                    selection.reversed = false;
 9007                    select_next_match_ranges(
 9008                        self,
 9009                        selection.start..selection.end,
 9010                        replace_newest,
 9011                        autoscroll,
 9012                        window,
 9013                        cx,
 9014                    );
 9015                }
 9016
 9017                if selections.len() == 1 {
 9018                    let selection = selections
 9019                        .last()
 9020                        .expect("ensured that there's only one selection");
 9021                    let query = buffer
 9022                        .text_for_range(selection.start..selection.end)
 9023                        .collect::<String>();
 9024                    let is_empty = query.is_empty();
 9025                    let select_state = SelectNextState {
 9026                        query: AhoCorasick::new(&[query])?,
 9027                        wordwise: true,
 9028                        done: is_empty,
 9029                    };
 9030                    self.select_next_state = Some(select_state);
 9031                } else {
 9032                    self.select_next_state = None;
 9033                }
 9034            } else if let Some(selected_text) = selected_text {
 9035                self.select_next_state = Some(SelectNextState {
 9036                    query: AhoCorasick::new(&[selected_text])?,
 9037                    wordwise: false,
 9038                    done: false,
 9039                });
 9040                self.select_next_match_internal(
 9041                    display_map,
 9042                    replace_newest,
 9043                    autoscroll,
 9044                    window,
 9045                    cx,
 9046                )?;
 9047            }
 9048        }
 9049        Ok(())
 9050    }
 9051
 9052    pub fn select_all_matches(
 9053        &mut self,
 9054        _action: &SelectAllMatches,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) -> Result<()> {
 9058        self.push_to_selection_history();
 9059        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9060
 9061        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9062        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9063            return Ok(());
 9064        };
 9065        if select_next_state.done {
 9066            return Ok(());
 9067        }
 9068
 9069        let mut new_selections = self.selections.all::<usize>(cx);
 9070
 9071        let buffer = &display_map.buffer_snapshot;
 9072        let query_matches = select_next_state
 9073            .query
 9074            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9075
 9076        for query_match in query_matches {
 9077            let query_match = query_match.unwrap(); // can only fail due to I/O
 9078            let offset_range = query_match.start()..query_match.end();
 9079            let display_range = offset_range.start.to_display_point(&display_map)
 9080                ..offset_range.end.to_display_point(&display_map);
 9081
 9082            if !select_next_state.wordwise
 9083                || (!movement::is_inside_word(&display_map, display_range.start)
 9084                    && !movement::is_inside_word(&display_map, display_range.end))
 9085            {
 9086                self.selections.change_with(cx, |selections| {
 9087                    new_selections.push(Selection {
 9088                        id: selections.new_selection_id(),
 9089                        start: offset_range.start,
 9090                        end: offset_range.end,
 9091                        reversed: false,
 9092                        goal: SelectionGoal::None,
 9093                    });
 9094                });
 9095            }
 9096        }
 9097
 9098        new_selections.sort_by_key(|selection| selection.start);
 9099        let mut ix = 0;
 9100        while ix + 1 < new_selections.len() {
 9101            let current_selection = &new_selections[ix];
 9102            let next_selection = &new_selections[ix + 1];
 9103            if current_selection.range().overlaps(&next_selection.range()) {
 9104                if current_selection.id < next_selection.id {
 9105                    new_selections.remove(ix + 1);
 9106                } else {
 9107                    new_selections.remove(ix);
 9108                }
 9109            } else {
 9110                ix += 1;
 9111            }
 9112        }
 9113
 9114        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9115
 9116        for selection in new_selections.iter_mut() {
 9117            selection.reversed = reversed;
 9118        }
 9119
 9120        select_next_state.done = true;
 9121        self.unfold_ranges(
 9122            &new_selections
 9123                .iter()
 9124                .map(|selection| selection.range())
 9125                .collect::<Vec<_>>(),
 9126            false,
 9127            false,
 9128            cx,
 9129        );
 9130        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9131            selections.select(new_selections)
 9132        });
 9133
 9134        Ok(())
 9135    }
 9136
 9137    pub fn select_next(
 9138        &mut self,
 9139        action: &SelectNext,
 9140        window: &mut Window,
 9141        cx: &mut Context<Self>,
 9142    ) -> Result<()> {
 9143        self.push_to_selection_history();
 9144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9145        self.select_next_match_internal(
 9146            &display_map,
 9147            action.replace_newest,
 9148            Some(Autoscroll::newest()),
 9149            window,
 9150            cx,
 9151        )?;
 9152        Ok(())
 9153    }
 9154
 9155    pub fn select_previous(
 9156        &mut self,
 9157        action: &SelectPrevious,
 9158        window: &mut Window,
 9159        cx: &mut Context<Self>,
 9160    ) -> Result<()> {
 9161        self.push_to_selection_history();
 9162        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9163        let buffer = &display_map.buffer_snapshot;
 9164        let mut selections = self.selections.all::<usize>(cx);
 9165        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9166            let query = &select_prev_state.query;
 9167            if !select_prev_state.done {
 9168                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9169                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9170                let mut next_selected_range = None;
 9171                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9172                let bytes_before_last_selection =
 9173                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9174                let bytes_after_first_selection =
 9175                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9176                let query_matches = query
 9177                    .stream_find_iter(bytes_before_last_selection)
 9178                    .map(|result| (last_selection.start, result))
 9179                    .chain(
 9180                        query
 9181                            .stream_find_iter(bytes_after_first_selection)
 9182                            .map(|result| (buffer.len(), result)),
 9183                    );
 9184                for (end_offset, query_match) in query_matches {
 9185                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9186                    let offset_range =
 9187                        end_offset - query_match.end()..end_offset - query_match.start();
 9188                    let display_range = offset_range.start.to_display_point(&display_map)
 9189                        ..offset_range.end.to_display_point(&display_map);
 9190
 9191                    if !select_prev_state.wordwise
 9192                        || (!movement::is_inside_word(&display_map, display_range.start)
 9193                            && !movement::is_inside_word(&display_map, display_range.end))
 9194                    {
 9195                        next_selected_range = Some(offset_range);
 9196                        break;
 9197                    }
 9198                }
 9199
 9200                if let Some(next_selected_range) = next_selected_range {
 9201                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9202                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9203                        if action.replace_newest {
 9204                            s.delete(s.newest_anchor().id);
 9205                        }
 9206                        s.insert_range(next_selected_range);
 9207                    });
 9208                } else {
 9209                    select_prev_state.done = true;
 9210                }
 9211            }
 9212
 9213            self.select_prev_state = Some(select_prev_state);
 9214        } else {
 9215            let mut only_carets = true;
 9216            let mut same_text_selected = true;
 9217            let mut selected_text = None;
 9218
 9219            let mut selections_iter = selections.iter().peekable();
 9220            while let Some(selection) = selections_iter.next() {
 9221                if selection.start != selection.end {
 9222                    only_carets = false;
 9223                }
 9224
 9225                if same_text_selected {
 9226                    if selected_text.is_none() {
 9227                        selected_text =
 9228                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9229                    }
 9230
 9231                    if let Some(next_selection) = selections_iter.peek() {
 9232                        if next_selection.range().len() == selection.range().len() {
 9233                            let next_selected_text = buffer
 9234                                .text_for_range(next_selection.range())
 9235                                .collect::<String>();
 9236                            if Some(next_selected_text) != selected_text {
 9237                                same_text_selected = false;
 9238                                selected_text = None;
 9239                            }
 9240                        } else {
 9241                            same_text_selected = false;
 9242                            selected_text = None;
 9243                        }
 9244                    }
 9245                }
 9246            }
 9247
 9248            if only_carets {
 9249                for selection in &mut selections {
 9250                    let word_range = movement::surrounding_word(
 9251                        &display_map,
 9252                        selection.start.to_display_point(&display_map),
 9253                    );
 9254                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9255                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9256                    selection.goal = SelectionGoal::None;
 9257                    selection.reversed = false;
 9258                }
 9259                if selections.len() == 1 {
 9260                    let selection = selections
 9261                        .last()
 9262                        .expect("ensured that there's only one selection");
 9263                    let query = buffer
 9264                        .text_for_range(selection.start..selection.end)
 9265                        .collect::<String>();
 9266                    let is_empty = query.is_empty();
 9267                    let select_state = SelectNextState {
 9268                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9269                        wordwise: true,
 9270                        done: is_empty,
 9271                    };
 9272                    self.select_prev_state = Some(select_state);
 9273                } else {
 9274                    self.select_prev_state = None;
 9275                }
 9276
 9277                self.unfold_ranges(
 9278                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9279                    false,
 9280                    true,
 9281                    cx,
 9282                );
 9283                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9284                    s.select(selections);
 9285                });
 9286            } else if let Some(selected_text) = selected_text {
 9287                self.select_prev_state = Some(SelectNextState {
 9288                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9289                    wordwise: false,
 9290                    done: false,
 9291                });
 9292                self.select_previous(action, window, cx)?;
 9293            }
 9294        }
 9295        Ok(())
 9296    }
 9297
 9298    pub fn toggle_comments(
 9299        &mut self,
 9300        action: &ToggleComments,
 9301        window: &mut Window,
 9302        cx: &mut Context<Self>,
 9303    ) {
 9304        if self.read_only(cx) {
 9305            return;
 9306        }
 9307        let text_layout_details = &self.text_layout_details(window);
 9308        self.transact(window, cx, |this, window, cx| {
 9309            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9310            let mut edits = Vec::new();
 9311            let mut selection_edit_ranges = Vec::new();
 9312            let mut last_toggled_row = None;
 9313            let snapshot = this.buffer.read(cx).read(cx);
 9314            let empty_str: Arc<str> = Arc::default();
 9315            let mut suffixes_inserted = Vec::new();
 9316            let ignore_indent = action.ignore_indent;
 9317
 9318            fn comment_prefix_range(
 9319                snapshot: &MultiBufferSnapshot,
 9320                row: MultiBufferRow,
 9321                comment_prefix: &str,
 9322                comment_prefix_whitespace: &str,
 9323                ignore_indent: bool,
 9324            ) -> Range<Point> {
 9325                let indent_size = if ignore_indent {
 9326                    0
 9327                } else {
 9328                    snapshot.indent_size_for_line(row).len
 9329                };
 9330
 9331                let start = Point::new(row.0, indent_size);
 9332
 9333                let mut line_bytes = snapshot
 9334                    .bytes_in_range(start..snapshot.max_point())
 9335                    .flatten()
 9336                    .copied();
 9337
 9338                // If this line currently begins with the line comment prefix, then record
 9339                // the range containing the prefix.
 9340                if line_bytes
 9341                    .by_ref()
 9342                    .take(comment_prefix.len())
 9343                    .eq(comment_prefix.bytes())
 9344                {
 9345                    // Include any whitespace that matches the comment prefix.
 9346                    let matching_whitespace_len = line_bytes
 9347                        .zip(comment_prefix_whitespace.bytes())
 9348                        .take_while(|(a, b)| a == b)
 9349                        .count() as u32;
 9350                    let end = Point::new(
 9351                        start.row,
 9352                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9353                    );
 9354                    start..end
 9355                } else {
 9356                    start..start
 9357                }
 9358            }
 9359
 9360            fn comment_suffix_range(
 9361                snapshot: &MultiBufferSnapshot,
 9362                row: MultiBufferRow,
 9363                comment_suffix: &str,
 9364                comment_suffix_has_leading_space: bool,
 9365            ) -> Range<Point> {
 9366                let end = Point::new(row.0, snapshot.line_len(row));
 9367                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9368
 9369                let mut line_end_bytes = snapshot
 9370                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9371                    .flatten()
 9372                    .copied();
 9373
 9374                let leading_space_len = if suffix_start_column > 0
 9375                    && line_end_bytes.next() == Some(b' ')
 9376                    && comment_suffix_has_leading_space
 9377                {
 9378                    1
 9379                } else {
 9380                    0
 9381                };
 9382
 9383                // If this line currently begins with the line comment prefix, then record
 9384                // the range containing the prefix.
 9385                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9386                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9387                    start..end
 9388                } else {
 9389                    end..end
 9390                }
 9391            }
 9392
 9393            // TODO: Handle selections that cross excerpts
 9394            for selection in &mut selections {
 9395                let start_column = snapshot
 9396                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9397                    .len;
 9398                let language = if let Some(language) =
 9399                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9400                {
 9401                    language
 9402                } else {
 9403                    continue;
 9404                };
 9405
 9406                selection_edit_ranges.clear();
 9407
 9408                // If multiple selections contain a given row, avoid processing that
 9409                // row more than once.
 9410                let mut start_row = MultiBufferRow(selection.start.row);
 9411                if last_toggled_row == Some(start_row) {
 9412                    start_row = start_row.next_row();
 9413                }
 9414                let end_row =
 9415                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9416                        MultiBufferRow(selection.end.row - 1)
 9417                    } else {
 9418                        MultiBufferRow(selection.end.row)
 9419                    };
 9420                last_toggled_row = Some(end_row);
 9421
 9422                if start_row > end_row {
 9423                    continue;
 9424                }
 9425
 9426                // If the language has line comments, toggle those.
 9427                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9428
 9429                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9430                if ignore_indent {
 9431                    full_comment_prefixes = full_comment_prefixes
 9432                        .into_iter()
 9433                        .map(|s| Arc::from(s.trim_end()))
 9434                        .collect();
 9435                }
 9436
 9437                if !full_comment_prefixes.is_empty() {
 9438                    let first_prefix = full_comment_prefixes
 9439                        .first()
 9440                        .expect("prefixes is non-empty");
 9441                    let prefix_trimmed_lengths = full_comment_prefixes
 9442                        .iter()
 9443                        .map(|p| p.trim_end_matches(' ').len())
 9444                        .collect::<SmallVec<[usize; 4]>>();
 9445
 9446                    let mut all_selection_lines_are_comments = true;
 9447
 9448                    for row in start_row.0..=end_row.0 {
 9449                        let row = MultiBufferRow(row);
 9450                        if start_row < end_row && snapshot.is_line_blank(row) {
 9451                            continue;
 9452                        }
 9453
 9454                        let prefix_range = full_comment_prefixes
 9455                            .iter()
 9456                            .zip(prefix_trimmed_lengths.iter().copied())
 9457                            .map(|(prefix, trimmed_prefix_len)| {
 9458                                comment_prefix_range(
 9459                                    snapshot.deref(),
 9460                                    row,
 9461                                    &prefix[..trimmed_prefix_len],
 9462                                    &prefix[trimmed_prefix_len..],
 9463                                    ignore_indent,
 9464                                )
 9465                            })
 9466                            .max_by_key(|range| range.end.column - range.start.column)
 9467                            .expect("prefixes is non-empty");
 9468
 9469                        if prefix_range.is_empty() {
 9470                            all_selection_lines_are_comments = false;
 9471                        }
 9472
 9473                        selection_edit_ranges.push(prefix_range);
 9474                    }
 9475
 9476                    if all_selection_lines_are_comments {
 9477                        edits.extend(
 9478                            selection_edit_ranges
 9479                                .iter()
 9480                                .cloned()
 9481                                .map(|range| (range, empty_str.clone())),
 9482                        );
 9483                    } else {
 9484                        let min_column = selection_edit_ranges
 9485                            .iter()
 9486                            .map(|range| range.start.column)
 9487                            .min()
 9488                            .unwrap_or(0);
 9489                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9490                            let position = Point::new(range.start.row, min_column);
 9491                            (position..position, first_prefix.clone())
 9492                        }));
 9493                    }
 9494                } else if let Some((full_comment_prefix, comment_suffix)) =
 9495                    language.block_comment_delimiters()
 9496                {
 9497                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9498                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9499                    let prefix_range = comment_prefix_range(
 9500                        snapshot.deref(),
 9501                        start_row,
 9502                        comment_prefix,
 9503                        comment_prefix_whitespace,
 9504                        ignore_indent,
 9505                    );
 9506                    let suffix_range = comment_suffix_range(
 9507                        snapshot.deref(),
 9508                        end_row,
 9509                        comment_suffix.trim_start_matches(' '),
 9510                        comment_suffix.starts_with(' '),
 9511                    );
 9512
 9513                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9514                        edits.push((
 9515                            prefix_range.start..prefix_range.start,
 9516                            full_comment_prefix.clone(),
 9517                        ));
 9518                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9519                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9520                    } else {
 9521                        edits.push((prefix_range, empty_str.clone()));
 9522                        edits.push((suffix_range, empty_str.clone()));
 9523                    }
 9524                } else {
 9525                    continue;
 9526                }
 9527            }
 9528
 9529            drop(snapshot);
 9530            this.buffer.update(cx, |buffer, cx| {
 9531                buffer.edit(edits, None, cx);
 9532            });
 9533
 9534            // Adjust selections so that they end before any comment suffixes that
 9535            // were inserted.
 9536            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9537            let mut selections = this.selections.all::<Point>(cx);
 9538            let snapshot = this.buffer.read(cx).read(cx);
 9539            for selection in &mut selections {
 9540                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9541                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9542                        Ordering::Less => {
 9543                            suffixes_inserted.next();
 9544                            continue;
 9545                        }
 9546                        Ordering::Greater => break,
 9547                        Ordering::Equal => {
 9548                            if selection.end.column == snapshot.line_len(row) {
 9549                                if selection.is_empty() {
 9550                                    selection.start.column -= suffix_len as u32;
 9551                                }
 9552                                selection.end.column -= suffix_len as u32;
 9553                            }
 9554                            break;
 9555                        }
 9556                    }
 9557                }
 9558            }
 9559
 9560            drop(snapshot);
 9561            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9562                s.select(selections)
 9563            });
 9564
 9565            let selections = this.selections.all::<Point>(cx);
 9566            let selections_on_single_row = selections.windows(2).all(|selections| {
 9567                selections[0].start.row == selections[1].start.row
 9568                    && selections[0].end.row == selections[1].end.row
 9569                    && selections[0].start.row == selections[0].end.row
 9570            });
 9571            let selections_selecting = selections
 9572                .iter()
 9573                .any(|selection| selection.start != selection.end);
 9574            let advance_downwards = action.advance_downwards
 9575                && selections_on_single_row
 9576                && !selections_selecting
 9577                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9578
 9579            if advance_downwards {
 9580                let snapshot = this.buffer.read(cx).snapshot(cx);
 9581
 9582                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9583                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9584                        let mut point = display_point.to_point(display_snapshot);
 9585                        point.row += 1;
 9586                        point = snapshot.clip_point(point, Bias::Left);
 9587                        let display_point = point.to_display_point(display_snapshot);
 9588                        let goal = SelectionGoal::HorizontalPosition(
 9589                            display_snapshot
 9590                                .x_for_display_point(display_point, text_layout_details)
 9591                                .into(),
 9592                        );
 9593                        (display_point, goal)
 9594                    })
 9595                });
 9596            }
 9597        });
 9598    }
 9599
 9600    pub fn select_enclosing_symbol(
 9601        &mut self,
 9602        _: &SelectEnclosingSymbol,
 9603        window: &mut Window,
 9604        cx: &mut Context<Self>,
 9605    ) {
 9606        let buffer = self.buffer.read(cx).snapshot(cx);
 9607        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9608
 9609        fn update_selection(
 9610            selection: &Selection<usize>,
 9611            buffer_snap: &MultiBufferSnapshot,
 9612        ) -> Option<Selection<usize>> {
 9613            let cursor = selection.head();
 9614            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9615            for symbol in symbols.iter().rev() {
 9616                let start = symbol.range.start.to_offset(buffer_snap);
 9617                let end = symbol.range.end.to_offset(buffer_snap);
 9618                let new_range = start..end;
 9619                if start < selection.start || end > selection.end {
 9620                    return Some(Selection {
 9621                        id: selection.id,
 9622                        start: new_range.start,
 9623                        end: new_range.end,
 9624                        goal: SelectionGoal::None,
 9625                        reversed: selection.reversed,
 9626                    });
 9627                }
 9628            }
 9629            None
 9630        }
 9631
 9632        let mut selected_larger_symbol = false;
 9633        let new_selections = old_selections
 9634            .iter()
 9635            .map(|selection| match update_selection(selection, &buffer) {
 9636                Some(new_selection) => {
 9637                    if new_selection.range() != selection.range() {
 9638                        selected_larger_symbol = true;
 9639                    }
 9640                    new_selection
 9641                }
 9642                None => selection.clone(),
 9643            })
 9644            .collect::<Vec<_>>();
 9645
 9646        if selected_larger_symbol {
 9647            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9648                s.select(new_selections);
 9649            });
 9650        }
 9651    }
 9652
 9653    pub fn select_larger_syntax_node(
 9654        &mut self,
 9655        _: &SelectLargerSyntaxNode,
 9656        window: &mut Window,
 9657        cx: &mut Context<Self>,
 9658    ) {
 9659        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9660        let buffer = self.buffer.read(cx).snapshot(cx);
 9661        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9662
 9663        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9664        let mut selected_larger_node = false;
 9665        let new_selections = old_selections
 9666            .iter()
 9667            .map(|selection| {
 9668                let old_range = selection.start..selection.end;
 9669                let mut new_range = old_range.clone();
 9670                let mut new_node = None;
 9671                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9672                {
 9673                    new_node = Some(node);
 9674                    new_range = containing_range;
 9675                    if !display_map.intersects_fold(new_range.start)
 9676                        && !display_map.intersects_fold(new_range.end)
 9677                    {
 9678                        break;
 9679                    }
 9680                }
 9681
 9682                if let Some(node) = new_node {
 9683                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9684                    // nodes. Parent and grandparent are also logged because this operation will not
 9685                    // visit nodes that have the same range as their parent.
 9686                    log::info!("Node: {node:?}");
 9687                    let parent = node.parent();
 9688                    log::info!("Parent: {parent:?}");
 9689                    let grandparent = parent.and_then(|x| x.parent());
 9690                    log::info!("Grandparent: {grandparent:?}");
 9691                }
 9692
 9693                selected_larger_node |= new_range != old_range;
 9694                Selection {
 9695                    id: selection.id,
 9696                    start: new_range.start,
 9697                    end: new_range.end,
 9698                    goal: SelectionGoal::None,
 9699                    reversed: selection.reversed,
 9700                }
 9701            })
 9702            .collect::<Vec<_>>();
 9703
 9704        if selected_larger_node {
 9705            stack.push(old_selections);
 9706            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9707                s.select(new_selections);
 9708            });
 9709        }
 9710        self.select_larger_syntax_node_stack = stack;
 9711    }
 9712
 9713    pub fn select_smaller_syntax_node(
 9714        &mut self,
 9715        _: &SelectSmallerSyntaxNode,
 9716        window: &mut Window,
 9717        cx: &mut Context<Self>,
 9718    ) {
 9719        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9720        if let Some(selections) = stack.pop() {
 9721            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9722                s.select(selections.to_vec());
 9723            });
 9724        }
 9725        self.select_larger_syntax_node_stack = stack;
 9726    }
 9727
 9728    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9729        if !EditorSettings::get_global(cx).gutter.runnables {
 9730            self.clear_tasks();
 9731            return Task::ready(());
 9732        }
 9733        let project = self.project.as_ref().map(Entity::downgrade);
 9734        cx.spawn_in(window, |this, mut cx| async move {
 9735            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9736            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9737                return;
 9738            };
 9739            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9740                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9741            }) else {
 9742                return;
 9743            };
 9744
 9745            let hide_runnables = project
 9746                .update(&mut cx, |project, cx| {
 9747                    // Do not display any test indicators in non-dev server remote projects.
 9748                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9749                })
 9750                .unwrap_or(true);
 9751            if hide_runnables {
 9752                return;
 9753            }
 9754            let new_rows =
 9755                cx.background_executor()
 9756                    .spawn({
 9757                        let snapshot = display_snapshot.clone();
 9758                        async move {
 9759                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9760                        }
 9761                    })
 9762                    .await;
 9763
 9764            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9765            this.update(&mut cx, |this, _| {
 9766                this.clear_tasks();
 9767                for (key, value) in rows {
 9768                    this.insert_tasks(key, value);
 9769                }
 9770            })
 9771            .ok();
 9772        })
 9773    }
 9774    fn fetch_runnable_ranges(
 9775        snapshot: &DisplaySnapshot,
 9776        range: Range<Anchor>,
 9777    ) -> Vec<language::RunnableRange> {
 9778        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9779    }
 9780
 9781    fn runnable_rows(
 9782        project: Entity<Project>,
 9783        snapshot: DisplaySnapshot,
 9784        runnable_ranges: Vec<RunnableRange>,
 9785        mut cx: AsyncWindowContext,
 9786    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9787        runnable_ranges
 9788            .into_iter()
 9789            .filter_map(|mut runnable| {
 9790                let tasks = cx
 9791                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9792                    .ok()?;
 9793                if tasks.is_empty() {
 9794                    return None;
 9795                }
 9796
 9797                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9798
 9799                let row = snapshot
 9800                    .buffer_snapshot
 9801                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9802                    .1
 9803                    .start
 9804                    .row;
 9805
 9806                let context_range =
 9807                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9808                Some((
 9809                    (runnable.buffer_id, row),
 9810                    RunnableTasks {
 9811                        templates: tasks,
 9812                        offset: MultiBufferOffset(runnable.run_range.start),
 9813                        context_range,
 9814                        column: point.column,
 9815                        extra_variables: runnable.extra_captures,
 9816                    },
 9817                ))
 9818            })
 9819            .collect()
 9820    }
 9821
 9822    fn templates_with_tags(
 9823        project: &Entity<Project>,
 9824        runnable: &mut Runnable,
 9825        cx: &mut App,
 9826    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9827        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9828            let (worktree_id, file) = project
 9829                .buffer_for_id(runnable.buffer, cx)
 9830                .and_then(|buffer| buffer.read(cx).file())
 9831                .map(|file| (file.worktree_id(cx), file.clone()))
 9832                .unzip();
 9833
 9834            (
 9835                project.task_store().read(cx).task_inventory().cloned(),
 9836                worktree_id,
 9837                file,
 9838            )
 9839        });
 9840
 9841        let tags = mem::take(&mut runnable.tags);
 9842        let mut tags: Vec<_> = tags
 9843            .into_iter()
 9844            .flat_map(|tag| {
 9845                let tag = tag.0.clone();
 9846                inventory
 9847                    .as_ref()
 9848                    .into_iter()
 9849                    .flat_map(|inventory| {
 9850                        inventory.read(cx).list_tasks(
 9851                            file.clone(),
 9852                            Some(runnable.language.clone()),
 9853                            worktree_id,
 9854                            cx,
 9855                        )
 9856                    })
 9857                    .filter(move |(_, template)| {
 9858                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9859                    })
 9860            })
 9861            .sorted_by_key(|(kind, _)| kind.to_owned())
 9862            .collect();
 9863        if let Some((leading_tag_source, _)) = tags.first() {
 9864            // Strongest source wins; if we have worktree tag binding, prefer that to
 9865            // global and language bindings;
 9866            // if we have a global binding, prefer that to language binding.
 9867            let first_mismatch = tags
 9868                .iter()
 9869                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9870            if let Some(index) = first_mismatch {
 9871                tags.truncate(index);
 9872            }
 9873        }
 9874
 9875        tags
 9876    }
 9877
 9878    pub fn move_to_enclosing_bracket(
 9879        &mut self,
 9880        _: &MoveToEnclosingBracket,
 9881        window: &mut Window,
 9882        cx: &mut Context<Self>,
 9883    ) {
 9884        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9885            s.move_offsets_with(|snapshot, selection| {
 9886                let Some(enclosing_bracket_ranges) =
 9887                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9888                else {
 9889                    return;
 9890                };
 9891
 9892                let mut best_length = usize::MAX;
 9893                let mut best_inside = false;
 9894                let mut best_in_bracket_range = false;
 9895                let mut best_destination = None;
 9896                for (open, close) in enclosing_bracket_ranges {
 9897                    let close = close.to_inclusive();
 9898                    let length = close.end() - open.start;
 9899                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9900                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9901                        || close.contains(&selection.head());
 9902
 9903                    // If best is next to a bracket and current isn't, skip
 9904                    if !in_bracket_range && best_in_bracket_range {
 9905                        continue;
 9906                    }
 9907
 9908                    // Prefer smaller lengths unless best is inside and current isn't
 9909                    if length > best_length && (best_inside || !inside) {
 9910                        continue;
 9911                    }
 9912
 9913                    best_length = length;
 9914                    best_inside = inside;
 9915                    best_in_bracket_range = in_bracket_range;
 9916                    best_destination = Some(
 9917                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9918                            if inside {
 9919                                open.end
 9920                            } else {
 9921                                open.start
 9922                            }
 9923                        } else if inside {
 9924                            *close.start()
 9925                        } else {
 9926                            *close.end()
 9927                        },
 9928                    );
 9929                }
 9930
 9931                if let Some(destination) = best_destination {
 9932                    selection.collapse_to(destination, SelectionGoal::None);
 9933                }
 9934            })
 9935        });
 9936    }
 9937
 9938    pub fn undo_selection(
 9939        &mut self,
 9940        _: &UndoSelection,
 9941        window: &mut Window,
 9942        cx: &mut Context<Self>,
 9943    ) {
 9944        self.end_selection(window, cx);
 9945        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9946        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9947            self.change_selections(None, window, cx, |s| {
 9948                s.select_anchors(entry.selections.to_vec())
 9949            });
 9950            self.select_next_state = entry.select_next_state;
 9951            self.select_prev_state = entry.select_prev_state;
 9952            self.add_selections_state = entry.add_selections_state;
 9953            self.request_autoscroll(Autoscroll::newest(), cx);
 9954        }
 9955        self.selection_history.mode = SelectionHistoryMode::Normal;
 9956    }
 9957
 9958    pub fn redo_selection(
 9959        &mut self,
 9960        _: &RedoSelection,
 9961        window: &mut Window,
 9962        cx: &mut Context<Self>,
 9963    ) {
 9964        self.end_selection(window, cx);
 9965        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9966        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9967            self.change_selections(None, window, cx, |s| {
 9968                s.select_anchors(entry.selections.to_vec())
 9969            });
 9970            self.select_next_state = entry.select_next_state;
 9971            self.select_prev_state = entry.select_prev_state;
 9972            self.add_selections_state = entry.add_selections_state;
 9973            self.request_autoscroll(Autoscroll::newest(), cx);
 9974        }
 9975        self.selection_history.mode = SelectionHistoryMode::Normal;
 9976    }
 9977
 9978    pub fn expand_excerpts(
 9979        &mut self,
 9980        action: &ExpandExcerpts,
 9981        _: &mut Window,
 9982        cx: &mut Context<Self>,
 9983    ) {
 9984        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9985    }
 9986
 9987    pub fn expand_excerpts_down(
 9988        &mut self,
 9989        action: &ExpandExcerptsDown,
 9990        _: &mut Window,
 9991        cx: &mut Context<Self>,
 9992    ) {
 9993        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9994    }
 9995
 9996    pub fn expand_excerpts_up(
 9997        &mut self,
 9998        action: &ExpandExcerptsUp,
 9999        _: &mut Window,
10000        cx: &mut Context<Self>,
10001    ) {
10002        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10003    }
10004
10005    pub fn expand_excerpts_for_direction(
10006        &mut self,
10007        lines: u32,
10008        direction: ExpandExcerptDirection,
10009
10010        cx: &mut Context<Self>,
10011    ) {
10012        let selections = self.selections.disjoint_anchors();
10013
10014        let lines = if lines == 0 {
10015            EditorSettings::get_global(cx).expand_excerpt_lines
10016        } else {
10017            lines
10018        };
10019
10020        self.buffer.update(cx, |buffer, cx| {
10021            let snapshot = buffer.snapshot(cx);
10022            let mut excerpt_ids = selections
10023                .iter()
10024                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10025                .collect::<Vec<_>>();
10026            excerpt_ids.sort();
10027            excerpt_ids.dedup();
10028            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10029        })
10030    }
10031
10032    pub fn expand_excerpt(
10033        &mut self,
10034        excerpt: ExcerptId,
10035        direction: ExpandExcerptDirection,
10036        cx: &mut Context<Self>,
10037    ) {
10038        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10039        self.buffer.update(cx, |buffer, cx| {
10040            buffer.expand_excerpts([excerpt], lines, direction, cx)
10041        })
10042    }
10043
10044    pub fn go_to_singleton_buffer_point(
10045        &mut self,
10046        point: Point,
10047        window: &mut Window,
10048        cx: &mut Context<Self>,
10049    ) {
10050        self.go_to_singleton_buffer_range(point..point, window, cx);
10051    }
10052
10053    pub fn go_to_singleton_buffer_range(
10054        &mut self,
10055        range: Range<Point>,
10056        window: &mut Window,
10057        cx: &mut Context<Self>,
10058    ) {
10059        let multibuffer = self.buffer().read(cx);
10060        let Some(buffer) = multibuffer.as_singleton() else {
10061            return;
10062        };
10063        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10064            return;
10065        };
10066        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10067            return;
10068        };
10069        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10070            s.select_anchor_ranges([start..end])
10071        });
10072    }
10073
10074    fn go_to_diagnostic(
10075        &mut self,
10076        _: &GoToDiagnostic,
10077        window: &mut Window,
10078        cx: &mut Context<Self>,
10079    ) {
10080        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10081    }
10082
10083    fn go_to_prev_diagnostic(
10084        &mut self,
10085        _: &GoToPrevDiagnostic,
10086        window: &mut Window,
10087        cx: &mut Context<Self>,
10088    ) {
10089        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10090    }
10091
10092    pub fn go_to_diagnostic_impl(
10093        &mut self,
10094        direction: Direction,
10095        window: &mut Window,
10096        cx: &mut Context<Self>,
10097    ) {
10098        let buffer = self.buffer.read(cx).snapshot(cx);
10099        let selection = self.selections.newest::<usize>(cx);
10100
10101        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10102        if direction == Direction::Next {
10103            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10104                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10105                    return;
10106                };
10107                self.activate_diagnostics(
10108                    buffer_id,
10109                    popover.local_diagnostic.diagnostic.group_id,
10110                    window,
10111                    cx,
10112                );
10113                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10114                    let primary_range_start = active_diagnostics.primary_range.start;
10115                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10116                        let mut new_selection = s.newest_anchor().clone();
10117                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10118                        s.select_anchors(vec![new_selection.clone()]);
10119                    });
10120                    self.refresh_inline_completion(false, true, window, cx);
10121                }
10122                return;
10123            }
10124        }
10125
10126        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10127            active_diagnostics
10128                .primary_range
10129                .to_offset(&buffer)
10130                .to_inclusive()
10131        });
10132        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10133            if active_primary_range.contains(&selection.head()) {
10134                *active_primary_range.start()
10135            } else {
10136                selection.head()
10137            }
10138        } else {
10139            selection.head()
10140        };
10141        let snapshot = self.snapshot(window, cx);
10142        loop {
10143            let mut diagnostics;
10144            if direction == Direction::Prev {
10145                diagnostics = buffer
10146                    .diagnostics_in_range::<_, usize>(0..search_start)
10147                    .collect::<Vec<_>>();
10148                diagnostics.reverse();
10149            } else {
10150                diagnostics = buffer
10151                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10152                    .collect::<Vec<_>>();
10153            };
10154            let group = diagnostics
10155                .into_iter()
10156                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10157                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10158                // be sorted in a stable way
10159                // skip until we are at current active diagnostic, if it exists
10160                .skip_while(|entry| {
10161                    let is_in_range = match direction {
10162                        Direction::Prev => entry.range.end > search_start,
10163                        Direction::Next => entry.range.start < search_start,
10164                    };
10165                    is_in_range
10166                        && self
10167                            .active_diagnostics
10168                            .as_ref()
10169                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10170                })
10171                .find_map(|entry| {
10172                    if entry.diagnostic.is_primary
10173                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10174                        && entry.range.start != entry.range.end
10175                        // if we match with the active diagnostic, skip it
10176                        && Some(entry.diagnostic.group_id)
10177                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10178                    {
10179                        Some((entry.range, entry.diagnostic.group_id))
10180                    } else {
10181                        None
10182                    }
10183                });
10184
10185            if let Some((primary_range, group_id)) = group {
10186                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10187                    return;
10188                };
10189                self.activate_diagnostics(buffer_id, group_id, window, cx);
10190                if self.active_diagnostics.is_some() {
10191                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10192                        s.select(vec![Selection {
10193                            id: selection.id,
10194                            start: primary_range.start,
10195                            end: primary_range.start,
10196                            reversed: false,
10197                            goal: SelectionGoal::None,
10198                        }]);
10199                    });
10200                    self.refresh_inline_completion(false, true, window, cx);
10201                }
10202                break;
10203            } else {
10204                // Cycle around to the start of the buffer, potentially moving back to the start of
10205                // the currently active diagnostic.
10206                active_primary_range.take();
10207                if direction == Direction::Prev {
10208                    if search_start == buffer.len() {
10209                        break;
10210                    } else {
10211                        search_start = buffer.len();
10212                    }
10213                } else if search_start == 0 {
10214                    break;
10215                } else {
10216                    search_start = 0;
10217                }
10218            }
10219        }
10220    }
10221
10222    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10223        let snapshot = self.snapshot(window, cx);
10224        let selection = self.selections.newest::<Point>(cx);
10225        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10226    }
10227
10228    fn go_to_hunk_after_position(
10229        &mut self,
10230        snapshot: &EditorSnapshot,
10231        position: Point,
10232        window: &mut Window,
10233        cx: &mut Context<Editor>,
10234    ) -> Option<MultiBufferDiffHunk> {
10235        let mut hunk = snapshot
10236            .buffer_snapshot
10237            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10238            .find(|hunk| hunk.row_range.start.0 > position.row);
10239        if hunk.is_none() {
10240            hunk = snapshot
10241                .buffer_snapshot
10242                .diff_hunks_in_range(Point::zero()..position)
10243                .find(|hunk| hunk.row_range.end.0 < position.row)
10244        }
10245        if let Some(hunk) = &hunk {
10246            let destination = Point::new(hunk.row_range.start.0, 0);
10247            self.unfold_ranges(&[destination..destination], false, false, cx);
10248            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10249                s.select_ranges(vec![destination..destination]);
10250            });
10251        }
10252
10253        hunk
10254    }
10255
10256    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10257        let snapshot = self.snapshot(window, cx);
10258        let selection = self.selections.newest::<Point>(cx);
10259        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10260    }
10261
10262    fn go_to_hunk_before_position(
10263        &mut self,
10264        snapshot: &EditorSnapshot,
10265        position: Point,
10266        window: &mut Window,
10267        cx: &mut Context<Editor>,
10268    ) -> Option<MultiBufferDiffHunk> {
10269        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10270        if hunk.is_none() {
10271            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10272        }
10273        if let Some(hunk) = &hunk {
10274            let destination = Point::new(hunk.row_range.start.0, 0);
10275            self.unfold_ranges(&[destination..destination], false, false, cx);
10276            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10277                s.select_ranges(vec![destination..destination]);
10278            });
10279        }
10280
10281        hunk
10282    }
10283
10284    pub fn go_to_definition(
10285        &mut self,
10286        _: &GoToDefinition,
10287        window: &mut Window,
10288        cx: &mut Context<Self>,
10289    ) -> Task<Result<Navigated>> {
10290        let definition =
10291            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10292        cx.spawn_in(window, |editor, mut cx| async move {
10293            if definition.await? == Navigated::Yes {
10294                return Ok(Navigated::Yes);
10295            }
10296            match editor.update_in(&mut cx, |editor, window, cx| {
10297                editor.find_all_references(&FindAllReferences, window, cx)
10298            })? {
10299                Some(references) => references.await,
10300                None => Ok(Navigated::No),
10301            }
10302        })
10303    }
10304
10305    pub fn go_to_declaration(
10306        &mut self,
10307        _: &GoToDeclaration,
10308        window: &mut Window,
10309        cx: &mut Context<Self>,
10310    ) -> Task<Result<Navigated>> {
10311        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10312    }
10313
10314    pub fn go_to_declaration_split(
10315        &mut self,
10316        _: &GoToDeclaration,
10317        window: &mut Window,
10318        cx: &mut Context<Self>,
10319    ) -> Task<Result<Navigated>> {
10320        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10321    }
10322
10323    pub fn go_to_implementation(
10324        &mut self,
10325        _: &GoToImplementation,
10326        window: &mut Window,
10327        cx: &mut Context<Self>,
10328    ) -> Task<Result<Navigated>> {
10329        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10330    }
10331
10332    pub fn go_to_implementation_split(
10333        &mut self,
10334        _: &GoToImplementationSplit,
10335        window: &mut Window,
10336        cx: &mut Context<Self>,
10337    ) -> Task<Result<Navigated>> {
10338        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10339    }
10340
10341    pub fn go_to_type_definition(
10342        &mut self,
10343        _: &GoToTypeDefinition,
10344        window: &mut Window,
10345        cx: &mut Context<Self>,
10346    ) -> Task<Result<Navigated>> {
10347        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10348    }
10349
10350    pub fn go_to_definition_split(
10351        &mut self,
10352        _: &GoToDefinitionSplit,
10353        window: &mut Window,
10354        cx: &mut Context<Self>,
10355    ) -> Task<Result<Navigated>> {
10356        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10357    }
10358
10359    pub fn go_to_type_definition_split(
10360        &mut self,
10361        _: &GoToTypeDefinitionSplit,
10362        window: &mut Window,
10363        cx: &mut Context<Self>,
10364    ) -> Task<Result<Navigated>> {
10365        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10366    }
10367
10368    fn go_to_definition_of_kind(
10369        &mut self,
10370        kind: GotoDefinitionKind,
10371        split: bool,
10372        window: &mut Window,
10373        cx: &mut Context<Self>,
10374    ) -> Task<Result<Navigated>> {
10375        let Some(provider) = self.semantics_provider.clone() else {
10376            return Task::ready(Ok(Navigated::No));
10377        };
10378        let head = self.selections.newest::<usize>(cx).head();
10379        let buffer = self.buffer.read(cx);
10380        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10381            text_anchor
10382        } else {
10383            return Task::ready(Ok(Navigated::No));
10384        };
10385
10386        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10387            return Task::ready(Ok(Navigated::No));
10388        };
10389
10390        cx.spawn_in(window, |editor, mut cx| async move {
10391            let definitions = definitions.await?;
10392            let navigated = editor
10393                .update_in(&mut cx, |editor, window, cx| {
10394                    editor.navigate_to_hover_links(
10395                        Some(kind),
10396                        definitions
10397                            .into_iter()
10398                            .filter(|location| {
10399                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10400                            })
10401                            .map(HoverLink::Text)
10402                            .collect::<Vec<_>>(),
10403                        split,
10404                        window,
10405                        cx,
10406                    )
10407                })?
10408                .await?;
10409            anyhow::Ok(navigated)
10410        })
10411    }
10412
10413    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10414        let selection = self.selections.newest_anchor();
10415        let head = selection.head();
10416        let tail = selection.tail();
10417
10418        let Some((buffer, start_position)) =
10419            self.buffer.read(cx).text_anchor_for_position(head, cx)
10420        else {
10421            return;
10422        };
10423
10424        let end_position = if head != tail {
10425            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10426                return;
10427            };
10428            Some(pos)
10429        } else {
10430            None
10431        };
10432
10433        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10434            let url = if let Some(end_pos) = end_position {
10435                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10436            } else {
10437                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10438            };
10439
10440            if let Some(url) = url {
10441                editor.update(&mut cx, |_, cx| {
10442                    cx.open_url(&url);
10443                })
10444            } else {
10445                Ok(())
10446            }
10447        });
10448
10449        url_finder.detach();
10450    }
10451
10452    pub fn open_selected_filename(
10453        &mut self,
10454        _: &OpenSelectedFilename,
10455        window: &mut Window,
10456        cx: &mut Context<Self>,
10457    ) {
10458        let Some(workspace) = self.workspace() else {
10459            return;
10460        };
10461
10462        let position = self.selections.newest_anchor().head();
10463
10464        let Some((buffer, buffer_position)) =
10465            self.buffer.read(cx).text_anchor_for_position(position, cx)
10466        else {
10467            return;
10468        };
10469
10470        let project = self.project.clone();
10471
10472        cx.spawn_in(window, |_, mut cx| async move {
10473            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10474
10475            if let Some((_, path)) = result {
10476                workspace
10477                    .update_in(&mut cx, |workspace, window, cx| {
10478                        workspace.open_resolved_path(path, window, cx)
10479                    })?
10480                    .await?;
10481            }
10482            anyhow::Ok(())
10483        })
10484        .detach();
10485    }
10486
10487    pub(crate) fn navigate_to_hover_links(
10488        &mut self,
10489        kind: Option<GotoDefinitionKind>,
10490        mut definitions: Vec<HoverLink>,
10491        split: bool,
10492        window: &mut Window,
10493        cx: &mut Context<Editor>,
10494    ) -> Task<Result<Navigated>> {
10495        // If there is one definition, just open it directly
10496        if definitions.len() == 1 {
10497            let definition = definitions.pop().unwrap();
10498
10499            enum TargetTaskResult {
10500                Location(Option<Location>),
10501                AlreadyNavigated,
10502            }
10503
10504            let target_task = match definition {
10505                HoverLink::Text(link) => {
10506                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10507                }
10508                HoverLink::InlayHint(lsp_location, server_id) => {
10509                    let computation =
10510                        self.compute_target_location(lsp_location, server_id, window, cx);
10511                    cx.background_executor().spawn(async move {
10512                        let location = computation.await?;
10513                        Ok(TargetTaskResult::Location(location))
10514                    })
10515                }
10516                HoverLink::Url(url) => {
10517                    cx.open_url(&url);
10518                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10519                }
10520                HoverLink::File(path) => {
10521                    if let Some(workspace) = self.workspace() {
10522                        cx.spawn_in(window, |_, mut cx| async move {
10523                            workspace
10524                                .update_in(&mut cx, |workspace, window, cx| {
10525                                    workspace.open_resolved_path(path, window, cx)
10526                                })?
10527                                .await
10528                                .map(|_| TargetTaskResult::AlreadyNavigated)
10529                        })
10530                    } else {
10531                        Task::ready(Ok(TargetTaskResult::Location(None)))
10532                    }
10533                }
10534            };
10535            cx.spawn_in(window, |editor, mut cx| async move {
10536                let target = match target_task.await.context("target resolution task")? {
10537                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10538                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10539                    TargetTaskResult::Location(Some(target)) => target,
10540                };
10541
10542                editor.update_in(&mut cx, |editor, window, cx| {
10543                    let Some(workspace) = editor.workspace() else {
10544                        return Navigated::No;
10545                    };
10546                    let pane = workspace.read(cx).active_pane().clone();
10547
10548                    let range = target.range.to_point(target.buffer.read(cx));
10549                    let range = editor.range_for_match(&range);
10550                    let range = collapse_multiline_range(range);
10551
10552                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10553                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10554                    } else {
10555                        window.defer(cx, move |window, cx| {
10556                            let target_editor: Entity<Self> =
10557                                workspace.update(cx, |workspace, cx| {
10558                                    let pane = if split {
10559                                        workspace.adjacent_pane(window, cx)
10560                                    } else {
10561                                        workspace.active_pane().clone()
10562                                    };
10563
10564                                    workspace.open_project_item(
10565                                        pane,
10566                                        target.buffer.clone(),
10567                                        true,
10568                                        true,
10569                                        window,
10570                                        cx,
10571                                    )
10572                                });
10573                            target_editor.update(cx, |target_editor, cx| {
10574                                // When selecting a definition in a different buffer, disable the nav history
10575                                // to avoid creating a history entry at the previous cursor location.
10576                                pane.update(cx, |pane, _| pane.disable_history());
10577                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10578                                pane.update(cx, |pane, _| pane.enable_history());
10579                            });
10580                        });
10581                    }
10582                    Navigated::Yes
10583                })
10584            })
10585        } else if !definitions.is_empty() {
10586            cx.spawn_in(window, |editor, mut cx| async move {
10587                let (title, location_tasks, workspace) = editor
10588                    .update_in(&mut cx, |editor, window, cx| {
10589                        let tab_kind = match kind {
10590                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10591                            _ => "Definitions",
10592                        };
10593                        let title = definitions
10594                            .iter()
10595                            .find_map(|definition| match definition {
10596                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10597                                    let buffer = origin.buffer.read(cx);
10598                                    format!(
10599                                        "{} for {}",
10600                                        tab_kind,
10601                                        buffer
10602                                            .text_for_range(origin.range.clone())
10603                                            .collect::<String>()
10604                                    )
10605                                }),
10606                                HoverLink::InlayHint(_, _) => None,
10607                                HoverLink::Url(_) => None,
10608                                HoverLink::File(_) => None,
10609                            })
10610                            .unwrap_or(tab_kind.to_string());
10611                        let location_tasks = definitions
10612                            .into_iter()
10613                            .map(|definition| match definition {
10614                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10615                                HoverLink::InlayHint(lsp_location, server_id) => editor
10616                                    .compute_target_location(lsp_location, server_id, window, cx),
10617                                HoverLink::Url(_) => Task::ready(Ok(None)),
10618                                HoverLink::File(_) => Task::ready(Ok(None)),
10619                            })
10620                            .collect::<Vec<_>>();
10621                        (title, location_tasks, editor.workspace().clone())
10622                    })
10623                    .context("location tasks preparation")?;
10624
10625                let locations = future::join_all(location_tasks)
10626                    .await
10627                    .into_iter()
10628                    .filter_map(|location| location.transpose())
10629                    .collect::<Result<_>>()
10630                    .context("location tasks")?;
10631
10632                let Some(workspace) = workspace else {
10633                    return Ok(Navigated::No);
10634                };
10635                let opened = workspace
10636                    .update_in(&mut cx, |workspace, window, cx| {
10637                        Self::open_locations_in_multibuffer(
10638                            workspace,
10639                            locations,
10640                            title,
10641                            split,
10642                            MultibufferSelectionMode::First,
10643                            window,
10644                            cx,
10645                        )
10646                    })
10647                    .ok();
10648
10649                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10650            })
10651        } else {
10652            Task::ready(Ok(Navigated::No))
10653        }
10654    }
10655
10656    fn compute_target_location(
10657        &self,
10658        lsp_location: lsp::Location,
10659        server_id: LanguageServerId,
10660        window: &mut Window,
10661        cx: &mut Context<Self>,
10662    ) -> Task<anyhow::Result<Option<Location>>> {
10663        let Some(project) = self.project.clone() else {
10664            return Task::ready(Ok(None));
10665        };
10666
10667        cx.spawn_in(window, move |editor, mut cx| async move {
10668            let location_task = editor.update(&mut cx, |_, cx| {
10669                project.update(cx, |project, cx| {
10670                    let language_server_name = project
10671                        .language_server_statuses(cx)
10672                        .find(|(id, _)| server_id == *id)
10673                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10674                    language_server_name.map(|language_server_name| {
10675                        project.open_local_buffer_via_lsp(
10676                            lsp_location.uri.clone(),
10677                            server_id,
10678                            language_server_name,
10679                            cx,
10680                        )
10681                    })
10682                })
10683            })?;
10684            let location = match location_task {
10685                Some(task) => Some({
10686                    let target_buffer_handle = task.await.context("open local buffer")?;
10687                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10688                        let target_start = target_buffer
10689                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10690                        let target_end = target_buffer
10691                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10692                        target_buffer.anchor_after(target_start)
10693                            ..target_buffer.anchor_before(target_end)
10694                    })?;
10695                    Location {
10696                        buffer: target_buffer_handle,
10697                        range,
10698                    }
10699                }),
10700                None => None,
10701            };
10702            Ok(location)
10703        })
10704    }
10705
10706    pub fn find_all_references(
10707        &mut self,
10708        _: &FindAllReferences,
10709        window: &mut Window,
10710        cx: &mut Context<Self>,
10711    ) -> Option<Task<Result<Navigated>>> {
10712        let selection = self.selections.newest::<usize>(cx);
10713        let multi_buffer = self.buffer.read(cx);
10714        let head = selection.head();
10715
10716        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10717        let head_anchor = multi_buffer_snapshot.anchor_at(
10718            head,
10719            if head < selection.tail() {
10720                Bias::Right
10721            } else {
10722                Bias::Left
10723            },
10724        );
10725
10726        match self
10727            .find_all_references_task_sources
10728            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10729        {
10730            Ok(_) => {
10731                log::info!(
10732                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10733                );
10734                return None;
10735            }
10736            Err(i) => {
10737                self.find_all_references_task_sources.insert(i, head_anchor);
10738            }
10739        }
10740
10741        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10742        let workspace = self.workspace()?;
10743        let project = workspace.read(cx).project().clone();
10744        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10745        Some(cx.spawn_in(window, |editor, mut cx| async move {
10746            let _cleanup = defer({
10747                let mut cx = cx.clone();
10748                move || {
10749                    let _ = editor.update(&mut cx, |editor, _| {
10750                        if let Ok(i) =
10751                            editor
10752                                .find_all_references_task_sources
10753                                .binary_search_by(|anchor| {
10754                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10755                                })
10756                        {
10757                            editor.find_all_references_task_sources.remove(i);
10758                        }
10759                    });
10760                }
10761            });
10762
10763            let locations = references.await?;
10764            if locations.is_empty() {
10765                return anyhow::Ok(Navigated::No);
10766            }
10767
10768            workspace.update_in(&mut cx, |workspace, window, cx| {
10769                let title = locations
10770                    .first()
10771                    .as_ref()
10772                    .map(|location| {
10773                        let buffer = location.buffer.read(cx);
10774                        format!(
10775                            "References to `{}`",
10776                            buffer
10777                                .text_for_range(location.range.clone())
10778                                .collect::<String>()
10779                        )
10780                    })
10781                    .unwrap();
10782                Self::open_locations_in_multibuffer(
10783                    workspace,
10784                    locations,
10785                    title,
10786                    false,
10787                    MultibufferSelectionMode::First,
10788                    window,
10789                    cx,
10790                );
10791                Navigated::Yes
10792            })
10793        }))
10794    }
10795
10796    /// Opens a multibuffer with the given project locations in it
10797    pub fn open_locations_in_multibuffer(
10798        workspace: &mut Workspace,
10799        mut locations: Vec<Location>,
10800        title: String,
10801        split: bool,
10802        multibuffer_selection_mode: MultibufferSelectionMode,
10803        window: &mut Window,
10804        cx: &mut Context<Workspace>,
10805    ) {
10806        // If there are multiple definitions, open them in a multibuffer
10807        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10808        let mut locations = locations.into_iter().peekable();
10809        let mut ranges = Vec::new();
10810        let capability = workspace.project().read(cx).capability();
10811
10812        let excerpt_buffer = cx.new(|cx| {
10813            let mut multibuffer = MultiBuffer::new(capability);
10814            while let Some(location) = locations.next() {
10815                let buffer = location.buffer.read(cx);
10816                let mut ranges_for_buffer = Vec::new();
10817                let range = location.range.to_offset(buffer);
10818                ranges_for_buffer.push(range.clone());
10819
10820                while let Some(next_location) = locations.peek() {
10821                    if next_location.buffer == location.buffer {
10822                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10823                        locations.next();
10824                    } else {
10825                        break;
10826                    }
10827                }
10828
10829                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10830                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10831                    location.buffer.clone(),
10832                    ranges_for_buffer,
10833                    DEFAULT_MULTIBUFFER_CONTEXT,
10834                    cx,
10835                ))
10836            }
10837
10838            multibuffer.with_title(title)
10839        });
10840
10841        let editor = cx.new(|cx| {
10842            Editor::for_multibuffer(
10843                excerpt_buffer,
10844                Some(workspace.project().clone()),
10845                true,
10846                window,
10847                cx,
10848            )
10849        });
10850        editor.update(cx, |editor, cx| {
10851            match multibuffer_selection_mode {
10852                MultibufferSelectionMode::First => {
10853                    if let Some(first_range) = ranges.first() {
10854                        editor.change_selections(None, window, cx, |selections| {
10855                            selections.clear_disjoint();
10856                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10857                        });
10858                    }
10859                    editor.highlight_background::<Self>(
10860                        &ranges,
10861                        |theme| theme.editor_highlighted_line_background,
10862                        cx,
10863                    );
10864                }
10865                MultibufferSelectionMode::All => {
10866                    editor.change_selections(None, window, cx, |selections| {
10867                        selections.clear_disjoint();
10868                        selections.select_anchor_ranges(ranges);
10869                    });
10870                }
10871            }
10872            editor.register_buffers_with_language_servers(cx);
10873        });
10874
10875        let item = Box::new(editor);
10876        let item_id = item.item_id();
10877
10878        if split {
10879            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10880        } else {
10881            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10882                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10883                    pane.close_current_preview_item(window, cx)
10884                } else {
10885                    None
10886                }
10887            });
10888            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10889        }
10890        workspace.active_pane().update(cx, |pane, cx| {
10891            pane.set_preview_item_id(Some(item_id), cx);
10892        });
10893    }
10894
10895    pub fn rename(
10896        &mut self,
10897        _: &Rename,
10898        window: &mut Window,
10899        cx: &mut Context<Self>,
10900    ) -> Option<Task<Result<()>>> {
10901        use language::ToOffset as _;
10902
10903        let provider = self.semantics_provider.clone()?;
10904        let selection = self.selections.newest_anchor().clone();
10905        let (cursor_buffer, cursor_buffer_position) = self
10906            .buffer
10907            .read(cx)
10908            .text_anchor_for_position(selection.head(), cx)?;
10909        let (tail_buffer, cursor_buffer_position_end) = self
10910            .buffer
10911            .read(cx)
10912            .text_anchor_for_position(selection.tail(), cx)?;
10913        if tail_buffer != cursor_buffer {
10914            return None;
10915        }
10916
10917        let snapshot = cursor_buffer.read(cx).snapshot();
10918        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10919        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10920        let prepare_rename = provider
10921            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10922            .unwrap_or_else(|| Task::ready(Ok(None)));
10923        drop(snapshot);
10924
10925        Some(cx.spawn_in(window, |this, mut cx| async move {
10926            let rename_range = if let Some(range) = prepare_rename.await? {
10927                Some(range)
10928            } else {
10929                this.update(&mut cx, |this, cx| {
10930                    let buffer = this.buffer.read(cx).snapshot(cx);
10931                    let mut buffer_highlights = this
10932                        .document_highlights_for_position(selection.head(), &buffer)
10933                        .filter(|highlight| {
10934                            highlight.start.excerpt_id == selection.head().excerpt_id
10935                                && highlight.end.excerpt_id == selection.head().excerpt_id
10936                        });
10937                    buffer_highlights
10938                        .next()
10939                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10940                })?
10941            };
10942            if let Some(rename_range) = rename_range {
10943                this.update_in(&mut cx, |this, window, cx| {
10944                    let snapshot = cursor_buffer.read(cx).snapshot();
10945                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10946                    let cursor_offset_in_rename_range =
10947                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10948                    let cursor_offset_in_rename_range_end =
10949                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10950
10951                    this.take_rename(false, window, cx);
10952                    let buffer = this.buffer.read(cx).read(cx);
10953                    let cursor_offset = selection.head().to_offset(&buffer);
10954                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10955                    let rename_end = rename_start + rename_buffer_range.len();
10956                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10957                    let mut old_highlight_id = None;
10958                    let old_name: Arc<str> = buffer
10959                        .chunks(rename_start..rename_end, true)
10960                        .map(|chunk| {
10961                            if old_highlight_id.is_none() {
10962                                old_highlight_id = chunk.syntax_highlight_id;
10963                            }
10964                            chunk.text
10965                        })
10966                        .collect::<String>()
10967                        .into();
10968
10969                    drop(buffer);
10970
10971                    // Position the selection in the rename editor so that it matches the current selection.
10972                    this.show_local_selections = false;
10973                    let rename_editor = cx.new(|cx| {
10974                        let mut editor = Editor::single_line(window, cx);
10975                        editor.buffer.update(cx, |buffer, cx| {
10976                            buffer.edit([(0..0, old_name.clone())], None, cx)
10977                        });
10978                        let rename_selection_range = match cursor_offset_in_rename_range
10979                            .cmp(&cursor_offset_in_rename_range_end)
10980                        {
10981                            Ordering::Equal => {
10982                                editor.select_all(&SelectAll, window, cx);
10983                                return editor;
10984                            }
10985                            Ordering::Less => {
10986                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10987                            }
10988                            Ordering::Greater => {
10989                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10990                            }
10991                        };
10992                        if rename_selection_range.end > old_name.len() {
10993                            editor.select_all(&SelectAll, window, cx);
10994                        } else {
10995                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10996                                s.select_ranges([rename_selection_range]);
10997                            });
10998                        }
10999                        editor
11000                    });
11001                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11002                        if e == &EditorEvent::Focused {
11003                            cx.emit(EditorEvent::FocusedIn)
11004                        }
11005                    })
11006                    .detach();
11007
11008                    let write_highlights =
11009                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11010                    let read_highlights =
11011                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11012                    let ranges = write_highlights
11013                        .iter()
11014                        .flat_map(|(_, ranges)| ranges.iter())
11015                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11016                        .cloned()
11017                        .collect();
11018
11019                    this.highlight_text::<Rename>(
11020                        ranges,
11021                        HighlightStyle {
11022                            fade_out: Some(0.6),
11023                            ..Default::default()
11024                        },
11025                        cx,
11026                    );
11027                    let rename_focus_handle = rename_editor.focus_handle(cx);
11028                    window.focus(&rename_focus_handle);
11029                    let block_id = this.insert_blocks(
11030                        [BlockProperties {
11031                            style: BlockStyle::Flex,
11032                            placement: BlockPlacement::Below(range.start),
11033                            height: 1,
11034                            render: Arc::new({
11035                                let rename_editor = rename_editor.clone();
11036                                move |cx: &mut BlockContext| {
11037                                    let mut text_style = cx.editor_style.text.clone();
11038                                    if let Some(highlight_style) = old_highlight_id
11039                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11040                                    {
11041                                        text_style = text_style.highlight(highlight_style);
11042                                    }
11043                                    div()
11044                                        .block_mouse_down()
11045                                        .pl(cx.anchor_x)
11046                                        .child(EditorElement::new(
11047                                            &rename_editor,
11048                                            EditorStyle {
11049                                                background: cx.theme().system().transparent,
11050                                                local_player: cx.editor_style.local_player,
11051                                                text: text_style,
11052                                                scrollbar_width: cx.editor_style.scrollbar_width,
11053                                                syntax: cx.editor_style.syntax.clone(),
11054                                                status: cx.editor_style.status.clone(),
11055                                                inlay_hints_style: HighlightStyle {
11056                                                    font_weight: Some(FontWeight::BOLD),
11057                                                    ..make_inlay_hints_style(cx.app)
11058                                                },
11059                                                inline_completion_styles: make_suggestion_styles(
11060                                                    cx.app,
11061                                                ),
11062                                                ..EditorStyle::default()
11063                                            },
11064                                        ))
11065                                        .into_any_element()
11066                                }
11067                            }),
11068                            priority: 0,
11069                        }],
11070                        Some(Autoscroll::fit()),
11071                        cx,
11072                    )[0];
11073                    this.pending_rename = Some(RenameState {
11074                        range,
11075                        old_name,
11076                        editor: rename_editor,
11077                        block_id,
11078                    });
11079                })?;
11080            }
11081
11082            Ok(())
11083        }))
11084    }
11085
11086    pub fn confirm_rename(
11087        &mut self,
11088        _: &ConfirmRename,
11089        window: &mut Window,
11090        cx: &mut Context<Self>,
11091    ) -> Option<Task<Result<()>>> {
11092        let rename = self.take_rename(false, window, cx)?;
11093        let workspace = self.workspace()?.downgrade();
11094        let (buffer, start) = self
11095            .buffer
11096            .read(cx)
11097            .text_anchor_for_position(rename.range.start, cx)?;
11098        let (end_buffer, _) = self
11099            .buffer
11100            .read(cx)
11101            .text_anchor_for_position(rename.range.end, cx)?;
11102        if buffer != end_buffer {
11103            return None;
11104        }
11105
11106        let old_name = rename.old_name;
11107        let new_name = rename.editor.read(cx).text(cx);
11108
11109        let rename = self.semantics_provider.as_ref()?.perform_rename(
11110            &buffer,
11111            start,
11112            new_name.clone(),
11113            cx,
11114        )?;
11115
11116        Some(cx.spawn_in(window, |editor, mut cx| async move {
11117            let project_transaction = rename.await?;
11118            Self::open_project_transaction(
11119                &editor,
11120                workspace,
11121                project_transaction,
11122                format!("Rename: {}{}", old_name, new_name),
11123                cx.clone(),
11124            )
11125            .await?;
11126
11127            editor.update(&mut cx, |editor, cx| {
11128                editor.refresh_document_highlights(cx);
11129            })?;
11130            Ok(())
11131        }))
11132    }
11133
11134    fn take_rename(
11135        &mut self,
11136        moving_cursor: bool,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) -> Option<RenameState> {
11140        let rename = self.pending_rename.take()?;
11141        if rename.editor.focus_handle(cx).is_focused(window) {
11142            window.focus(&self.focus_handle);
11143        }
11144
11145        self.remove_blocks(
11146            [rename.block_id].into_iter().collect(),
11147            Some(Autoscroll::fit()),
11148            cx,
11149        );
11150        self.clear_highlights::<Rename>(cx);
11151        self.show_local_selections = true;
11152
11153        if moving_cursor {
11154            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11155                editor.selections.newest::<usize>(cx).head()
11156            });
11157
11158            // Update the selection to match the position of the selection inside
11159            // the rename editor.
11160            let snapshot = self.buffer.read(cx).read(cx);
11161            let rename_range = rename.range.to_offset(&snapshot);
11162            let cursor_in_editor = snapshot
11163                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11164                .min(rename_range.end);
11165            drop(snapshot);
11166
11167            self.change_selections(None, window, cx, |s| {
11168                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11169            });
11170        } else {
11171            self.refresh_document_highlights(cx);
11172        }
11173
11174        Some(rename)
11175    }
11176
11177    pub fn pending_rename(&self) -> Option<&RenameState> {
11178        self.pending_rename.as_ref()
11179    }
11180
11181    fn format(
11182        &mut self,
11183        _: &Format,
11184        window: &mut Window,
11185        cx: &mut Context<Self>,
11186    ) -> Option<Task<Result<()>>> {
11187        let project = match &self.project {
11188            Some(project) => project.clone(),
11189            None => return None,
11190        };
11191
11192        Some(self.perform_format(
11193            project,
11194            FormatTrigger::Manual,
11195            FormatTarget::Buffers,
11196            window,
11197            cx,
11198        ))
11199    }
11200
11201    fn format_selections(
11202        &mut self,
11203        _: &FormatSelections,
11204        window: &mut Window,
11205        cx: &mut Context<Self>,
11206    ) -> Option<Task<Result<()>>> {
11207        let project = match &self.project {
11208            Some(project) => project.clone(),
11209            None => return None,
11210        };
11211
11212        let ranges = self
11213            .selections
11214            .all_adjusted(cx)
11215            .into_iter()
11216            .map(|selection| selection.range())
11217            .collect_vec();
11218
11219        Some(self.perform_format(
11220            project,
11221            FormatTrigger::Manual,
11222            FormatTarget::Ranges(ranges),
11223            window,
11224            cx,
11225        ))
11226    }
11227
11228    fn perform_format(
11229        &mut self,
11230        project: Entity<Project>,
11231        trigger: FormatTrigger,
11232        target: FormatTarget,
11233        window: &mut Window,
11234        cx: &mut Context<Self>,
11235    ) -> Task<Result<()>> {
11236        let buffer = self.buffer.clone();
11237        let (buffers, target) = match target {
11238            FormatTarget::Buffers => {
11239                let mut buffers = buffer.read(cx).all_buffers();
11240                if trigger == FormatTrigger::Save {
11241                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11242                }
11243                (buffers, LspFormatTarget::Buffers)
11244            }
11245            FormatTarget::Ranges(selection_ranges) => {
11246                let multi_buffer = buffer.read(cx);
11247                let snapshot = multi_buffer.read(cx);
11248                let mut buffers = HashSet::default();
11249                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11250                    BTreeMap::new();
11251                for selection_range in selection_ranges {
11252                    for (buffer, buffer_range, _) in
11253                        snapshot.range_to_buffer_ranges(selection_range)
11254                    {
11255                        let buffer_id = buffer.remote_id();
11256                        let start = buffer.anchor_before(buffer_range.start);
11257                        let end = buffer.anchor_after(buffer_range.end);
11258                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11259                        buffer_id_to_ranges
11260                            .entry(buffer_id)
11261                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11262                            .or_insert_with(|| vec![start..end]);
11263                    }
11264                }
11265                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11266            }
11267        };
11268
11269        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11270        let format = project.update(cx, |project, cx| {
11271            project.format(buffers, target, true, trigger, cx)
11272        });
11273
11274        cx.spawn_in(window, |_, mut cx| async move {
11275            let transaction = futures::select_biased! {
11276                () = timeout => {
11277                    log::warn!("timed out waiting for formatting");
11278                    None
11279                }
11280                transaction = format.log_err().fuse() => transaction,
11281            };
11282
11283            buffer
11284                .update(&mut cx, |buffer, cx| {
11285                    if let Some(transaction) = transaction {
11286                        if !buffer.is_singleton() {
11287                            buffer.push_transaction(&transaction.0, cx);
11288                        }
11289                    }
11290
11291                    cx.notify();
11292                })
11293                .ok();
11294
11295            Ok(())
11296        })
11297    }
11298
11299    fn restart_language_server(
11300        &mut self,
11301        _: &RestartLanguageServer,
11302        _: &mut Window,
11303        cx: &mut Context<Self>,
11304    ) {
11305        if let Some(project) = self.project.clone() {
11306            self.buffer.update(cx, |multi_buffer, cx| {
11307                project.update(cx, |project, cx| {
11308                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11309                });
11310            })
11311        }
11312    }
11313
11314    fn cancel_language_server_work(
11315        &mut self,
11316        _: &actions::CancelLanguageServerWork,
11317        _: &mut Window,
11318        cx: &mut Context<Self>,
11319    ) {
11320        if let Some(project) = self.project.clone() {
11321            self.buffer.update(cx, |multi_buffer, cx| {
11322                project.update(cx, |project, cx| {
11323                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11324                });
11325            })
11326        }
11327    }
11328
11329    fn show_character_palette(
11330        &mut self,
11331        _: &ShowCharacterPalette,
11332        window: &mut Window,
11333        _: &mut Context<Self>,
11334    ) {
11335        window.show_character_palette();
11336    }
11337
11338    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11339        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11340            let buffer = self.buffer.read(cx).snapshot(cx);
11341            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11342            let is_valid = buffer
11343                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11344                .any(|entry| {
11345                    entry.diagnostic.is_primary
11346                        && !entry.range.is_empty()
11347                        && entry.range.start == primary_range_start
11348                        && entry.diagnostic.message == active_diagnostics.primary_message
11349                });
11350
11351            if is_valid != active_diagnostics.is_valid {
11352                active_diagnostics.is_valid = is_valid;
11353                let mut new_styles = HashMap::default();
11354                for (block_id, diagnostic) in &active_diagnostics.blocks {
11355                    new_styles.insert(
11356                        *block_id,
11357                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11358                    );
11359                }
11360                self.display_map.update(cx, |display_map, _cx| {
11361                    display_map.replace_blocks(new_styles)
11362                });
11363            }
11364        }
11365    }
11366
11367    fn activate_diagnostics(
11368        &mut self,
11369        buffer_id: BufferId,
11370        group_id: usize,
11371        window: &mut Window,
11372        cx: &mut Context<Self>,
11373    ) {
11374        self.dismiss_diagnostics(cx);
11375        let snapshot = self.snapshot(window, cx);
11376        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11377            let buffer = self.buffer.read(cx).snapshot(cx);
11378
11379            let mut primary_range = None;
11380            let mut primary_message = None;
11381            let diagnostic_group = buffer
11382                .diagnostic_group(buffer_id, group_id)
11383                .filter_map(|entry| {
11384                    let start = entry.range.start;
11385                    let end = entry.range.end;
11386                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11387                        && (start.row == end.row
11388                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11389                    {
11390                        return None;
11391                    }
11392                    if entry.diagnostic.is_primary {
11393                        primary_range = Some(entry.range.clone());
11394                        primary_message = Some(entry.diagnostic.message.clone());
11395                    }
11396                    Some(entry)
11397                })
11398                .collect::<Vec<_>>();
11399            let primary_range = primary_range?;
11400            let primary_message = primary_message?;
11401
11402            let blocks = display_map
11403                .insert_blocks(
11404                    diagnostic_group.iter().map(|entry| {
11405                        let diagnostic = entry.diagnostic.clone();
11406                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11407                        BlockProperties {
11408                            style: BlockStyle::Fixed,
11409                            placement: BlockPlacement::Below(
11410                                buffer.anchor_after(entry.range.start),
11411                            ),
11412                            height: message_height,
11413                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11414                            priority: 0,
11415                        }
11416                    }),
11417                    cx,
11418                )
11419                .into_iter()
11420                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11421                .collect();
11422
11423            Some(ActiveDiagnosticGroup {
11424                primary_range: buffer.anchor_before(primary_range.start)
11425                    ..buffer.anchor_after(primary_range.end),
11426                primary_message,
11427                group_id,
11428                blocks,
11429                is_valid: true,
11430            })
11431        });
11432    }
11433
11434    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11435        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11436            self.display_map.update(cx, |display_map, cx| {
11437                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11438            });
11439            cx.notify();
11440        }
11441    }
11442
11443    pub fn set_selections_from_remote(
11444        &mut self,
11445        selections: Vec<Selection<Anchor>>,
11446        pending_selection: Option<Selection<Anchor>>,
11447        window: &mut Window,
11448        cx: &mut Context<Self>,
11449    ) {
11450        let old_cursor_position = self.selections.newest_anchor().head();
11451        self.selections.change_with(cx, |s| {
11452            s.select_anchors(selections);
11453            if let Some(pending_selection) = pending_selection {
11454                s.set_pending(pending_selection, SelectMode::Character);
11455            } else {
11456                s.clear_pending();
11457            }
11458        });
11459        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11460    }
11461
11462    fn push_to_selection_history(&mut self) {
11463        self.selection_history.push(SelectionHistoryEntry {
11464            selections: self.selections.disjoint_anchors(),
11465            select_next_state: self.select_next_state.clone(),
11466            select_prev_state: self.select_prev_state.clone(),
11467            add_selections_state: self.add_selections_state.clone(),
11468        });
11469    }
11470
11471    pub fn transact(
11472        &mut self,
11473        window: &mut Window,
11474        cx: &mut Context<Self>,
11475        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11476    ) -> Option<TransactionId> {
11477        self.start_transaction_at(Instant::now(), window, cx);
11478        update(self, window, cx);
11479        self.end_transaction_at(Instant::now(), cx)
11480    }
11481
11482    pub fn start_transaction_at(
11483        &mut self,
11484        now: Instant,
11485        window: &mut Window,
11486        cx: &mut Context<Self>,
11487    ) {
11488        self.end_selection(window, cx);
11489        if let Some(tx_id) = self
11490            .buffer
11491            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11492        {
11493            self.selection_history
11494                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11495            cx.emit(EditorEvent::TransactionBegun {
11496                transaction_id: tx_id,
11497            })
11498        }
11499    }
11500
11501    pub fn end_transaction_at(
11502        &mut self,
11503        now: Instant,
11504        cx: &mut Context<Self>,
11505    ) -> Option<TransactionId> {
11506        if let Some(transaction_id) = self
11507            .buffer
11508            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11509        {
11510            if let Some((_, end_selections)) =
11511                self.selection_history.transaction_mut(transaction_id)
11512            {
11513                *end_selections = Some(self.selections.disjoint_anchors());
11514            } else {
11515                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11516            }
11517
11518            cx.emit(EditorEvent::Edited { transaction_id });
11519            Some(transaction_id)
11520        } else {
11521            None
11522        }
11523    }
11524
11525    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11526        if self.selection_mark_mode {
11527            self.change_selections(None, window, cx, |s| {
11528                s.move_with(|_, sel| {
11529                    sel.collapse_to(sel.head(), SelectionGoal::None);
11530                });
11531            })
11532        }
11533        self.selection_mark_mode = true;
11534        cx.notify();
11535    }
11536
11537    pub fn swap_selection_ends(
11538        &mut self,
11539        _: &actions::SwapSelectionEnds,
11540        window: &mut Window,
11541        cx: &mut Context<Self>,
11542    ) {
11543        self.change_selections(None, window, cx, |s| {
11544            s.move_with(|_, sel| {
11545                if sel.start != sel.end {
11546                    sel.reversed = !sel.reversed
11547                }
11548            });
11549        });
11550        self.request_autoscroll(Autoscroll::newest(), cx);
11551        cx.notify();
11552    }
11553
11554    pub fn toggle_fold(
11555        &mut self,
11556        _: &actions::ToggleFold,
11557        window: &mut Window,
11558        cx: &mut Context<Self>,
11559    ) {
11560        if self.is_singleton(cx) {
11561            let selection = self.selections.newest::<Point>(cx);
11562
11563            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11564            let range = if selection.is_empty() {
11565                let point = selection.head().to_display_point(&display_map);
11566                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11567                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11568                    .to_point(&display_map);
11569                start..end
11570            } else {
11571                selection.range()
11572            };
11573            if display_map.folds_in_range(range).next().is_some() {
11574                self.unfold_lines(&Default::default(), window, cx)
11575            } else {
11576                self.fold(&Default::default(), window, cx)
11577            }
11578        } else {
11579            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11580            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11581                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11582                .map(|(snapshot, _, _)| snapshot.remote_id())
11583                .collect();
11584
11585            for buffer_id in buffer_ids {
11586                if self.is_buffer_folded(buffer_id, cx) {
11587                    self.unfold_buffer(buffer_id, cx);
11588                } else {
11589                    self.fold_buffer(buffer_id, cx);
11590                }
11591            }
11592        }
11593    }
11594
11595    pub fn toggle_fold_recursive(
11596        &mut self,
11597        _: &actions::ToggleFoldRecursive,
11598        window: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) {
11601        let selection = self.selections.newest::<Point>(cx);
11602
11603        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11604        let range = if selection.is_empty() {
11605            let point = selection.head().to_display_point(&display_map);
11606            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11607            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11608                .to_point(&display_map);
11609            start..end
11610        } else {
11611            selection.range()
11612        };
11613        if display_map.folds_in_range(range).next().is_some() {
11614            self.unfold_recursive(&Default::default(), window, cx)
11615        } else {
11616            self.fold_recursive(&Default::default(), window, cx)
11617        }
11618    }
11619
11620    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11621        if self.is_singleton(cx) {
11622            let mut to_fold = Vec::new();
11623            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11624            let selections = self.selections.all_adjusted(cx);
11625
11626            for selection in selections {
11627                let range = selection.range().sorted();
11628                let buffer_start_row = range.start.row;
11629
11630                if range.start.row != range.end.row {
11631                    let mut found = false;
11632                    let mut row = range.start.row;
11633                    while row <= range.end.row {
11634                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11635                        {
11636                            found = true;
11637                            row = crease.range().end.row + 1;
11638                            to_fold.push(crease);
11639                        } else {
11640                            row += 1
11641                        }
11642                    }
11643                    if found {
11644                        continue;
11645                    }
11646                }
11647
11648                for row in (0..=range.start.row).rev() {
11649                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11650                        if crease.range().end.row >= buffer_start_row {
11651                            to_fold.push(crease);
11652                            if row <= range.start.row {
11653                                break;
11654                            }
11655                        }
11656                    }
11657                }
11658            }
11659
11660            self.fold_creases(to_fold, true, window, cx);
11661        } else {
11662            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11663
11664            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11665                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11666                .map(|(snapshot, _, _)| snapshot.remote_id())
11667                .collect();
11668            for buffer_id in buffer_ids {
11669                self.fold_buffer(buffer_id, cx);
11670            }
11671        }
11672    }
11673
11674    fn fold_at_level(
11675        &mut self,
11676        fold_at: &FoldAtLevel,
11677        window: &mut Window,
11678        cx: &mut Context<Self>,
11679    ) {
11680        if !self.buffer.read(cx).is_singleton() {
11681            return;
11682        }
11683
11684        let fold_at_level = fold_at.level;
11685        let snapshot = self.buffer.read(cx).snapshot(cx);
11686        let mut to_fold = Vec::new();
11687        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11688
11689        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11690            while start_row < end_row {
11691                match self
11692                    .snapshot(window, cx)
11693                    .crease_for_buffer_row(MultiBufferRow(start_row))
11694                {
11695                    Some(crease) => {
11696                        let nested_start_row = crease.range().start.row + 1;
11697                        let nested_end_row = crease.range().end.row;
11698
11699                        if current_level < fold_at_level {
11700                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11701                        } else if current_level == fold_at_level {
11702                            to_fold.push(crease);
11703                        }
11704
11705                        start_row = nested_end_row + 1;
11706                    }
11707                    None => start_row += 1,
11708                }
11709            }
11710        }
11711
11712        self.fold_creases(to_fold, true, window, cx);
11713    }
11714
11715    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11716        if self.buffer.read(cx).is_singleton() {
11717            let mut fold_ranges = Vec::new();
11718            let snapshot = self.buffer.read(cx).snapshot(cx);
11719
11720            for row in 0..snapshot.max_row().0 {
11721                if let Some(foldable_range) = self
11722                    .snapshot(window, cx)
11723                    .crease_for_buffer_row(MultiBufferRow(row))
11724                {
11725                    fold_ranges.push(foldable_range);
11726                }
11727            }
11728
11729            self.fold_creases(fold_ranges, true, window, cx);
11730        } else {
11731            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11732                editor
11733                    .update_in(&mut cx, |editor, _, cx| {
11734                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11735                            editor.fold_buffer(buffer_id, cx);
11736                        }
11737                    })
11738                    .ok();
11739            });
11740        }
11741    }
11742
11743    pub fn fold_function_bodies(
11744        &mut self,
11745        _: &actions::FoldFunctionBodies,
11746        window: &mut Window,
11747        cx: &mut Context<Self>,
11748    ) {
11749        let snapshot = self.buffer.read(cx).snapshot(cx);
11750
11751        let ranges = snapshot
11752            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11753            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11754            .collect::<Vec<_>>();
11755
11756        let creases = ranges
11757            .into_iter()
11758            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11759            .collect();
11760
11761        self.fold_creases(creases, true, window, cx);
11762    }
11763
11764    pub fn fold_recursive(
11765        &mut self,
11766        _: &actions::FoldRecursive,
11767        window: &mut Window,
11768        cx: &mut Context<Self>,
11769    ) {
11770        let mut to_fold = Vec::new();
11771        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11772        let selections = self.selections.all_adjusted(cx);
11773
11774        for selection in selections {
11775            let range = selection.range().sorted();
11776            let buffer_start_row = range.start.row;
11777
11778            if range.start.row != range.end.row {
11779                let mut found = false;
11780                for row in range.start.row..=range.end.row {
11781                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11782                        found = true;
11783                        to_fold.push(crease);
11784                    }
11785                }
11786                if found {
11787                    continue;
11788                }
11789            }
11790
11791            for row in (0..=range.start.row).rev() {
11792                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11793                    if crease.range().end.row >= buffer_start_row {
11794                        to_fold.push(crease);
11795                    } else {
11796                        break;
11797                    }
11798                }
11799            }
11800        }
11801
11802        self.fold_creases(to_fold, true, window, cx);
11803    }
11804
11805    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11806        let buffer_row = fold_at.buffer_row;
11807        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11808
11809        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11810            let autoscroll = self
11811                .selections
11812                .all::<Point>(cx)
11813                .iter()
11814                .any(|selection| crease.range().overlaps(&selection.range()));
11815
11816            self.fold_creases(vec![crease], autoscroll, window, cx);
11817        }
11818    }
11819
11820    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11821        if self.is_singleton(cx) {
11822            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11823            let buffer = &display_map.buffer_snapshot;
11824            let selections = self.selections.all::<Point>(cx);
11825            let ranges = selections
11826                .iter()
11827                .map(|s| {
11828                    let range = s.display_range(&display_map).sorted();
11829                    let mut start = range.start.to_point(&display_map);
11830                    let mut end = range.end.to_point(&display_map);
11831                    start.column = 0;
11832                    end.column = buffer.line_len(MultiBufferRow(end.row));
11833                    start..end
11834                })
11835                .collect::<Vec<_>>();
11836
11837            self.unfold_ranges(&ranges, true, true, cx);
11838        } else {
11839            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11840            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11841                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11842                .map(|(snapshot, _, _)| snapshot.remote_id())
11843                .collect();
11844            for buffer_id in buffer_ids {
11845                self.unfold_buffer(buffer_id, cx);
11846            }
11847        }
11848    }
11849
11850    pub fn unfold_recursive(
11851        &mut self,
11852        _: &UnfoldRecursive,
11853        _window: &mut Window,
11854        cx: &mut Context<Self>,
11855    ) {
11856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11857        let selections = self.selections.all::<Point>(cx);
11858        let ranges = selections
11859            .iter()
11860            .map(|s| {
11861                let mut range = s.display_range(&display_map).sorted();
11862                *range.start.column_mut() = 0;
11863                *range.end.column_mut() = display_map.line_len(range.end.row());
11864                let start = range.start.to_point(&display_map);
11865                let end = range.end.to_point(&display_map);
11866                start..end
11867            })
11868            .collect::<Vec<_>>();
11869
11870        self.unfold_ranges(&ranges, true, true, cx);
11871    }
11872
11873    pub fn unfold_at(
11874        &mut self,
11875        unfold_at: &UnfoldAt,
11876        _window: &mut Window,
11877        cx: &mut Context<Self>,
11878    ) {
11879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11880
11881        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11882            ..Point::new(
11883                unfold_at.buffer_row.0,
11884                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11885            );
11886
11887        let autoscroll = self
11888            .selections
11889            .all::<Point>(cx)
11890            .iter()
11891            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11892
11893        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11894    }
11895
11896    pub fn unfold_all(
11897        &mut self,
11898        _: &actions::UnfoldAll,
11899        _window: &mut Window,
11900        cx: &mut Context<Self>,
11901    ) {
11902        if self.buffer.read(cx).is_singleton() {
11903            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11904            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11905        } else {
11906            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11907                editor
11908                    .update(&mut cx, |editor, cx| {
11909                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11910                            editor.unfold_buffer(buffer_id, cx);
11911                        }
11912                    })
11913                    .ok();
11914            });
11915        }
11916    }
11917
11918    pub fn fold_selected_ranges(
11919        &mut self,
11920        _: &FoldSelectedRanges,
11921        window: &mut Window,
11922        cx: &mut Context<Self>,
11923    ) {
11924        let selections = self.selections.all::<Point>(cx);
11925        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11926        let line_mode = self.selections.line_mode;
11927        let ranges = selections
11928            .into_iter()
11929            .map(|s| {
11930                if line_mode {
11931                    let start = Point::new(s.start.row, 0);
11932                    let end = Point::new(
11933                        s.end.row,
11934                        display_map
11935                            .buffer_snapshot
11936                            .line_len(MultiBufferRow(s.end.row)),
11937                    );
11938                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11939                } else {
11940                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11941                }
11942            })
11943            .collect::<Vec<_>>();
11944        self.fold_creases(ranges, true, window, cx);
11945    }
11946
11947    pub fn fold_ranges<T: ToOffset + Clone>(
11948        &mut self,
11949        ranges: Vec<Range<T>>,
11950        auto_scroll: bool,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) {
11954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11955        let ranges = ranges
11956            .into_iter()
11957            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11958            .collect::<Vec<_>>();
11959        self.fold_creases(ranges, auto_scroll, window, cx);
11960    }
11961
11962    pub fn fold_creases<T: ToOffset + Clone>(
11963        &mut self,
11964        creases: Vec<Crease<T>>,
11965        auto_scroll: bool,
11966        window: &mut Window,
11967        cx: &mut Context<Self>,
11968    ) {
11969        if creases.is_empty() {
11970            return;
11971        }
11972
11973        let mut buffers_affected = HashSet::default();
11974        let multi_buffer = self.buffer().read(cx);
11975        for crease in &creases {
11976            if let Some((_, buffer, _)) =
11977                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11978            {
11979                buffers_affected.insert(buffer.read(cx).remote_id());
11980            };
11981        }
11982
11983        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11984
11985        if auto_scroll {
11986            self.request_autoscroll(Autoscroll::fit(), cx);
11987        }
11988
11989        cx.notify();
11990
11991        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11992            // Clear diagnostics block when folding a range that contains it.
11993            let snapshot = self.snapshot(window, cx);
11994            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11995                drop(snapshot);
11996                self.active_diagnostics = Some(active_diagnostics);
11997                self.dismiss_diagnostics(cx);
11998            } else {
11999                self.active_diagnostics = Some(active_diagnostics);
12000            }
12001        }
12002
12003        self.scrollbar_marker_state.dirty = true;
12004    }
12005
12006    /// Removes any folds whose ranges intersect any of the given ranges.
12007    pub fn unfold_ranges<T: ToOffset + Clone>(
12008        &mut self,
12009        ranges: &[Range<T>],
12010        inclusive: bool,
12011        auto_scroll: bool,
12012        cx: &mut Context<Self>,
12013    ) {
12014        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12015            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12016        });
12017    }
12018
12019    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12020        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12021            return;
12022        }
12023        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12024        self.display_map
12025            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12026        cx.emit(EditorEvent::BufferFoldToggled {
12027            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12028            folded: true,
12029        });
12030        cx.notify();
12031    }
12032
12033    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12034        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12035            return;
12036        }
12037        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12038        self.display_map.update(cx, |display_map, cx| {
12039            display_map.unfold_buffer(buffer_id, cx);
12040        });
12041        cx.emit(EditorEvent::BufferFoldToggled {
12042            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12043            folded: false,
12044        });
12045        cx.notify();
12046    }
12047
12048    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12049        self.display_map.read(cx).is_buffer_folded(buffer)
12050    }
12051
12052    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12053        self.display_map.read(cx).folded_buffers()
12054    }
12055
12056    /// Removes any folds with the given ranges.
12057    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12058        &mut self,
12059        ranges: &[Range<T>],
12060        type_id: TypeId,
12061        auto_scroll: bool,
12062        cx: &mut Context<Self>,
12063    ) {
12064        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12065            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12066        });
12067    }
12068
12069    fn remove_folds_with<T: ToOffset + Clone>(
12070        &mut self,
12071        ranges: &[Range<T>],
12072        auto_scroll: bool,
12073        cx: &mut Context<Self>,
12074        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12075    ) {
12076        if ranges.is_empty() {
12077            return;
12078        }
12079
12080        let mut buffers_affected = HashSet::default();
12081        let multi_buffer = self.buffer().read(cx);
12082        for range in ranges {
12083            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12084                buffers_affected.insert(buffer.read(cx).remote_id());
12085            };
12086        }
12087
12088        self.display_map.update(cx, update);
12089
12090        if auto_scroll {
12091            self.request_autoscroll(Autoscroll::fit(), cx);
12092        }
12093
12094        cx.notify();
12095        self.scrollbar_marker_state.dirty = true;
12096        self.active_indent_guides_state.dirty = true;
12097    }
12098
12099    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12100        self.display_map.read(cx).fold_placeholder.clone()
12101    }
12102
12103    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12104        self.buffer.update(cx, |buffer, cx| {
12105            buffer.set_all_diff_hunks_expanded(cx);
12106        });
12107    }
12108
12109    pub fn expand_all_diff_hunks(
12110        &mut self,
12111        _: &ExpandAllHunkDiffs,
12112        _window: &mut Window,
12113        cx: &mut Context<Self>,
12114    ) {
12115        self.buffer.update(cx, |buffer, cx| {
12116            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12117        });
12118    }
12119
12120    pub fn toggle_selected_diff_hunks(
12121        &mut self,
12122        _: &ToggleSelectedDiffHunks,
12123        _window: &mut Window,
12124        cx: &mut Context<Self>,
12125    ) {
12126        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12127        self.toggle_diff_hunks_in_ranges(ranges, cx);
12128    }
12129
12130    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12131        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12132        self.buffer
12133            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12134    }
12135
12136    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12137        self.buffer.update(cx, |buffer, cx| {
12138            let ranges = vec![Anchor::min()..Anchor::max()];
12139            if !buffer.all_diff_hunks_expanded()
12140                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12141            {
12142                buffer.collapse_diff_hunks(ranges, cx);
12143                true
12144            } else {
12145                false
12146            }
12147        })
12148    }
12149
12150    fn toggle_diff_hunks_in_ranges(
12151        &mut self,
12152        ranges: Vec<Range<Anchor>>,
12153        cx: &mut Context<'_, Editor>,
12154    ) {
12155        self.buffer.update(cx, |buffer, cx| {
12156            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12157                buffer.collapse_diff_hunks(ranges, cx)
12158            } else {
12159                buffer.expand_diff_hunks(ranges, cx)
12160            }
12161        })
12162    }
12163
12164    pub(crate) fn apply_all_diff_hunks(
12165        &mut self,
12166        _: &ApplyAllDiffHunks,
12167        window: &mut Window,
12168        cx: &mut Context<Self>,
12169    ) {
12170        let buffers = self.buffer.read(cx).all_buffers();
12171        for branch_buffer in buffers {
12172            branch_buffer.update(cx, |branch_buffer, cx| {
12173                branch_buffer.merge_into_base(Vec::new(), cx);
12174            });
12175        }
12176
12177        if let Some(project) = self.project.clone() {
12178            self.save(true, project, window, cx).detach_and_log_err(cx);
12179        }
12180    }
12181
12182    pub(crate) fn apply_selected_diff_hunks(
12183        &mut self,
12184        _: &ApplyDiffHunk,
12185        window: &mut Window,
12186        cx: &mut Context<Self>,
12187    ) {
12188        let snapshot = self.snapshot(window, cx);
12189        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12190        let mut ranges_by_buffer = HashMap::default();
12191        self.transact(window, cx, |editor, _window, cx| {
12192            for hunk in hunks {
12193                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12194                    ranges_by_buffer
12195                        .entry(buffer.clone())
12196                        .or_insert_with(Vec::new)
12197                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12198                }
12199            }
12200
12201            for (buffer, ranges) in ranges_by_buffer {
12202                buffer.update(cx, |buffer, cx| {
12203                    buffer.merge_into_base(ranges, cx);
12204                });
12205            }
12206        });
12207
12208        if let Some(project) = self.project.clone() {
12209            self.save(true, project, window, cx).detach_and_log_err(cx);
12210        }
12211    }
12212
12213    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12214        if hovered != self.gutter_hovered {
12215            self.gutter_hovered = hovered;
12216            cx.notify();
12217        }
12218    }
12219
12220    pub fn insert_blocks(
12221        &mut self,
12222        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12223        autoscroll: Option<Autoscroll>,
12224        cx: &mut Context<Self>,
12225    ) -> Vec<CustomBlockId> {
12226        let blocks = self
12227            .display_map
12228            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12229        if let Some(autoscroll) = autoscroll {
12230            self.request_autoscroll(autoscroll, cx);
12231        }
12232        cx.notify();
12233        blocks
12234    }
12235
12236    pub fn resize_blocks(
12237        &mut self,
12238        heights: HashMap<CustomBlockId, u32>,
12239        autoscroll: Option<Autoscroll>,
12240        cx: &mut Context<Self>,
12241    ) {
12242        self.display_map
12243            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12244        if let Some(autoscroll) = autoscroll {
12245            self.request_autoscroll(autoscroll, cx);
12246        }
12247        cx.notify();
12248    }
12249
12250    pub fn replace_blocks(
12251        &mut self,
12252        renderers: HashMap<CustomBlockId, RenderBlock>,
12253        autoscroll: Option<Autoscroll>,
12254        cx: &mut Context<Self>,
12255    ) {
12256        self.display_map
12257            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12258        if let Some(autoscroll) = autoscroll {
12259            self.request_autoscroll(autoscroll, cx);
12260        }
12261        cx.notify();
12262    }
12263
12264    pub fn remove_blocks(
12265        &mut self,
12266        block_ids: HashSet<CustomBlockId>,
12267        autoscroll: Option<Autoscroll>,
12268        cx: &mut Context<Self>,
12269    ) {
12270        self.display_map.update(cx, |display_map, cx| {
12271            display_map.remove_blocks(block_ids, cx)
12272        });
12273        if let Some(autoscroll) = autoscroll {
12274            self.request_autoscroll(autoscroll, cx);
12275        }
12276        cx.notify();
12277    }
12278
12279    pub fn row_for_block(
12280        &self,
12281        block_id: CustomBlockId,
12282        cx: &mut Context<Self>,
12283    ) -> Option<DisplayRow> {
12284        self.display_map
12285            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12286    }
12287
12288    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12289        self.focused_block = Some(focused_block);
12290    }
12291
12292    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12293        self.focused_block.take()
12294    }
12295
12296    pub fn insert_creases(
12297        &mut self,
12298        creases: impl IntoIterator<Item = Crease<Anchor>>,
12299        cx: &mut Context<Self>,
12300    ) -> Vec<CreaseId> {
12301        self.display_map
12302            .update(cx, |map, cx| map.insert_creases(creases, cx))
12303    }
12304
12305    pub fn remove_creases(
12306        &mut self,
12307        ids: impl IntoIterator<Item = CreaseId>,
12308        cx: &mut Context<Self>,
12309    ) {
12310        self.display_map
12311            .update(cx, |map, cx| map.remove_creases(ids, cx));
12312    }
12313
12314    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12315        self.display_map
12316            .update(cx, |map, cx| map.snapshot(cx))
12317            .longest_row()
12318    }
12319
12320    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12321        self.display_map
12322            .update(cx, |map, cx| map.snapshot(cx))
12323            .max_point()
12324    }
12325
12326    pub fn text(&self, cx: &App) -> String {
12327        self.buffer.read(cx).read(cx).text()
12328    }
12329
12330    pub fn is_empty(&self, cx: &App) -> bool {
12331        self.buffer.read(cx).read(cx).is_empty()
12332    }
12333
12334    pub fn text_option(&self, cx: &App) -> Option<String> {
12335        let text = self.text(cx);
12336        let text = text.trim();
12337
12338        if text.is_empty() {
12339            return None;
12340        }
12341
12342        Some(text.to_string())
12343    }
12344
12345    pub fn set_text(
12346        &mut self,
12347        text: impl Into<Arc<str>>,
12348        window: &mut Window,
12349        cx: &mut Context<Self>,
12350    ) {
12351        self.transact(window, cx, |this, _, cx| {
12352            this.buffer
12353                .read(cx)
12354                .as_singleton()
12355                .expect("you can only call set_text on editors for singleton buffers")
12356                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12357        });
12358    }
12359
12360    pub fn display_text(&self, cx: &mut App) -> String {
12361        self.display_map
12362            .update(cx, |map, cx| map.snapshot(cx))
12363            .text()
12364    }
12365
12366    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12367        let mut wrap_guides = smallvec::smallvec![];
12368
12369        if self.show_wrap_guides == Some(false) {
12370            return wrap_guides;
12371        }
12372
12373        let settings = self.buffer.read(cx).settings_at(0, cx);
12374        if settings.show_wrap_guides {
12375            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12376                wrap_guides.push((soft_wrap as usize, true));
12377            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12378                wrap_guides.push((soft_wrap as usize, true));
12379            }
12380            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12381        }
12382
12383        wrap_guides
12384    }
12385
12386    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12387        let settings = self.buffer.read(cx).settings_at(0, cx);
12388        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12389        match mode {
12390            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12391                SoftWrap::None
12392            }
12393            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12394            language_settings::SoftWrap::PreferredLineLength => {
12395                SoftWrap::Column(settings.preferred_line_length)
12396            }
12397            language_settings::SoftWrap::Bounded => {
12398                SoftWrap::Bounded(settings.preferred_line_length)
12399            }
12400        }
12401    }
12402
12403    pub fn set_soft_wrap_mode(
12404        &mut self,
12405        mode: language_settings::SoftWrap,
12406
12407        cx: &mut Context<Self>,
12408    ) {
12409        self.soft_wrap_mode_override = Some(mode);
12410        cx.notify();
12411    }
12412
12413    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12414        self.text_style_refinement = Some(style);
12415    }
12416
12417    /// called by the Element so we know what style we were most recently rendered with.
12418    pub(crate) fn set_style(
12419        &mut self,
12420        style: EditorStyle,
12421        window: &mut Window,
12422        cx: &mut Context<Self>,
12423    ) {
12424        let rem_size = window.rem_size();
12425        self.display_map.update(cx, |map, cx| {
12426            map.set_font(
12427                style.text.font(),
12428                style.text.font_size.to_pixels(rem_size),
12429                cx,
12430            )
12431        });
12432        self.style = Some(style);
12433    }
12434
12435    pub fn style(&self) -> Option<&EditorStyle> {
12436        self.style.as_ref()
12437    }
12438
12439    // Called by the element. This method is not designed to be called outside of the editor
12440    // element's layout code because it does not notify when rewrapping is computed synchronously.
12441    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12442        self.display_map
12443            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12444    }
12445
12446    pub fn set_soft_wrap(&mut self) {
12447        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12448    }
12449
12450    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12451        if self.soft_wrap_mode_override.is_some() {
12452            self.soft_wrap_mode_override.take();
12453        } else {
12454            let soft_wrap = match self.soft_wrap_mode(cx) {
12455                SoftWrap::GitDiff => return,
12456                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12457                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12458                    language_settings::SoftWrap::None
12459                }
12460            };
12461            self.soft_wrap_mode_override = Some(soft_wrap);
12462        }
12463        cx.notify();
12464    }
12465
12466    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12467        let Some(workspace) = self.workspace() else {
12468            return;
12469        };
12470        let fs = workspace.read(cx).app_state().fs.clone();
12471        let current_show = TabBarSettings::get_global(cx).show;
12472        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12473            setting.show = Some(!current_show);
12474        });
12475    }
12476
12477    pub fn toggle_indent_guides(
12478        &mut self,
12479        _: &ToggleIndentGuides,
12480        _: &mut Window,
12481        cx: &mut Context<Self>,
12482    ) {
12483        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12484            self.buffer
12485                .read(cx)
12486                .settings_at(0, cx)
12487                .indent_guides
12488                .enabled
12489        });
12490        self.show_indent_guides = Some(!currently_enabled);
12491        cx.notify();
12492    }
12493
12494    fn should_show_indent_guides(&self) -> Option<bool> {
12495        self.show_indent_guides
12496    }
12497
12498    pub fn toggle_line_numbers(
12499        &mut self,
12500        _: &ToggleLineNumbers,
12501        _: &mut Window,
12502        cx: &mut Context<Self>,
12503    ) {
12504        let mut editor_settings = EditorSettings::get_global(cx).clone();
12505        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12506        EditorSettings::override_global(editor_settings, cx);
12507    }
12508
12509    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12510        self.use_relative_line_numbers
12511            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12512    }
12513
12514    pub fn toggle_relative_line_numbers(
12515        &mut self,
12516        _: &ToggleRelativeLineNumbers,
12517        _: &mut Window,
12518        cx: &mut Context<Self>,
12519    ) {
12520        let is_relative = self.should_use_relative_line_numbers(cx);
12521        self.set_relative_line_number(Some(!is_relative), cx)
12522    }
12523
12524    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12525        self.use_relative_line_numbers = is_relative;
12526        cx.notify();
12527    }
12528
12529    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12530        self.show_gutter = show_gutter;
12531        cx.notify();
12532    }
12533
12534    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12535        self.show_scrollbars = show_scrollbars;
12536        cx.notify();
12537    }
12538
12539    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12540        self.show_line_numbers = Some(show_line_numbers);
12541        cx.notify();
12542    }
12543
12544    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12545        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12546        cx.notify();
12547    }
12548
12549    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12550        self.show_code_actions = Some(show_code_actions);
12551        cx.notify();
12552    }
12553
12554    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12555        self.show_runnables = Some(show_runnables);
12556        cx.notify();
12557    }
12558
12559    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12560        if self.display_map.read(cx).masked != masked {
12561            self.display_map.update(cx, |map, _| map.masked = masked);
12562        }
12563        cx.notify()
12564    }
12565
12566    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12567        self.show_wrap_guides = Some(show_wrap_guides);
12568        cx.notify();
12569    }
12570
12571    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12572        self.show_indent_guides = Some(show_indent_guides);
12573        cx.notify();
12574    }
12575
12576    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12577        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12578            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12579                if let Some(dir) = file.abs_path(cx).parent() {
12580                    return Some(dir.to_owned());
12581                }
12582            }
12583
12584            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12585                return Some(project_path.path.to_path_buf());
12586            }
12587        }
12588
12589        None
12590    }
12591
12592    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12593        self.active_excerpt(cx)?
12594            .1
12595            .read(cx)
12596            .file()
12597            .and_then(|f| f.as_local())
12598    }
12599
12600    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12601        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12602            let project_path = buffer.read(cx).project_path(cx)?;
12603            let project = self.project.as_ref()?.read(cx);
12604            project.absolute_path(&project_path, cx)
12605        })
12606    }
12607
12608    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12609        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12610            let project_path = buffer.read(cx).project_path(cx)?;
12611            let project = self.project.as_ref()?.read(cx);
12612            let entry = project.entry_for_path(&project_path, cx)?;
12613            let path = entry.path.to_path_buf();
12614            Some(path)
12615        })
12616    }
12617
12618    pub fn reveal_in_finder(
12619        &mut self,
12620        _: &RevealInFileManager,
12621        _window: &mut Window,
12622        cx: &mut Context<Self>,
12623    ) {
12624        if let Some(target) = self.target_file(cx) {
12625            cx.reveal_path(&target.abs_path(cx));
12626        }
12627    }
12628
12629    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12630        if let Some(path) = self.target_file_abs_path(cx) {
12631            if let Some(path) = path.to_str() {
12632                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12633            }
12634        }
12635    }
12636
12637    pub fn copy_relative_path(
12638        &mut self,
12639        _: &CopyRelativePath,
12640        _window: &mut Window,
12641        cx: &mut Context<Self>,
12642    ) {
12643        if let Some(path) = self.target_file_path(cx) {
12644            if let Some(path) = path.to_str() {
12645                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12646            }
12647        }
12648    }
12649
12650    pub fn toggle_git_blame(
12651        &mut self,
12652        _: &ToggleGitBlame,
12653        window: &mut Window,
12654        cx: &mut Context<Self>,
12655    ) {
12656        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12657
12658        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12659            self.start_git_blame(true, window, cx);
12660        }
12661
12662        cx.notify();
12663    }
12664
12665    pub fn toggle_git_blame_inline(
12666        &mut self,
12667        _: &ToggleGitBlameInline,
12668        window: &mut Window,
12669        cx: &mut Context<Self>,
12670    ) {
12671        self.toggle_git_blame_inline_internal(true, window, cx);
12672        cx.notify();
12673    }
12674
12675    pub fn git_blame_inline_enabled(&self) -> bool {
12676        self.git_blame_inline_enabled
12677    }
12678
12679    pub fn toggle_selection_menu(
12680        &mut self,
12681        _: &ToggleSelectionMenu,
12682        _: &mut Window,
12683        cx: &mut Context<Self>,
12684    ) {
12685        self.show_selection_menu = self
12686            .show_selection_menu
12687            .map(|show_selections_menu| !show_selections_menu)
12688            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12689
12690        cx.notify();
12691    }
12692
12693    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12694        self.show_selection_menu
12695            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12696    }
12697
12698    fn start_git_blame(
12699        &mut self,
12700        user_triggered: bool,
12701        window: &mut Window,
12702        cx: &mut Context<Self>,
12703    ) {
12704        if let Some(project) = self.project.as_ref() {
12705            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12706                return;
12707            };
12708
12709            if buffer.read(cx).file().is_none() {
12710                return;
12711            }
12712
12713            let focused = self.focus_handle(cx).contains_focused(window, cx);
12714
12715            let project = project.clone();
12716            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12717            self.blame_subscription =
12718                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12719            self.blame = Some(blame);
12720        }
12721    }
12722
12723    fn toggle_git_blame_inline_internal(
12724        &mut self,
12725        user_triggered: bool,
12726        window: &mut Window,
12727        cx: &mut Context<Self>,
12728    ) {
12729        if self.git_blame_inline_enabled {
12730            self.git_blame_inline_enabled = false;
12731            self.show_git_blame_inline = false;
12732            self.show_git_blame_inline_delay_task.take();
12733        } else {
12734            self.git_blame_inline_enabled = true;
12735            self.start_git_blame_inline(user_triggered, window, cx);
12736        }
12737
12738        cx.notify();
12739    }
12740
12741    fn start_git_blame_inline(
12742        &mut self,
12743        user_triggered: bool,
12744        window: &mut Window,
12745        cx: &mut Context<Self>,
12746    ) {
12747        self.start_git_blame(user_triggered, window, cx);
12748
12749        if ProjectSettings::get_global(cx)
12750            .git
12751            .inline_blame_delay()
12752            .is_some()
12753        {
12754            self.start_inline_blame_timer(window, cx);
12755        } else {
12756            self.show_git_blame_inline = true
12757        }
12758    }
12759
12760    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12761        self.blame.as_ref()
12762    }
12763
12764    pub fn show_git_blame_gutter(&self) -> bool {
12765        self.show_git_blame_gutter
12766    }
12767
12768    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12769        self.show_git_blame_gutter && self.has_blame_entries(cx)
12770    }
12771
12772    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12773        self.show_git_blame_inline
12774            && self.focus_handle.is_focused(window)
12775            && !self.newest_selection_head_on_empty_line(cx)
12776            && self.has_blame_entries(cx)
12777    }
12778
12779    fn has_blame_entries(&self, cx: &App) -> bool {
12780        self.blame()
12781            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12782    }
12783
12784    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12785        let cursor_anchor = self.selections.newest_anchor().head();
12786
12787        let snapshot = self.buffer.read(cx).snapshot(cx);
12788        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12789
12790        snapshot.line_len(buffer_row) == 0
12791    }
12792
12793    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12794        let buffer_and_selection = maybe!({
12795            let selection = self.selections.newest::<Point>(cx);
12796            let selection_range = selection.range();
12797
12798            let multi_buffer = self.buffer().read(cx);
12799            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12800            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12801
12802            let (buffer, range, _) = if selection.reversed {
12803                buffer_ranges.first()
12804            } else {
12805                buffer_ranges.last()
12806            }?;
12807
12808            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12809                ..text::ToPoint::to_point(&range.end, &buffer).row;
12810            Some((
12811                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12812                selection,
12813            ))
12814        });
12815
12816        let Some((buffer, selection)) = buffer_and_selection else {
12817            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12818        };
12819
12820        let Some(project) = self.project.as_ref() else {
12821            return Task::ready(Err(anyhow!("editor does not have project")));
12822        };
12823
12824        project.update(cx, |project, cx| {
12825            project.get_permalink_to_line(&buffer, selection, cx)
12826        })
12827    }
12828
12829    pub fn copy_permalink_to_line(
12830        &mut self,
12831        _: &CopyPermalinkToLine,
12832        window: &mut Window,
12833        cx: &mut Context<Self>,
12834    ) {
12835        let permalink_task = self.get_permalink_to_line(cx);
12836        let workspace = self.workspace();
12837
12838        cx.spawn_in(window, |_, mut cx| async move {
12839            match permalink_task.await {
12840                Ok(permalink) => {
12841                    cx.update(|_, cx| {
12842                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12843                    })
12844                    .ok();
12845                }
12846                Err(err) => {
12847                    let message = format!("Failed to copy permalink: {err}");
12848
12849                    Err::<(), anyhow::Error>(err).log_err();
12850
12851                    if let Some(workspace) = workspace {
12852                        workspace
12853                            .update_in(&mut cx, |workspace, _, cx| {
12854                                struct CopyPermalinkToLine;
12855
12856                                workspace.show_toast(
12857                                    Toast::new(
12858                                        NotificationId::unique::<CopyPermalinkToLine>(),
12859                                        message,
12860                                    ),
12861                                    cx,
12862                                )
12863                            })
12864                            .ok();
12865                    }
12866                }
12867            }
12868        })
12869        .detach();
12870    }
12871
12872    pub fn copy_file_location(
12873        &mut self,
12874        _: &CopyFileLocation,
12875        _: &mut Window,
12876        cx: &mut Context<Self>,
12877    ) {
12878        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12879        if let Some(file) = self.target_file(cx) {
12880            if let Some(path) = file.path().to_str() {
12881                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12882            }
12883        }
12884    }
12885
12886    pub fn open_permalink_to_line(
12887        &mut self,
12888        _: &OpenPermalinkToLine,
12889        window: &mut Window,
12890        cx: &mut Context<Self>,
12891    ) {
12892        let permalink_task = self.get_permalink_to_line(cx);
12893        let workspace = self.workspace();
12894
12895        cx.spawn_in(window, |_, mut cx| async move {
12896            match permalink_task.await {
12897                Ok(permalink) => {
12898                    cx.update(|_, cx| {
12899                        cx.open_url(permalink.as_ref());
12900                    })
12901                    .ok();
12902                }
12903                Err(err) => {
12904                    let message = format!("Failed to open permalink: {err}");
12905
12906                    Err::<(), anyhow::Error>(err).log_err();
12907
12908                    if let Some(workspace) = workspace {
12909                        workspace
12910                            .update(&mut cx, |workspace, cx| {
12911                                struct OpenPermalinkToLine;
12912
12913                                workspace.show_toast(
12914                                    Toast::new(
12915                                        NotificationId::unique::<OpenPermalinkToLine>(),
12916                                        message,
12917                                    ),
12918                                    cx,
12919                                )
12920                            })
12921                            .ok();
12922                    }
12923                }
12924            }
12925        })
12926        .detach();
12927    }
12928
12929    pub fn insert_uuid_v4(
12930        &mut self,
12931        _: &InsertUuidV4,
12932        window: &mut Window,
12933        cx: &mut Context<Self>,
12934    ) {
12935        self.insert_uuid(UuidVersion::V4, window, cx);
12936    }
12937
12938    pub fn insert_uuid_v7(
12939        &mut self,
12940        _: &InsertUuidV7,
12941        window: &mut Window,
12942        cx: &mut Context<Self>,
12943    ) {
12944        self.insert_uuid(UuidVersion::V7, window, cx);
12945    }
12946
12947    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12948        self.transact(window, cx, |this, window, cx| {
12949            let edits = this
12950                .selections
12951                .all::<Point>(cx)
12952                .into_iter()
12953                .map(|selection| {
12954                    let uuid = match version {
12955                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12956                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12957                    };
12958
12959                    (selection.range(), uuid.to_string())
12960                });
12961            this.edit(edits, cx);
12962            this.refresh_inline_completion(true, false, window, cx);
12963        });
12964    }
12965
12966    pub fn open_selections_in_multibuffer(
12967        &mut self,
12968        _: &OpenSelectionsInMultibuffer,
12969        window: &mut Window,
12970        cx: &mut Context<Self>,
12971    ) {
12972        let multibuffer = self.buffer.read(cx);
12973
12974        let Some(buffer) = multibuffer.as_singleton() else {
12975            return;
12976        };
12977
12978        let Some(workspace) = self.workspace() else {
12979            return;
12980        };
12981
12982        let locations = self
12983            .selections
12984            .disjoint_anchors()
12985            .iter()
12986            .map(|range| Location {
12987                buffer: buffer.clone(),
12988                range: range.start.text_anchor..range.end.text_anchor,
12989            })
12990            .collect::<Vec<_>>();
12991
12992        let title = multibuffer.title(cx).to_string();
12993
12994        cx.spawn_in(window, |_, mut cx| async move {
12995            workspace.update_in(&mut cx, |workspace, window, cx| {
12996                Self::open_locations_in_multibuffer(
12997                    workspace,
12998                    locations,
12999                    format!("Selections for '{title}'"),
13000                    false,
13001                    MultibufferSelectionMode::All,
13002                    window,
13003                    cx,
13004                );
13005            })
13006        })
13007        .detach();
13008    }
13009
13010    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13011    /// last highlight added will be used.
13012    ///
13013    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13014    pub fn highlight_rows<T: 'static>(
13015        &mut self,
13016        range: Range<Anchor>,
13017        color: Hsla,
13018        should_autoscroll: bool,
13019        cx: &mut Context<Self>,
13020    ) {
13021        let snapshot = self.buffer().read(cx).snapshot(cx);
13022        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13023        let ix = row_highlights.binary_search_by(|highlight| {
13024            Ordering::Equal
13025                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13026                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13027        });
13028
13029        if let Err(mut ix) = ix {
13030            let index = post_inc(&mut self.highlight_order);
13031
13032            // If this range intersects with the preceding highlight, then merge it with
13033            // the preceding highlight. Otherwise insert a new highlight.
13034            let mut merged = false;
13035            if ix > 0 {
13036                let prev_highlight = &mut row_highlights[ix - 1];
13037                if prev_highlight
13038                    .range
13039                    .end
13040                    .cmp(&range.start, &snapshot)
13041                    .is_ge()
13042                {
13043                    ix -= 1;
13044                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13045                        prev_highlight.range.end = range.end;
13046                    }
13047                    merged = true;
13048                    prev_highlight.index = index;
13049                    prev_highlight.color = color;
13050                    prev_highlight.should_autoscroll = should_autoscroll;
13051                }
13052            }
13053
13054            if !merged {
13055                row_highlights.insert(
13056                    ix,
13057                    RowHighlight {
13058                        range: range.clone(),
13059                        index,
13060                        color,
13061                        should_autoscroll,
13062                    },
13063                );
13064            }
13065
13066            // If any of the following highlights intersect with this one, merge them.
13067            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13068                let highlight = &row_highlights[ix];
13069                if next_highlight
13070                    .range
13071                    .start
13072                    .cmp(&highlight.range.end, &snapshot)
13073                    .is_le()
13074                {
13075                    if next_highlight
13076                        .range
13077                        .end
13078                        .cmp(&highlight.range.end, &snapshot)
13079                        .is_gt()
13080                    {
13081                        row_highlights[ix].range.end = next_highlight.range.end;
13082                    }
13083                    row_highlights.remove(ix + 1);
13084                } else {
13085                    break;
13086                }
13087            }
13088        }
13089    }
13090
13091    /// Remove any highlighted row ranges of the given type that intersect the
13092    /// given ranges.
13093    pub fn remove_highlighted_rows<T: 'static>(
13094        &mut self,
13095        ranges_to_remove: Vec<Range<Anchor>>,
13096        cx: &mut Context<Self>,
13097    ) {
13098        let snapshot = self.buffer().read(cx).snapshot(cx);
13099        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13100        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13101        row_highlights.retain(|highlight| {
13102            while let Some(range_to_remove) = ranges_to_remove.peek() {
13103                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13104                    Ordering::Less | Ordering::Equal => {
13105                        ranges_to_remove.next();
13106                    }
13107                    Ordering::Greater => {
13108                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13109                            Ordering::Less | Ordering::Equal => {
13110                                return false;
13111                            }
13112                            Ordering::Greater => break,
13113                        }
13114                    }
13115                }
13116            }
13117
13118            true
13119        })
13120    }
13121
13122    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13123    pub fn clear_row_highlights<T: 'static>(&mut self) {
13124        self.highlighted_rows.remove(&TypeId::of::<T>());
13125    }
13126
13127    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13128    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13129        self.highlighted_rows
13130            .get(&TypeId::of::<T>())
13131            .map_or(&[] as &[_], |vec| vec.as_slice())
13132            .iter()
13133            .map(|highlight| (highlight.range.clone(), highlight.color))
13134    }
13135
13136    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13137    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13138    /// Allows to ignore certain kinds of highlights.
13139    pub fn highlighted_display_rows(
13140        &self,
13141        window: &mut Window,
13142        cx: &mut App,
13143    ) -> BTreeMap<DisplayRow, Hsla> {
13144        let snapshot = self.snapshot(window, cx);
13145        let mut used_highlight_orders = HashMap::default();
13146        self.highlighted_rows
13147            .iter()
13148            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13149            .fold(
13150                BTreeMap::<DisplayRow, Hsla>::new(),
13151                |mut unique_rows, highlight| {
13152                    let start = highlight.range.start.to_display_point(&snapshot);
13153                    let end = highlight.range.end.to_display_point(&snapshot);
13154                    let start_row = start.row().0;
13155                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13156                        && end.column() == 0
13157                    {
13158                        end.row().0.saturating_sub(1)
13159                    } else {
13160                        end.row().0
13161                    };
13162                    for row in start_row..=end_row {
13163                        let used_index =
13164                            used_highlight_orders.entry(row).or_insert(highlight.index);
13165                        if highlight.index >= *used_index {
13166                            *used_index = highlight.index;
13167                            unique_rows.insert(DisplayRow(row), highlight.color);
13168                        }
13169                    }
13170                    unique_rows
13171                },
13172            )
13173    }
13174
13175    pub fn highlighted_display_row_for_autoscroll(
13176        &self,
13177        snapshot: &DisplaySnapshot,
13178    ) -> Option<DisplayRow> {
13179        self.highlighted_rows
13180            .values()
13181            .flat_map(|highlighted_rows| highlighted_rows.iter())
13182            .filter_map(|highlight| {
13183                if highlight.should_autoscroll {
13184                    Some(highlight.range.start.to_display_point(snapshot).row())
13185                } else {
13186                    None
13187                }
13188            })
13189            .min()
13190    }
13191
13192    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13193        self.highlight_background::<SearchWithinRange>(
13194            ranges,
13195            |colors| colors.editor_document_highlight_read_background,
13196            cx,
13197        )
13198    }
13199
13200    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13201        self.breadcrumb_header = Some(new_header);
13202    }
13203
13204    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13205        self.clear_background_highlights::<SearchWithinRange>(cx);
13206    }
13207
13208    pub fn highlight_background<T: 'static>(
13209        &mut self,
13210        ranges: &[Range<Anchor>],
13211        color_fetcher: fn(&ThemeColors) -> Hsla,
13212        cx: &mut Context<Self>,
13213    ) {
13214        self.background_highlights
13215            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13216        self.scrollbar_marker_state.dirty = true;
13217        cx.notify();
13218    }
13219
13220    pub fn clear_background_highlights<T: 'static>(
13221        &mut self,
13222        cx: &mut Context<Self>,
13223    ) -> Option<BackgroundHighlight> {
13224        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13225        if !text_highlights.1.is_empty() {
13226            self.scrollbar_marker_state.dirty = true;
13227            cx.notify();
13228        }
13229        Some(text_highlights)
13230    }
13231
13232    pub fn highlight_gutter<T: 'static>(
13233        &mut self,
13234        ranges: &[Range<Anchor>],
13235        color_fetcher: fn(&App) -> Hsla,
13236        cx: &mut Context<Self>,
13237    ) {
13238        self.gutter_highlights
13239            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13240        cx.notify();
13241    }
13242
13243    pub fn clear_gutter_highlights<T: 'static>(
13244        &mut self,
13245        cx: &mut Context<Self>,
13246    ) -> Option<GutterHighlight> {
13247        cx.notify();
13248        self.gutter_highlights.remove(&TypeId::of::<T>())
13249    }
13250
13251    #[cfg(feature = "test-support")]
13252    pub fn all_text_background_highlights(
13253        &self,
13254        window: &mut Window,
13255        cx: &mut Context<Self>,
13256    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13257        let snapshot = self.snapshot(window, cx);
13258        let buffer = &snapshot.buffer_snapshot;
13259        let start = buffer.anchor_before(0);
13260        let end = buffer.anchor_after(buffer.len());
13261        let theme = cx.theme().colors();
13262        self.background_highlights_in_range(start..end, &snapshot, theme)
13263    }
13264
13265    #[cfg(feature = "test-support")]
13266    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13267        let snapshot = self.buffer().read(cx).snapshot(cx);
13268
13269        let highlights = self
13270            .background_highlights
13271            .get(&TypeId::of::<items::BufferSearchHighlights>());
13272
13273        if let Some((_color, ranges)) = highlights {
13274            ranges
13275                .iter()
13276                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13277                .collect_vec()
13278        } else {
13279            vec![]
13280        }
13281    }
13282
13283    fn document_highlights_for_position<'a>(
13284        &'a self,
13285        position: Anchor,
13286        buffer: &'a MultiBufferSnapshot,
13287    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13288        let read_highlights = self
13289            .background_highlights
13290            .get(&TypeId::of::<DocumentHighlightRead>())
13291            .map(|h| &h.1);
13292        let write_highlights = self
13293            .background_highlights
13294            .get(&TypeId::of::<DocumentHighlightWrite>())
13295            .map(|h| &h.1);
13296        let left_position = position.bias_left(buffer);
13297        let right_position = position.bias_right(buffer);
13298        read_highlights
13299            .into_iter()
13300            .chain(write_highlights)
13301            .flat_map(move |ranges| {
13302                let start_ix = match ranges.binary_search_by(|probe| {
13303                    let cmp = probe.end.cmp(&left_position, buffer);
13304                    if cmp.is_ge() {
13305                        Ordering::Greater
13306                    } else {
13307                        Ordering::Less
13308                    }
13309                }) {
13310                    Ok(i) | Err(i) => i,
13311                };
13312
13313                ranges[start_ix..]
13314                    .iter()
13315                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13316            })
13317    }
13318
13319    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13320        self.background_highlights
13321            .get(&TypeId::of::<T>())
13322            .map_or(false, |(_, highlights)| !highlights.is_empty())
13323    }
13324
13325    pub fn background_highlights_in_range(
13326        &self,
13327        search_range: Range<Anchor>,
13328        display_snapshot: &DisplaySnapshot,
13329        theme: &ThemeColors,
13330    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13331        let mut results = Vec::new();
13332        for (color_fetcher, ranges) in self.background_highlights.values() {
13333            let color = color_fetcher(theme);
13334            let start_ix = match ranges.binary_search_by(|probe| {
13335                let cmp = probe
13336                    .end
13337                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13338                if cmp.is_gt() {
13339                    Ordering::Greater
13340                } else {
13341                    Ordering::Less
13342                }
13343            }) {
13344                Ok(i) | Err(i) => i,
13345            };
13346            for range in &ranges[start_ix..] {
13347                if range
13348                    .start
13349                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13350                    .is_ge()
13351                {
13352                    break;
13353                }
13354
13355                let start = range.start.to_display_point(display_snapshot);
13356                let end = range.end.to_display_point(display_snapshot);
13357                results.push((start..end, color))
13358            }
13359        }
13360        results
13361    }
13362
13363    pub fn background_highlight_row_ranges<T: 'static>(
13364        &self,
13365        search_range: Range<Anchor>,
13366        display_snapshot: &DisplaySnapshot,
13367        count: usize,
13368    ) -> Vec<RangeInclusive<DisplayPoint>> {
13369        let mut results = Vec::new();
13370        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13371            return vec![];
13372        };
13373
13374        let start_ix = match ranges.binary_search_by(|probe| {
13375            let cmp = probe
13376                .end
13377                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13378            if cmp.is_gt() {
13379                Ordering::Greater
13380            } else {
13381                Ordering::Less
13382            }
13383        }) {
13384            Ok(i) | Err(i) => i,
13385        };
13386        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13387            if let (Some(start_display), Some(end_display)) = (start, end) {
13388                results.push(
13389                    start_display.to_display_point(display_snapshot)
13390                        ..=end_display.to_display_point(display_snapshot),
13391                );
13392            }
13393        };
13394        let mut start_row: Option<Point> = None;
13395        let mut end_row: Option<Point> = None;
13396        if ranges.len() > count {
13397            return Vec::new();
13398        }
13399        for range in &ranges[start_ix..] {
13400            if range
13401                .start
13402                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13403                .is_ge()
13404            {
13405                break;
13406            }
13407            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13408            if let Some(current_row) = &end_row {
13409                if end.row == current_row.row {
13410                    continue;
13411                }
13412            }
13413            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13414            if start_row.is_none() {
13415                assert_eq!(end_row, None);
13416                start_row = Some(start);
13417                end_row = Some(end);
13418                continue;
13419            }
13420            if let Some(current_end) = end_row.as_mut() {
13421                if start.row > current_end.row + 1 {
13422                    push_region(start_row, end_row);
13423                    start_row = Some(start);
13424                    end_row = Some(end);
13425                } else {
13426                    // Merge two hunks.
13427                    *current_end = end;
13428                }
13429            } else {
13430                unreachable!();
13431            }
13432        }
13433        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13434        push_region(start_row, end_row);
13435        results
13436    }
13437
13438    pub fn gutter_highlights_in_range(
13439        &self,
13440        search_range: Range<Anchor>,
13441        display_snapshot: &DisplaySnapshot,
13442        cx: &App,
13443    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13444        let mut results = Vec::new();
13445        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13446            let color = color_fetcher(cx);
13447            let start_ix = match ranges.binary_search_by(|probe| {
13448                let cmp = probe
13449                    .end
13450                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13451                if cmp.is_gt() {
13452                    Ordering::Greater
13453                } else {
13454                    Ordering::Less
13455                }
13456            }) {
13457                Ok(i) | Err(i) => i,
13458            };
13459            for range in &ranges[start_ix..] {
13460                if range
13461                    .start
13462                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13463                    .is_ge()
13464                {
13465                    break;
13466                }
13467
13468                let start = range.start.to_display_point(display_snapshot);
13469                let end = range.end.to_display_point(display_snapshot);
13470                results.push((start..end, color))
13471            }
13472        }
13473        results
13474    }
13475
13476    /// Get the text ranges corresponding to the redaction query
13477    pub fn redacted_ranges(
13478        &self,
13479        search_range: Range<Anchor>,
13480        display_snapshot: &DisplaySnapshot,
13481        cx: &App,
13482    ) -> Vec<Range<DisplayPoint>> {
13483        display_snapshot
13484            .buffer_snapshot
13485            .redacted_ranges(search_range, |file| {
13486                if let Some(file) = file {
13487                    file.is_private()
13488                        && EditorSettings::get(
13489                            Some(SettingsLocation {
13490                                worktree_id: file.worktree_id(cx),
13491                                path: file.path().as_ref(),
13492                            }),
13493                            cx,
13494                        )
13495                        .redact_private_values
13496                } else {
13497                    false
13498                }
13499            })
13500            .map(|range| {
13501                range.start.to_display_point(display_snapshot)
13502                    ..range.end.to_display_point(display_snapshot)
13503            })
13504            .collect()
13505    }
13506
13507    pub fn highlight_text<T: 'static>(
13508        &mut self,
13509        ranges: Vec<Range<Anchor>>,
13510        style: HighlightStyle,
13511        cx: &mut Context<Self>,
13512    ) {
13513        self.display_map.update(cx, |map, _| {
13514            map.highlight_text(TypeId::of::<T>(), ranges, style)
13515        });
13516        cx.notify();
13517    }
13518
13519    pub(crate) fn highlight_inlays<T: 'static>(
13520        &mut self,
13521        highlights: Vec<InlayHighlight>,
13522        style: HighlightStyle,
13523        cx: &mut Context<Self>,
13524    ) {
13525        self.display_map.update(cx, |map, _| {
13526            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13527        });
13528        cx.notify();
13529    }
13530
13531    pub fn text_highlights<'a, T: 'static>(
13532        &'a self,
13533        cx: &'a App,
13534    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13535        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13536    }
13537
13538    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13539        let cleared = self
13540            .display_map
13541            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13542        if cleared {
13543            cx.notify();
13544        }
13545    }
13546
13547    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13548        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13549            && self.focus_handle.is_focused(window)
13550    }
13551
13552    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13553        self.show_cursor_when_unfocused = is_enabled;
13554        cx.notify();
13555    }
13556
13557    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13558        self.project
13559            .as_ref()
13560            .map(|project| project.read(cx).lsp_store())
13561    }
13562
13563    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13564        cx.notify();
13565    }
13566
13567    fn on_buffer_event(
13568        &mut self,
13569        multibuffer: &Entity<MultiBuffer>,
13570        event: &multi_buffer::Event,
13571        window: &mut Window,
13572        cx: &mut Context<Self>,
13573    ) {
13574        match event {
13575            multi_buffer::Event::Edited {
13576                singleton_buffer_edited,
13577                edited_buffer: buffer_edited,
13578            } => {
13579                self.scrollbar_marker_state.dirty = true;
13580                self.active_indent_guides_state.dirty = true;
13581                self.refresh_active_diagnostics(cx);
13582                self.refresh_code_actions(window, cx);
13583                if self.has_active_inline_completion() {
13584                    self.update_visible_inline_completion(window, cx);
13585                }
13586                if let Some(buffer) = buffer_edited {
13587                    let buffer_id = buffer.read(cx).remote_id();
13588                    if !self.registered_buffers.contains_key(&buffer_id) {
13589                        if let Some(lsp_store) = self.lsp_store(cx) {
13590                            lsp_store.update(cx, |lsp_store, cx| {
13591                                self.registered_buffers.insert(
13592                                    buffer_id,
13593                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13594                                );
13595                            })
13596                        }
13597                    }
13598                }
13599                cx.emit(EditorEvent::BufferEdited);
13600                cx.emit(SearchEvent::MatchesInvalidated);
13601                if *singleton_buffer_edited {
13602                    if let Some(project) = &self.project {
13603                        let project = project.read(cx);
13604                        #[allow(clippy::mutable_key_type)]
13605                        let languages_affected = multibuffer
13606                            .read(cx)
13607                            .all_buffers()
13608                            .into_iter()
13609                            .filter_map(|buffer| {
13610                                let buffer = buffer.read(cx);
13611                                let language = buffer.language()?;
13612                                if project.is_local()
13613                                    && project
13614                                        .language_servers_for_local_buffer(buffer, cx)
13615                                        .count()
13616                                        == 0
13617                                {
13618                                    None
13619                                } else {
13620                                    Some(language)
13621                                }
13622                            })
13623                            .cloned()
13624                            .collect::<HashSet<_>>();
13625                        if !languages_affected.is_empty() {
13626                            self.refresh_inlay_hints(
13627                                InlayHintRefreshReason::BufferEdited(languages_affected),
13628                                cx,
13629                            );
13630                        }
13631                    }
13632                }
13633
13634                let Some(project) = &self.project else { return };
13635                let (telemetry, is_via_ssh) = {
13636                    let project = project.read(cx);
13637                    let telemetry = project.client().telemetry().clone();
13638                    let is_via_ssh = project.is_via_ssh();
13639                    (telemetry, is_via_ssh)
13640                };
13641                refresh_linked_ranges(self, window, cx);
13642                telemetry.log_edit_event("editor", is_via_ssh);
13643            }
13644            multi_buffer::Event::ExcerptsAdded {
13645                buffer,
13646                predecessor,
13647                excerpts,
13648            } => {
13649                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13650                let buffer_id = buffer.read(cx).remote_id();
13651                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13652                    if let Some(project) = &self.project {
13653                        get_unstaged_changes_for_buffers(
13654                            project,
13655                            [buffer.clone()],
13656                            self.buffer.clone(),
13657                            cx,
13658                        );
13659                    }
13660                }
13661                cx.emit(EditorEvent::ExcerptsAdded {
13662                    buffer: buffer.clone(),
13663                    predecessor: *predecessor,
13664                    excerpts: excerpts.clone(),
13665                });
13666                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13667            }
13668            multi_buffer::Event::ExcerptsRemoved { ids } => {
13669                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13670                let buffer = self.buffer.read(cx);
13671                self.registered_buffers
13672                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13673                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13674            }
13675            multi_buffer::Event::ExcerptsEdited { ids } => {
13676                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13677            }
13678            multi_buffer::Event::ExcerptsExpanded { ids } => {
13679                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13680                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13681            }
13682            multi_buffer::Event::Reparsed(buffer_id) => {
13683                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13684
13685                cx.emit(EditorEvent::Reparsed(*buffer_id));
13686            }
13687            multi_buffer::Event::DiffHunksToggled => {
13688                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13689            }
13690            multi_buffer::Event::LanguageChanged(buffer_id) => {
13691                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13692                cx.emit(EditorEvent::Reparsed(*buffer_id));
13693                cx.notify();
13694            }
13695            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13696            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13697            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13698                cx.emit(EditorEvent::TitleChanged)
13699            }
13700            // multi_buffer::Event::DiffBaseChanged => {
13701            //     self.scrollbar_marker_state.dirty = true;
13702            //     cx.emit(EditorEvent::DiffBaseChanged);
13703            //     cx.notify();
13704            // }
13705            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13706            multi_buffer::Event::DiagnosticsUpdated => {
13707                self.refresh_active_diagnostics(cx);
13708                self.scrollbar_marker_state.dirty = true;
13709                cx.notify();
13710            }
13711            _ => {}
13712        };
13713    }
13714
13715    fn on_display_map_changed(
13716        &mut self,
13717        _: Entity<DisplayMap>,
13718        _: &mut Window,
13719        cx: &mut Context<Self>,
13720    ) {
13721        cx.notify();
13722    }
13723
13724    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13725        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13726        self.refresh_inline_completion(true, false, window, cx);
13727        self.refresh_inlay_hints(
13728            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13729                self.selections.newest_anchor().head(),
13730                &self.buffer.read(cx).snapshot(cx),
13731                cx,
13732            )),
13733            cx,
13734        );
13735
13736        let old_cursor_shape = self.cursor_shape;
13737
13738        {
13739            let editor_settings = EditorSettings::get_global(cx);
13740            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13741            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13742            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13743        }
13744
13745        if old_cursor_shape != self.cursor_shape {
13746            cx.emit(EditorEvent::CursorShapeChanged);
13747        }
13748
13749        let project_settings = ProjectSettings::get_global(cx);
13750        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13751
13752        if self.mode == EditorMode::Full {
13753            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13754            if self.git_blame_inline_enabled != inline_blame_enabled {
13755                self.toggle_git_blame_inline_internal(false, window, cx);
13756            }
13757        }
13758
13759        cx.notify();
13760    }
13761
13762    pub fn set_searchable(&mut self, searchable: bool) {
13763        self.searchable = searchable;
13764    }
13765
13766    pub fn searchable(&self) -> bool {
13767        self.searchable
13768    }
13769
13770    fn open_proposed_changes_editor(
13771        &mut self,
13772        _: &OpenProposedChangesEditor,
13773        window: &mut Window,
13774        cx: &mut Context<Self>,
13775    ) {
13776        let Some(workspace) = self.workspace() else {
13777            cx.propagate();
13778            return;
13779        };
13780
13781        let selections = self.selections.all::<usize>(cx);
13782        let multi_buffer = self.buffer.read(cx);
13783        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13784        let mut new_selections_by_buffer = HashMap::default();
13785        for selection in selections {
13786            for (buffer, range, _) in
13787                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13788            {
13789                let mut range = range.to_point(buffer);
13790                range.start.column = 0;
13791                range.end.column = buffer.line_len(range.end.row);
13792                new_selections_by_buffer
13793                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13794                    .or_insert(Vec::new())
13795                    .push(range)
13796            }
13797        }
13798
13799        let proposed_changes_buffers = new_selections_by_buffer
13800            .into_iter()
13801            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13802            .collect::<Vec<_>>();
13803        let proposed_changes_editor = cx.new(|cx| {
13804            ProposedChangesEditor::new(
13805                "Proposed changes",
13806                proposed_changes_buffers,
13807                self.project.clone(),
13808                window,
13809                cx,
13810            )
13811        });
13812
13813        window.defer(cx, move |window, cx| {
13814            workspace.update(cx, |workspace, cx| {
13815                workspace.active_pane().update(cx, |pane, cx| {
13816                    pane.add_item(
13817                        Box::new(proposed_changes_editor),
13818                        true,
13819                        true,
13820                        None,
13821                        window,
13822                        cx,
13823                    );
13824                });
13825            });
13826        });
13827    }
13828
13829    pub fn open_excerpts_in_split(
13830        &mut self,
13831        _: &OpenExcerptsSplit,
13832        window: &mut Window,
13833        cx: &mut Context<Self>,
13834    ) {
13835        self.open_excerpts_common(None, true, window, cx)
13836    }
13837
13838    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13839        self.open_excerpts_common(None, false, window, cx)
13840    }
13841
13842    fn open_excerpts_common(
13843        &mut self,
13844        jump_data: Option<JumpData>,
13845        split: bool,
13846        window: &mut Window,
13847        cx: &mut Context<Self>,
13848    ) {
13849        let Some(workspace) = self.workspace() else {
13850            cx.propagate();
13851            return;
13852        };
13853
13854        if self.buffer.read(cx).is_singleton() {
13855            cx.propagate();
13856            return;
13857        }
13858
13859        let mut new_selections_by_buffer = HashMap::default();
13860        match &jump_data {
13861            Some(JumpData::MultiBufferPoint {
13862                excerpt_id,
13863                position,
13864                anchor,
13865                line_offset_from_top,
13866            }) => {
13867                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13868                if let Some(buffer) = multi_buffer_snapshot
13869                    .buffer_id_for_excerpt(*excerpt_id)
13870                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13871                {
13872                    let buffer_snapshot = buffer.read(cx).snapshot();
13873                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13874                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13875                    } else {
13876                        buffer_snapshot.clip_point(*position, Bias::Left)
13877                    };
13878                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13879                    new_selections_by_buffer.insert(
13880                        buffer,
13881                        (
13882                            vec![jump_to_offset..jump_to_offset],
13883                            Some(*line_offset_from_top),
13884                        ),
13885                    );
13886                }
13887            }
13888            Some(JumpData::MultiBufferRow {
13889                row,
13890                line_offset_from_top,
13891            }) => {
13892                let point = MultiBufferPoint::new(row.0, 0);
13893                if let Some((buffer, buffer_point, _)) =
13894                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13895                {
13896                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13897                    new_selections_by_buffer
13898                        .entry(buffer)
13899                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13900                        .0
13901                        .push(buffer_offset..buffer_offset)
13902                }
13903            }
13904            None => {
13905                let selections = self.selections.all::<usize>(cx);
13906                let multi_buffer = self.buffer.read(cx);
13907                for selection in selections {
13908                    for (buffer, mut range, _) in multi_buffer
13909                        .snapshot(cx)
13910                        .range_to_buffer_ranges(selection.range())
13911                    {
13912                        // When editing branch buffers, jump to the corresponding location
13913                        // in their base buffer.
13914                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13915                        let buffer = buffer_handle.read(cx);
13916                        if let Some(base_buffer) = buffer.base_buffer() {
13917                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13918                            buffer_handle = base_buffer;
13919                        }
13920
13921                        if selection.reversed {
13922                            mem::swap(&mut range.start, &mut range.end);
13923                        }
13924                        new_selections_by_buffer
13925                            .entry(buffer_handle)
13926                            .or_insert((Vec::new(), None))
13927                            .0
13928                            .push(range)
13929                    }
13930                }
13931            }
13932        }
13933
13934        if new_selections_by_buffer.is_empty() {
13935            return;
13936        }
13937
13938        // We defer the pane interaction because we ourselves are a workspace item
13939        // and activating a new item causes the pane to call a method on us reentrantly,
13940        // which panics if we're on the stack.
13941        window.defer(cx, move |window, cx| {
13942            workspace.update(cx, |workspace, cx| {
13943                let pane = if split {
13944                    workspace.adjacent_pane(window, cx)
13945                } else {
13946                    workspace.active_pane().clone()
13947                };
13948
13949                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13950                    let editor = buffer
13951                        .read(cx)
13952                        .file()
13953                        .is_none()
13954                        .then(|| {
13955                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13956                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13957                            // Instead, we try to activate the existing editor in the pane first.
13958                            let (editor, pane_item_index) =
13959                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13960                                    let editor = item.downcast::<Editor>()?;
13961                                    let singleton_buffer =
13962                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13963                                    if singleton_buffer == buffer {
13964                                        Some((editor, i))
13965                                    } else {
13966                                        None
13967                                    }
13968                                })?;
13969                            pane.update(cx, |pane, cx| {
13970                                pane.activate_item(pane_item_index, true, true, window, cx)
13971                            });
13972                            Some(editor)
13973                        })
13974                        .flatten()
13975                        .unwrap_or_else(|| {
13976                            workspace.open_project_item::<Self>(
13977                                pane.clone(),
13978                                buffer,
13979                                true,
13980                                true,
13981                                window,
13982                                cx,
13983                            )
13984                        });
13985
13986                    editor.update(cx, |editor, cx| {
13987                        let autoscroll = match scroll_offset {
13988                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13989                            None => Autoscroll::newest(),
13990                        };
13991                        let nav_history = editor.nav_history.take();
13992                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13993                            s.select_ranges(ranges);
13994                        });
13995                        editor.nav_history = nav_history;
13996                    });
13997                }
13998            })
13999        });
14000    }
14001
14002    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14003        let snapshot = self.buffer.read(cx).read(cx);
14004        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14005        Some(
14006            ranges
14007                .iter()
14008                .map(move |range| {
14009                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14010                })
14011                .collect(),
14012        )
14013    }
14014
14015    fn selection_replacement_ranges(
14016        &self,
14017        range: Range<OffsetUtf16>,
14018        cx: &mut App,
14019    ) -> Vec<Range<OffsetUtf16>> {
14020        let selections = self.selections.all::<OffsetUtf16>(cx);
14021        let newest_selection = selections
14022            .iter()
14023            .max_by_key(|selection| selection.id)
14024            .unwrap();
14025        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14026        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14027        let snapshot = self.buffer.read(cx).read(cx);
14028        selections
14029            .into_iter()
14030            .map(|mut selection| {
14031                selection.start.0 =
14032                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14033                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14034                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14035                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14036            })
14037            .collect()
14038    }
14039
14040    fn report_editor_event(
14041        &self,
14042        event_type: &'static str,
14043        file_extension: Option<String>,
14044        cx: &App,
14045    ) {
14046        if cfg!(any(test, feature = "test-support")) {
14047            return;
14048        }
14049
14050        let Some(project) = &self.project else { return };
14051
14052        // If None, we are in a file without an extension
14053        let file = self
14054            .buffer
14055            .read(cx)
14056            .as_singleton()
14057            .and_then(|b| b.read(cx).file());
14058        let file_extension = file_extension.or(file
14059            .as_ref()
14060            .and_then(|file| Path::new(file.file_name(cx)).extension())
14061            .and_then(|e| e.to_str())
14062            .map(|a| a.to_string()));
14063
14064        let vim_mode = cx
14065            .global::<SettingsStore>()
14066            .raw_user_settings()
14067            .get("vim_mode")
14068            == Some(&serde_json::Value::Bool(true));
14069
14070        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14071            == language::language_settings::InlineCompletionProvider::Copilot;
14072        let copilot_enabled_for_language = self
14073            .buffer
14074            .read(cx)
14075            .settings_at(0, cx)
14076            .show_inline_completions;
14077
14078        let project = project.read(cx);
14079        telemetry::event!(
14080            event_type,
14081            file_extension,
14082            vim_mode,
14083            copilot_enabled,
14084            copilot_enabled_for_language,
14085            is_via_ssh = project.is_via_ssh(),
14086        );
14087    }
14088
14089    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14090    /// with each line being an array of {text, highlight} objects.
14091    fn copy_highlight_json(
14092        &mut self,
14093        _: &CopyHighlightJson,
14094        window: &mut Window,
14095        cx: &mut Context<Self>,
14096    ) {
14097        #[derive(Serialize)]
14098        struct Chunk<'a> {
14099            text: String,
14100            highlight: Option<&'a str>,
14101        }
14102
14103        let snapshot = self.buffer.read(cx).snapshot(cx);
14104        let range = self
14105            .selected_text_range(false, window, cx)
14106            .and_then(|selection| {
14107                if selection.range.is_empty() {
14108                    None
14109                } else {
14110                    Some(selection.range)
14111                }
14112            })
14113            .unwrap_or_else(|| 0..snapshot.len());
14114
14115        let chunks = snapshot.chunks(range, true);
14116        let mut lines = Vec::new();
14117        let mut line: VecDeque<Chunk> = VecDeque::new();
14118
14119        let Some(style) = self.style.as_ref() else {
14120            return;
14121        };
14122
14123        for chunk in chunks {
14124            let highlight = chunk
14125                .syntax_highlight_id
14126                .and_then(|id| id.name(&style.syntax));
14127            let mut chunk_lines = chunk.text.split('\n').peekable();
14128            while let Some(text) = chunk_lines.next() {
14129                let mut merged_with_last_token = false;
14130                if let Some(last_token) = line.back_mut() {
14131                    if last_token.highlight == highlight {
14132                        last_token.text.push_str(text);
14133                        merged_with_last_token = true;
14134                    }
14135                }
14136
14137                if !merged_with_last_token {
14138                    line.push_back(Chunk {
14139                        text: text.into(),
14140                        highlight,
14141                    });
14142                }
14143
14144                if chunk_lines.peek().is_some() {
14145                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14146                        line.pop_front();
14147                    }
14148                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14149                        line.pop_back();
14150                    }
14151
14152                    lines.push(mem::take(&mut line));
14153                }
14154            }
14155        }
14156
14157        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14158            return;
14159        };
14160        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14161    }
14162
14163    pub fn open_context_menu(
14164        &mut self,
14165        _: &OpenContextMenu,
14166        window: &mut Window,
14167        cx: &mut Context<Self>,
14168    ) {
14169        self.request_autoscroll(Autoscroll::newest(), cx);
14170        let position = self.selections.newest_display(cx).start;
14171        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14172    }
14173
14174    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14175        &self.inlay_hint_cache
14176    }
14177
14178    pub fn replay_insert_event(
14179        &mut self,
14180        text: &str,
14181        relative_utf16_range: Option<Range<isize>>,
14182        window: &mut Window,
14183        cx: &mut Context<Self>,
14184    ) {
14185        if !self.input_enabled {
14186            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14187            return;
14188        }
14189        if let Some(relative_utf16_range) = relative_utf16_range {
14190            let selections = self.selections.all::<OffsetUtf16>(cx);
14191            self.change_selections(None, window, cx, |s| {
14192                let new_ranges = selections.into_iter().map(|range| {
14193                    let start = OffsetUtf16(
14194                        range
14195                            .head()
14196                            .0
14197                            .saturating_add_signed(relative_utf16_range.start),
14198                    );
14199                    let end = OffsetUtf16(
14200                        range
14201                            .head()
14202                            .0
14203                            .saturating_add_signed(relative_utf16_range.end),
14204                    );
14205                    start..end
14206                });
14207                s.select_ranges(new_ranges);
14208            });
14209        }
14210
14211        self.handle_input(text, window, cx);
14212    }
14213
14214    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14215        let Some(provider) = self.semantics_provider.as_ref() else {
14216            return false;
14217        };
14218
14219        let mut supports = false;
14220        self.buffer().read(cx).for_each_buffer(|buffer| {
14221            supports |= provider.supports_inlay_hints(buffer, cx);
14222        });
14223        supports
14224    }
14225    pub fn is_focused(&self, window: &mut Window) -> bool {
14226        self.focus_handle.is_focused(window)
14227    }
14228
14229    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14230        cx.emit(EditorEvent::Focused);
14231
14232        if let Some(descendant) = self
14233            .last_focused_descendant
14234            .take()
14235            .and_then(|descendant| descendant.upgrade())
14236        {
14237            window.focus(&descendant);
14238        } else {
14239            if let Some(blame) = self.blame.as_ref() {
14240                blame.update(cx, GitBlame::focus)
14241            }
14242
14243            self.blink_manager.update(cx, BlinkManager::enable);
14244            self.show_cursor_names(window, cx);
14245            self.buffer.update(cx, |buffer, cx| {
14246                buffer.finalize_last_transaction(cx);
14247                if self.leader_peer_id.is_none() {
14248                    buffer.set_active_selections(
14249                        &self.selections.disjoint_anchors(),
14250                        self.selections.line_mode,
14251                        self.cursor_shape,
14252                        cx,
14253                    );
14254                }
14255            });
14256        }
14257    }
14258
14259    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14260        cx.emit(EditorEvent::FocusedIn)
14261    }
14262
14263    fn handle_focus_out(
14264        &mut self,
14265        event: FocusOutEvent,
14266        _window: &mut Window,
14267        _cx: &mut Context<Self>,
14268    ) {
14269        if event.blurred != self.focus_handle {
14270            self.last_focused_descendant = Some(event.blurred);
14271        }
14272    }
14273
14274    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14275        self.blink_manager.update(cx, BlinkManager::disable);
14276        self.buffer
14277            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14278
14279        if let Some(blame) = self.blame.as_ref() {
14280            blame.update(cx, GitBlame::blur)
14281        }
14282        if !self.hover_state.focused(window, cx) {
14283            hide_hover(self, cx);
14284        }
14285
14286        self.hide_context_menu(window, cx);
14287        cx.emit(EditorEvent::Blurred);
14288        cx.notify();
14289    }
14290
14291    pub fn register_action<A: Action>(
14292        &mut self,
14293        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14294    ) -> Subscription {
14295        let id = self.next_editor_action_id.post_inc();
14296        let listener = Arc::new(listener);
14297        self.editor_actions.borrow_mut().insert(
14298            id,
14299            Box::new(move |window, _| {
14300                let listener = listener.clone();
14301                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14302                    let action = action.downcast_ref().unwrap();
14303                    if phase == DispatchPhase::Bubble {
14304                        listener(action, window, cx)
14305                    }
14306                })
14307            }),
14308        );
14309
14310        let editor_actions = self.editor_actions.clone();
14311        Subscription::new(move || {
14312            editor_actions.borrow_mut().remove(&id);
14313        })
14314    }
14315
14316    pub fn file_header_size(&self) -> u32 {
14317        FILE_HEADER_HEIGHT
14318    }
14319
14320    pub fn revert(
14321        &mut self,
14322        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14323        window: &mut Window,
14324        cx: &mut Context<Self>,
14325    ) {
14326        self.buffer().update(cx, |multi_buffer, cx| {
14327            for (buffer_id, changes) in revert_changes {
14328                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14329                    buffer.update(cx, |buffer, cx| {
14330                        buffer.edit(
14331                            changes.into_iter().map(|(range, text)| {
14332                                (range, text.to_string().map(Arc::<str>::from))
14333                            }),
14334                            None,
14335                            cx,
14336                        );
14337                    });
14338                }
14339            }
14340        });
14341        self.change_selections(None, window, cx, |selections| selections.refresh());
14342    }
14343
14344    pub fn to_pixel_point(
14345        &self,
14346        source: multi_buffer::Anchor,
14347        editor_snapshot: &EditorSnapshot,
14348        window: &mut Window,
14349    ) -> Option<gpui::Point<Pixels>> {
14350        let source_point = source.to_display_point(editor_snapshot);
14351        self.display_to_pixel_point(source_point, editor_snapshot, window)
14352    }
14353
14354    pub fn display_to_pixel_point(
14355        &self,
14356        source: DisplayPoint,
14357        editor_snapshot: &EditorSnapshot,
14358        window: &mut Window,
14359    ) -> Option<gpui::Point<Pixels>> {
14360        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14361        let text_layout_details = self.text_layout_details(window);
14362        let scroll_top = text_layout_details
14363            .scroll_anchor
14364            .scroll_position(editor_snapshot)
14365            .y;
14366
14367        if source.row().as_f32() < scroll_top.floor() {
14368            return None;
14369        }
14370        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14371        let source_y = line_height * (source.row().as_f32() - scroll_top);
14372        Some(gpui::Point::new(source_x, source_y))
14373    }
14374
14375    pub fn has_active_completions_menu(&self) -> bool {
14376        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14377            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14378        })
14379    }
14380
14381    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14382        self.addons
14383            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14384    }
14385
14386    pub fn unregister_addon<T: Addon>(&mut self) {
14387        self.addons.remove(&std::any::TypeId::of::<T>());
14388    }
14389
14390    pub fn addon<T: Addon>(&self) -> Option<&T> {
14391        let type_id = std::any::TypeId::of::<T>();
14392        self.addons
14393            .get(&type_id)
14394            .and_then(|item| item.to_any().downcast_ref::<T>())
14395    }
14396
14397    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14398        let text_layout_details = self.text_layout_details(window);
14399        let style = &text_layout_details.editor_style;
14400        let font_id = window.text_system().resolve_font(&style.text.font());
14401        let font_size = style.text.font_size.to_pixels(window.rem_size());
14402        let line_height = style.text.line_height_in_pixels(window.rem_size());
14403        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14404
14405        gpui::Point::new(em_width, line_height)
14406    }
14407}
14408
14409fn get_unstaged_changes_for_buffers(
14410    project: &Entity<Project>,
14411    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14412    buffer: Entity<MultiBuffer>,
14413    cx: &mut App,
14414) {
14415    let mut tasks = Vec::new();
14416    project.update(cx, |project, cx| {
14417        for buffer in buffers {
14418            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14419        }
14420    });
14421    cx.spawn(|mut cx| async move {
14422        let change_sets = futures::future::join_all(tasks).await;
14423        buffer
14424            .update(&mut cx, |buffer, cx| {
14425                for change_set in change_sets {
14426                    if let Some(change_set) = change_set.log_err() {
14427                        buffer.add_change_set(change_set, cx);
14428                    }
14429                }
14430            })
14431            .ok();
14432    })
14433    .detach();
14434}
14435
14436fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14437    let tab_size = tab_size.get() as usize;
14438    let mut width = offset;
14439
14440    for ch in text.chars() {
14441        width += if ch == '\t' {
14442            tab_size - (width % tab_size)
14443        } else {
14444            1
14445        };
14446    }
14447
14448    width - offset
14449}
14450
14451#[cfg(test)]
14452mod tests {
14453    use super::*;
14454
14455    #[test]
14456    fn test_string_size_with_expanded_tabs() {
14457        let nz = |val| NonZeroU32::new(val).unwrap();
14458        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14459        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14460        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14461        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14462        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14463        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14464        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14465        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14466    }
14467}
14468
14469/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14470struct WordBreakingTokenizer<'a> {
14471    input: &'a str,
14472}
14473
14474impl<'a> WordBreakingTokenizer<'a> {
14475    fn new(input: &'a str) -> Self {
14476        Self { input }
14477    }
14478}
14479
14480fn is_char_ideographic(ch: char) -> bool {
14481    use unicode_script::Script::*;
14482    use unicode_script::UnicodeScript;
14483    matches!(ch.script(), Han | Tangut | Yi)
14484}
14485
14486fn is_grapheme_ideographic(text: &str) -> bool {
14487    text.chars().any(is_char_ideographic)
14488}
14489
14490fn is_grapheme_whitespace(text: &str) -> bool {
14491    text.chars().any(|x| x.is_whitespace())
14492}
14493
14494fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14495    text.chars().next().map_or(false, |ch| {
14496        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14497    })
14498}
14499
14500#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14501struct WordBreakToken<'a> {
14502    token: &'a str,
14503    grapheme_len: usize,
14504    is_whitespace: bool,
14505}
14506
14507impl<'a> Iterator for WordBreakingTokenizer<'a> {
14508    /// Yields a span, the count of graphemes in the token, and whether it was
14509    /// whitespace. Note that it also breaks at word boundaries.
14510    type Item = WordBreakToken<'a>;
14511
14512    fn next(&mut self) -> Option<Self::Item> {
14513        use unicode_segmentation::UnicodeSegmentation;
14514        if self.input.is_empty() {
14515            return None;
14516        }
14517
14518        let mut iter = self.input.graphemes(true).peekable();
14519        let mut offset = 0;
14520        let mut graphemes = 0;
14521        if let Some(first_grapheme) = iter.next() {
14522            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14523            offset += first_grapheme.len();
14524            graphemes += 1;
14525            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14526                if let Some(grapheme) = iter.peek().copied() {
14527                    if should_stay_with_preceding_ideograph(grapheme) {
14528                        offset += grapheme.len();
14529                        graphemes += 1;
14530                    }
14531                }
14532            } else {
14533                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14534                let mut next_word_bound = words.peek().copied();
14535                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14536                    next_word_bound = words.next();
14537                }
14538                while let Some(grapheme) = iter.peek().copied() {
14539                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14540                        break;
14541                    };
14542                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14543                        break;
14544                    };
14545                    offset += grapheme.len();
14546                    graphemes += 1;
14547                    iter.next();
14548                }
14549            }
14550            let token = &self.input[..offset];
14551            self.input = &self.input[offset..];
14552            if is_whitespace {
14553                Some(WordBreakToken {
14554                    token: " ",
14555                    grapheme_len: 1,
14556                    is_whitespace: true,
14557                })
14558            } else {
14559                Some(WordBreakToken {
14560                    token,
14561                    grapheme_len: graphemes,
14562                    is_whitespace: false,
14563                })
14564            }
14565        } else {
14566            None
14567        }
14568    }
14569}
14570
14571#[test]
14572fn test_word_breaking_tokenizer() {
14573    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14574        ("", &[]),
14575        ("  ", &[(" ", 1, true)]),
14576        ("Ʒ", &[("Ʒ", 1, false)]),
14577        ("Ǽ", &[("Ǽ", 1, false)]),
14578        ("", &[("", 1, false)]),
14579        ("⋑⋑", &[("⋑⋑", 2, false)]),
14580        (
14581            "原理,进而",
14582            &[
14583                ("", 1, false),
14584                ("理,", 2, false),
14585                ("", 1, false),
14586                ("", 1, false),
14587            ],
14588        ),
14589        (
14590            "hello world",
14591            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14592        ),
14593        (
14594            "hello, world",
14595            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14596        ),
14597        (
14598            "  hello world",
14599            &[
14600                (" ", 1, true),
14601                ("hello", 5, false),
14602                (" ", 1, true),
14603                ("world", 5, false),
14604            ],
14605        ),
14606        (
14607            "这是什么 \n 钢笔",
14608            &[
14609                ("", 1, false),
14610                ("", 1, false),
14611                ("", 1, false),
14612                ("", 1, false),
14613                (" ", 1, true),
14614                ("", 1, false),
14615                ("", 1, false),
14616            ],
14617        ),
14618        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14619    ];
14620
14621    for (input, result) in tests {
14622        assert_eq!(
14623            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14624            result
14625                .iter()
14626                .copied()
14627                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14628                    token,
14629                    grapheme_len,
14630                    is_whitespace,
14631                })
14632                .collect::<Vec<_>>()
14633        );
14634    }
14635}
14636
14637fn wrap_with_prefix(
14638    line_prefix: String,
14639    unwrapped_text: String,
14640    wrap_column: usize,
14641    tab_size: NonZeroU32,
14642) -> String {
14643    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14644    let mut wrapped_text = String::new();
14645    let mut current_line = line_prefix.clone();
14646
14647    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14648    let mut current_line_len = line_prefix_len;
14649    for WordBreakToken {
14650        token,
14651        grapheme_len,
14652        is_whitespace,
14653    } in tokenizer
14654    {
14655        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14656            wrapped_text.push_str(current_line.trim_end());
14657            wrapped_text.push('\n');
14658            current_line.truncate(line_prefix.len());
14659            current_line_len = line_prefix_len;
14660            if !is_whitespace {
14661                current_line.push_str(token);
14662                current_line_len += grapheme_len;
14663            }
14664        } else if !is_whitespace {
14665            current_line.push_str(token);
14666            current_line_len += grapheme_len;
14667        } else if current_line_len != line_prefix_len {
14668            current_line.push(' ');
14669            current_line_len += 1;
14670        }
14671    }
14672
14673    if !current_line.is_empty() {
14674        wrapped_text.push_str(&current_line);
14675    }
14676    wrapped_text
14677}
14678
14679#[test]
14680fn test_wrap_with_prefix() {
14681    assert_eq!(
14682        wrap_with_prefix(
14683            "# ".to_string(),
14684            "abcdefg".to_string(),
14685            4,
14686            NonZeroU32::new(4).unwrap()
14687        ),
14688        "# abcdefg"
14689    );
14690    assert_eq!(
14691        wrap_with_prefix(
14692            "".to_string(),
14693            "\thello world".to_string(),
14694            8,
14695            NonZeroU32::new(4).unwrap()
14696        ),
14697        "hello\nworld"
14698    );
14699    assert_eq!(
14700        wrap_with_prefix(
14701            "// ".to_string(),
14702            "xx \nyy zz aa bb cc".to_string(),
14703            12,
14704            NonZeroU32::new(4).unwrap()
14705        ),
14706        "// xx yy zz\n// aa bb cc"
14707    );
14708    assert_eq!(
14709        wrap_with_prefix(
14710            String::new(),
14711            "这是什么 \n 钢笔".to_string(),
14712            3,
14713            NonZeroU32::new(4).unwrap()
14714        ),
14715        "这是什\n么 钢\n"
14716    );
14717}
14718
14719pub trait CollaborationHub {
14720    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14721    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14722    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14723}
14724
14725impl CollaborationHub for Entity<Project> {
14726    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14727        self.read(cx).collaborators()
14728    }
14729
14730    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14731        self.read(cx).user_store().read(cx).participant_indices()
14732    }
14733
14734    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14735        let this = self.read(cx);
14736        let user_ids = this.collaborators().values().map(|c| c.user_id);
14737        this.user_store().read_with(cx, |user_store, cx| {
14738            user_store.participant_names(user_ids, cx)
14739        })
14740    }
14741}
14742
14743pub trait SemanticsProvider {
14744    fn hover(
14745        &self,
14746        buffer: &Entity<Buffer>,
14747        position: text::Anchor,
14748        cx: &mut App,
14749    ) -> Option<Task<Vec<project::Hover>>>;
14750
14751    fn inlay_hints(
14752        &self,
14753        buffer_handle: Entity<Buffer>,
14754        range: Range<text::Anchor>,
14755        cx: &mut App,
14756    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14757
14758    fn resolve_inlay_hint(
14759        &self,
14760        hint: InlayHint,
14761        buffer_handle: Entity<Buffer>,
14762        server_id: LanguageServerId,
14763        cx: &mut App,
14764    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14765
14766    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14767
14768    fn document_highlights(
14769        &self,
14770        buffer: &Entity<Buffer>,
14771        position: text::Anchor,
14772        cx: &mut App,
14773    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14774
14775    fn definitions(
14776        &self,
14777        buffer: &Entity<Buffer>,
14778        position: text::Anchor,
14779        kind: GotoDefinitionKind,
14780        cx: &mut App,
14781    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14782
14783    fn range_for_rename(
14784        &self,
14785        buffer: &Entity<Buffer>,
14786        position: text::Anchor,
14787        cx: &mut App,
14788    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14789
14790    fn perform_rename(
14791        &self,
14792        buffer: &Entity<Buffer>,
14793        position: text::Anchor,
14794        new_name: String,
14795        cx: &mut App,
14796    ) -> Option<Task<Result<ProjectTransaction>>>;
14797}
14798
14799pub trait CompletionProvider {
14800    fn completions(
14801        &self,
14802        buffer: &Entity<Buffer>,
14803        buffer_position: text::Anchor,
14804        trigger: CompletionContext,
14805        window: &mut Window,
14806        cx: &mut Context<Editor>,
14807    ) -> Task<Result<Vec<Completion>>>;
14808
14809    fn resolve_completions(
14810        &self,
14811        buffer: Entity<Buffer>,
14812        completion_indices: Vec<usize>,
14813        completions: Rc<RefCell<Box<[Completion]>>>,
14814        cx: &mut Context<Editor>,
14815    ) -> Task<Result<bool>>;
14816
14817    fn apply_additional_edits_for_completion(
14818        &self,
14819        _buffer: Entity<Buffer>,
14820        _completions: Rc<RefCell<Box<[Completion]>>>,
14821        _completion_index: usize,
14822        _push_to_history: bool,
14823        _cx: &mut Context<Editor>,
14824    ) -> Task<Result<Option<language::Transaction>>> {
14825        Task::ready(Ok(None))
14826    }
14827
14828    fn is_completion_trigger(
14829        &self,
14830        buffer: &Entity<Buffer>,
14831        position: language::Anchor,
14832        text: &str,
14833        trigger_in_words: bool,
14834        cx: &mut Context<Editor>,
14835    ) -> bool;
14836
14837    fn sort_completions(&self) -> bool {
14838        true
14839    }
14840}
14841
14842pub trait CodeActionProvider {
14843    fn id(&self) -> Arc<str>;
14844
14845    fn code_actions(
14846        &self,
14847        buffer: &Entity<Buffer>,
14848        range: Range<text::Anchor>,
14849        window: &mut Window,
14850        cx: &mut App,
14851    ) -> Task<Result<Vec<CodeAction>>>;
14852
14853    fn apply_code_action(
14854        &self,
14855        buffer_handle: Entity<Buffer>,
14856        action: CodeAction,
14857        excerpt_id: ExcerptId,
14858        push_to_history: bool,
14859        window: &mut Window,
14860        cx: &mut App,
14861    ) -> Task<Result<ProjectTransaction>>;
14862}
14863
14864impl CodeActionProvider for Entity<Project> {
14865    fn id(&self) -> Arc<str> {
14866        "project".into()
14867    }
14868
14869    fn code_actions(
14870        &self,
14871        buffer: &Entity<Buffer>,
14872        range: Range<text::Anchor>,
14873        _window: &mut Window,
14874        cx: &mut App,
14875    ) -> Task<Result<Vec<CodeAction>>> {
14876        self.update(cx, |project, cx| {
14877            project.code_actions(buffer, range, None, cx)
14878        })
14879    }
14880
14881    fn apply_code_action(
14882        &self,
14883        buffer_handle: Entity<Buffer>,
14884        action: CodeAction,
14885        _excerpt_id: ExcerptId,
14886        push_to_history: bool,
14887        _window: &mut Window,
14888        cx: &mut App,
14889    ) -> Task<Result<ProjectTransaction>> {
14890        self.update(cx, |project, cx| {
14891            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14892        })
14893    }
14894}
14895
14896fn snippet_completions(
14897    project: &Project,
14898    buffer: &Entity<Buffer>,
14899    buffer_position: text::Anchor,
14900    cx: &mut App,
14901) -> Task<Result<Vec<Completion>>> {
14902    let language = buffer.read(cx).language_at(buffer_position);
14903    let language_name = language.as_ref().map(|language| language.lsp_id());
14904    let snippet_store = project.snippets().read(cx);
14905    let snippets = snippet_store.snippets_for(language_name, cx);
14906
14907    if snippets.is_empty() {
14908        return Task::ready(Ok(vec![]));
14909    }
14910    let snapshot = buffer.read(cx).text_snapshot();
14911    let chars: String = snapshot
14912        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14913        .collect();
14914
14915    let scope = language.map(|language| language.default_scope());
14916    let executor = cx.background_executor().clone();
14917
14918    cx.background_executor().spawn(async move {
14919        let classifier = CharClassifier::new(scope).for_completion(true);
14920        let mut last_word = chars
14921            .chars()
14922            .take_while(|c| classifier.is_word(*c))
14923            .collect::<String>();
14924        last_word = last_word.chars().rev().collect();
14925
14926        if last_word.is_empty() {
14927            return Ok(vec![]);
14928        }
14929
14930        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14931        let to_lsp = |point: &text::Anchor| {
14932            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14933            point_to_lsp(end)
14934        };
14935        let lsp_end = to_lsp(&buffer_position);
14936
14937        let candidates = snippets
14938            .iter()
14939            .enumerate()
14940            .flat_map(|(ix, snippet)| {
14941                snippet
14942                    .prefix
14943                    .iter()
14944                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14945            })
14946            .collect::<Vec<StringMatchCandidate>>();
14947
14948        let mut matches = fuzzy::match_strings(
14949            &candidates,
14950            &last_word,
14951            last_word.chars().any(|c| c.is_uppercase()),
14952            100,
14953            &Default::default(),
14954            executor,
14955        )
14956        .await;
14957
14958        // Remove all candidates where the query's start does not match the start of any word in the candidate
14959        if let Some(query_start) = last_word.chars().next() {
14960            matches.retain(|string_match| {
14961                split_words(&string_match.string).any(|word| {
14962                    // Check that the first codepoint of the word as lowercase matches the first
14963                    // codepoint of the query as lowercase
14964                    word.chars()
14965                        .flat_map(|codepoint| codepoint.to_lowercase())
14966                        .zip(query_start.to_lowercase())
14967                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14968                })
14969            });
14970        }
14971
14972        let matched_strings = matches
14973            .into_iter()
14974            .map(|m| m.string)
14975            .collect::<HashSet<_>>();
14976
14977        let result: Vec<Completion> = snippets
14978            .into_iter()
14979            .filter_map(|snippet| {
14980                let matching_prefix = snippet
14981                    .prefix
14982                    .iter()
14983                    .find(|prefix| matched_strings.contains(*prefix))?;
14984                let start = as_offset - last_word.len();
14985                let start = snapshot.anchor_before(start);
14986                let range = start..buffer_position;
14987                let lsp_start = to_lsp(&start);
14988                let lsp_range = lsp::Range {
14989                    start: lsp_start,
14990                    end: lsp_end,
14991                };
14992                Some(Completion {
14993                    old_range: range,
14994                    new_text: snippet.body.clone(),
14995                    resolved: false,
14996                    label: CodeLabel {
14997                        text: matching_prefix.clone(),
14998                        runs: vec![],
14999                        filter_range: 0..matching_prefix.len(),
15000                    },
15001                    server_id: LanguageServerId(usize::MAX),
15002                    documentation: snippet
15003                        .description
15004                        .clone()
15005                        .map(CompletionDocumentation::SingleLine),
15006                    lsp_completion: lsp::CompletionItem {
15007                        label: snippet.prefix.first().unwrap().clone(),
15008                        kind: Some(CompletionItemKind::SNIPPET),
15009                        label_details: snippet.description.as_ref().map(|description| {
15010                            lsp::CompletionItemLabelDetails {
15011                                detail: Some(description.clone()),
15012                                description: None,
15013                            }
15014                        }),
15015                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15016                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15017                            lsp::InsertReplaceEdit {
15018                                new_text: snippet.body.clone(),
15019                                insert: lsp_range,
15020                                replace: lsp_range,
15021                            },
15022                        )),
15023                        filter_text: Some(snippet.body.clone()),
15024                        sort_text: Some(char::MAX.to_string()),
15025                        ..Default::default()
15026                    },
15027                    confirm: None,
15028                })
15029            })
15030            .collect();
15031
15032        Ok(result)
15033    })
15034}
15035
15036impl CompletionProvider for Entity<Project> {
15037    fn completions(
15038        &self,
15039        buffer: &Entity<Buffer>,
15040        buffer_position: text::Anchor,
15041        options: CompletionContext,
15042        _window: &mut Window,
15043        cx: &mut Context<Editor>,
15044    ) -> Task<Result<Vec<Completion>>> {
15045        self.update(cx, |project, cx| {
15046            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15047            let project_completions = project.completions(buffer, buffer_position, options, cx);
15048            cx.background_executor().spawn(async move {
15049                let mut completions = project_completions.await?;
15050                let snippets_completions = snippets.await?;
15051                completions.extend(snippets_completions);
15052                Ok(completions)
15053            })
15054        })
15055    }
15056
15057    fn resolve_completions(
15058        &self,
15059        buffer: Entity<Buffer>,
15060        completion_indices: Vec<usize>,
15061        completions: Rc<RefCell<Box<[Completion]>>>,
15062        cx: &mut Context<Editor>,
15063    ) -> Task<Result<bool>> {
15064        self.update(cx, |project, cx| {
15065            project.lsp_store().update(cx, |lsp_store, cx| {
15066                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15067            })
15068        })
15069    }
15070
15071    fn apply_additional_edits_for_completion(
15072        &self,
15073        buffer: Entity<Buffer>,
15074        completions: Rc<RefCell<Box<[Completion]>>>,
15075        completion_index: usize,
15076        push_to_history: bool,
15077        cx: &mut Context<Editor>,
15078    ) -> Task<Result<Option<language::Transaction>>> {
15079        self.update(cx, |project, cx| {
15080            project.lsp_store().update(cx, |lsp_store, cx| {
15081                lsp_store.apply_additional_edits_for_completion(
15082                    buffer,
15083                    completions,
15084                    completion_index,
15085                    push_to_history,
15086                    cx,
15087                )
15088            })
15089        })
15090    }
15091
15092    fn is_completion_trigger(
15093        &self,
15094        buffer: &Entity<Buffer>,
15095        position: language::Anchor,
15096        text: &str,
15097        trigger_in_words: bool,
15098        cx: &mut Context<Editor>,
15099    ) -> bool {
15100        let mut chars = text.chars();
15101        let char = if let Some(char) = chars.next() {
15102            char
15103        } else {
15104            return false;
15105        };
15106        if chars.next().is_some() {
15107            return false;
15108        }
15109
15110        let buffer = buffer.read(cx);
15111        let snapshot = buffer.snapshot();
15112        if !snapshot.settings_at(position, cx).show_completions_on_input {
15113            return false;
15114        }
15115        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15116        if trigger_in_words && classifier.is_word(char) {
15117            return true;
15118        }
15119
15120        buffer.completion_triggers().contains(text)
15121    }
15122}
15123
15124impl SemanticsProvider for Entity<Project> {
15125    fn hover(
15126        &self,
15127        buffer: &Entity<Buffer>,
15128        position: text::Anchor,
15129        cx: &mut App,
15130    ) -> Option<Task<Vec<project::Hover>>> {
15131        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15132    }
15133
15134    fn document_highlights(
15135        &self,
15136        buffer: &Entity<Buffer>,
15137        position: text::Anchor,
15138        cx: &mut App,
15139    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15140        Some(self.update(cx, |project, cx| {
15141            project.document_highlights(buffer, position, cx)
15142        }))
15143    }
15144
15145    fn definitions(
15146        &self,
15147        buffer: &Entity<Buffer>,
15148        position: text::Anchor,
15149        kind: GotoDefinitionKind,
15150        cx: &mut App,
15151    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15152        Some(self.update(cx, |project, cx| match kind {
15153            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15154            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15155            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15156            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15157        }))
15158    }
15159
15160    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15161        // TODO: make this work for remote projects
15162        self.read(cx)
15163            .language_servers_for_local_buffer(buffer.read(cx), cx)
15164            .any(
15165                |(_, server)| match server.capabilities().inlay_hint_provider {
15166                    Some(lsp::OneOf::Left(enabled)) => enabled,
15167                    Some(lsp::OneOf::Right(_)) => true,
15168                    None => false,
15169                },
15170            )
15171    }
15172
15173    fn inlay_hints(
15174        &self,
15175        buffer_handle: Entity<Buffer>,
15176        range: Range<text::Anchor>,
15177        cx: &mut App,
15178    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15179        Some(self.update(cx, |project, cx| {
15180            project.inlay_hints(buffer_handle, range, cx)
15181        }))
15182    }
15183
15184    fn resolve_inlay_hint(
15185        &self,
15186        hint: InlayHint,
15187        buffer_handle: Entity<Buffer>,
15188        server_id: LanguageServerId,
15189        cx: &mut App,
15190    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15191        Some(self.update(cx, |project, cx| {
15192            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15193        }))
15194    }
15195
15196    fn range_for_rename(
15197        &self,
15198        buffer: &Entity<Buffer>,
15199        position: text::Anchor,
15200        cx: &mut App,
15201    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15202        Some(self.update(cx, |project, cx| {
15203            let buffer = buffer.clone();
15204            let task = project.prepare_rename(buffer.clone(), position, cx);
15205            cx.spawn(|_, mut cx| async move {
15206                Ok(match task.await? {
15207                    PrepareRenameResponse::Success(range) => Some(range),
15208                    PrepareRenameResponse::InvalidPosition => None,
15209                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15210                        // Fallback on using TreeSitter info to determine identifier range
15211                        buffer.update(&mut cx, |buffer, _| {
15212                            let snapshot = buffer.snapshot();
15213                            let (range, kind) = snapshot.surrounding_word(position);
15214                            if kind != Some(CharKind::Word) {
15215                                return None;
15216                            }
15217                            Some(
15218                                snapshot.anchor_before(range.start)
15219                                    ..snapshot.anchor_after(range.end),
15220                            )
15221                        })?
15222                    }
15223                })
15224            })
15225        }))
15226    }
15227
15228    fn perform_rename(
15229        &self,
15230        buffer: &Entity<Buffer>,
15231        position: text::Anchor,
15232        new_name: String,
15233        cx: &mut App,
15234    ) -> Option<Task<Result<ProjectTransaction>>> {
15235        Some(self.update(cx, |project, cx| {
15236            project.perform_rename(buffer.clone(), position, new_name, cx)
15237        }))
15238    }
15239}
15240
15241fn inlay_hint_settings(
15242    location: Anchor,
15243    snapshot: &MultiBufferSnapshot,
15244    cx: &mut Context<Editor>,
15245) -> InlayHintSettings {
15246    let file = snapshot.file_at(location);
15247    let language = snapshot.language_at(location).map(|l| l.name());
15248    language_settings(language, file, cx).inlay_hints
15249}
15250
15251fn consume_contiguous_rows(
15252    contiguous_row_selections: &mut Vec<Selection<Point>>,
15253    selection: &Selection<Point>,
15254    display_map: &DisplaySnapshot,
15255    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15256) -> (MultiBufferRow, MultiBufferRow) {
15257    contiguous_row_selections.push(selection.clone());
15258    let start_row = MultiBufferRow(selection.start.row);
15259    let mut end_row = ending_row(selection, display_map);
15260
15261    while let Some(next_selection) = selections.peek() {
15262        if next_selection.start.row <= end_row.0 {
15263            end_row = ending_row(next_selection, display_map);
15264            contiguous_row_selections.push(selections.next().unwrap().clone());
15265        } else {
15266            break;
15267        }
15268    }
15269    (start_row, end_row)
15270}
15271
15272fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15273    if next_selection.end.column > 0 || next_selection.is_empty() {
15274        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15275    } else {
15276        MultiBufferRow(next_selection.end.row)
15277    }
15278}
15279
15280impl EditorSnapshot {
15281    pub fn remote_selections_in_range<'a>(
15282        &'a self,
15283        range: &'a Range<Anchor>,
15284        collaboration_hub: &dyn CollaborationHub,
15285        cx: &'a App,
15286    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15287        let participant_names = collaboration_hub.user_names(cx);
15288        let participant_indices = collaboration_hub.user_participant_indices(cx);
15289        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15290        let collaborators_by_replica_id = collaborators_by_peer_id
15291            .iter()
15292            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15293            .collect::<HashMap<_, _>>();
15294        self.buffer_snapshot
15295            .selections_in_range(range, false)
15296            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15297                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15298                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15299                let user_name = participant_names.get(&collaborator.user_id).cloned();
15300                Some(RemoteSelection {
15301                    replica_id,
15302                    selection,
15303                    cursor_shape,
15304                    line_mode,
15305                    participant_index,
15306                    peer_id: collaborator.peer_id,
15307                    user_name,
15308                })
15309            })
15310    }
15311
15312    pub fn hunks_for_ranges(
15313        &self,
15314        ranges: impl Iterator<Item = Range<Point>>,
15315    ) -> Vec<MultiBufferDiffHunk> {
15316        let mut hunks = Vec::new();
15317        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15318            HashMap::default();
15319        for query_range in ranges {
15320            let query_rows =
15321                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15322            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15323                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15324            ) {
15325                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15326                // when the caret is just above or just below the deleted hunk.
15327                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15328                let related_to_selection = if allow_adjacent {
15329                    hunk.row_range.overlaps(&query_rows)
15330                        || hunk.row_range.start == query_rows.end
15331                        || hunk.row_range.end == query_rows.start
15332                } else {
15333                    hunk.row_range.overlaps(&query_rows)
15334                };
15335                if related_to_selection {
15336                    if !processed_buffer_rows
15337                        .entry(hunk.buffer_id)
15338                        .or_default()
15339                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15340                    {
15341                        continue;
15342                    }
15343                    hunks.push(hunk);
15344                }
15345            }
15346        }
15347
15348        hunks
15349    }
15350
15351    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15352        self.display_snapshot.buffer_snapshot.language_at(position)
15353    }
15354
15355    pub fn is_focused(&self) -> bool {
15356        self.is_focused
15357    }
15358
15359    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15360        self.placeholder_text.as_ref()
15361    }
15362
15363    pub fn scroll_position(&self) -> gpui::Point<f32> {
15364        self.scroll_anchor.scroll_position(&self.display_snapshot)
15365    }
15366
15367    fn gutter_dimensions(
15368        &self,
15369        font_id: FontId,
15370        font_size: Pixels,
15371        max_line_number_width: Pixels,
15372        cx: &App,
15373    ) -> Option<GutterDimensions> {
15374        if !self.show_gutter {
15375            return None;
15376        }
15377
15378        let descent = cx.text_system().descent(font_id, font_size);
15379        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15380        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15381
15382        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15383            matches!(
15384                ProjectSettings::get_global(cx).git.git_gutter,
15385                Some(GitGutterSetting::TrackedFiles)
15386            )
15387        });
15388        let gutter_settings = EditorSettings::get_global(cx).gutter;
15389        let show_line_numbers = self
15390            .show_line_numbers
15391            .unwrap_or(gutter_settings.line_numbers);
15392        let line_gutter_width = if show_line_numbers {
15393            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15394            let min_width_for_number_on_gutter = em_advance * 4.0;
15395            max_line_number_width.max(min_width_for_number_on_gutter)
15396        } else {
15397            0.0.into()
15398        };
15399
15400        let show_code_actions = self
15401            .show_code_actions
15402            .unwrap_or(gutter_settings.code_actions);
15403
15404        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15405
15406        let git_blame_entries_width =
15407            self.git_blame_gutter_max_author_length
15408                .map(|max_author_length| {
15409                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15410
15411                    /// The number of characters to dedicate to gaps and margins.
15412                    const SPACING_WIDTH: usize = 4;
15413
15414                    let max_char_count = max_author_length
15415                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15416                        + ::git::SHORT_SHA_LENGTH
15417                        + MAX_RELATIVE_TIMESTAMP.len()
15418                        + SPACING_WIDTH;
15419
15420                    em_advance * max_char_count
15421                });
15422
15423        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15424        left_padding += if show_code_actions || show_runnables {
15425            em_width * 3.0
15426        } else if show_git_gutter && show_line_numbers {
15427            em_width * 2.0
15428        } else if show_git_gutter || show_line_numbers {
15429            em_width
15430        } else {
15431            px(0.)
15432        };
15433
15434        let right_padding = if gutter_settings.folds && show_line_numbers {
15435            em_width * 4.0
15436        } else if gutter_settings.folds {
15437            em_width * 3.0
15438        } else if show_line_numbers {
15439            em_width
15440        } else {
15441            px(0.)
15442        };
15443
15444        Some(GutterDimensions {
15445            left_padding,
15446            right_padding,
15447            width: line_gutter_width + left_padding + right_padding,
15448            margin: -descent,
15449            git_blame_entries_width,
15450        })
15451    }
15452
15453    pub fn render_crease_toggle(
15454        &self,
15455        buffer_row: MultiBufferRow,
15456        row_contains_cursor: bool,
15457        editor: Entity<Editor>,
15458        window: &mut Window,
15459        cx: &mut App,
15460    ) -> Option<AnyElement> {
15461        let folded = self.is_line_folded(buffer_row);
15462        let mut is_foldable = false;
15463
15464        if let Some(crease) = self
15465            .crease_snapshot
15466            .query_row(buffer_row, &self.buffer_snapshot)
15467        {
15468            is_foldable = true;
15469            match crease {
15470                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15471                    if let Some(render_toggle) = render_toggle {
15472                        let toggle_callback =
15473                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15474                                if folded {
15475                                    editor.update(cx, |editor, cx| {
15476                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15477                                    });
15478                                } else {
15479                                    editor.update(cx, |editor, cx| {
15480                                        editor.unfold_at(
15481                                            &crate::UnfoldAt { buffer_row },
15482                                            window,
15483                                            cx,
15484                                        )
15485                                    });
15486                                }
15487                            });
15488                        return Some((render_toggle)(
15489                            buffer_row,
15490                            folded,
15491                            toggle_callback,
15492                            window,
15493                            cx,
15494                        ));
15495                    }
15496                }
15497            }
15498        }
15499
15500        is_foldable |= self.starts_indent(buffer_row);
15501
15502        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15503            Some(
15504                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15505                    .toggle_state(folded)
15506                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15507                        if folded {
15508                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15509                        } else {
15510                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15511                        }
15512                    }))
15513                    .into_any_element(),
15514            )
15515        } else {
15516            None
15517        }
15518    }
15519
15520    pub fn render_crease_trailer(
15521        &self,
15522        buffer_row: MultiBufferRow,
15523        window: &mut Window,
15524        cx: &mut App,
15525    ) -> Option<AnyElement> {
15526        let folded = self.is_line_folded(buffer_row);
15527        if let Crease::Inline { render_trailer, .. } = self
15528            .crease_snapshot
15529            .query_row(buffer_row, &self.buffer_snapshot)?
15530        {
15531            let render_trailer = render_trailer.as_ref()?;
15532            Some(render_trailer(buffer_row, folded, window, cx))
15533        } else {
15534            None
15535        }
15536    }
15537}
15538
15539impl Deref for EditorSnapshot {
15540    type Target = DisplaySnapshot;
15541
15542    fn deref(&self) -> &Self::Target {
15543        &self.display_snapshot
15544    }
15545}
15546
15547#[derive(Clone, Debug, PartialEq, Eq)]
15548pub enum EditorEvent {
15549    InputIgnored {
15550        text: Arc<str>,
15551    },
15552    InputHandled {
15553        utf16_range_to_replace: Option<Range<isize>>,
15554        text: Arc<str>,
15555    },
15556    ExcerptsAdded {
15557        buffer: Entity<Buffer>,
15558        predecessor: ExcerptId,
15559        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15560    },
15561    ExcerptsRemoved {
15562        ids: Vec<ExcerptId>,
15563    },
15564    BufferFoldToggled {
15565        ids: Vec<ExcerptId>,
15566        folded: bool,
15567    },
15568    ExcerptsEdited {
15569        ids: Vec<ExcerptId>,
15570    },
15571    ExcerptsExpanded {
15572        ids: Vec<ExcerptId>,
15573    },
15574    BufferEdited,
15575    Edited {
15576        transaction_id: clock::Lamport,
15577    },
15578    Reparsed(BufferId),
15579    Focused,
15580    FocusedIn,
15581    Blurred,
15582    DirtyChanged,
15583    Saved,
15584    TitleChanged,
15585    DiffBaseChanged,
15586    SelectionsChanged {
15587        local: bool,
15588    },
15589    ScrollPositionChanged {
15590        local: bool,
15591        autoscroll: bool,
15592    },
15593    Closed,
15594    TransactionUndone {
15595        transaction_id: clock::Lamport,
15596    },
15597    TransactionBegun {
15598        transaction_id: clock::Lamport,
15599    },
15600    Reloaded,
15601    CursorShapeChanged,
15602}
15603
15604impl EventEmitter<EditorEvent> for Editor {}
15605
15606impl Focusable for Editor {
15607    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15608        self.focus_handle.clone()
15609    }
15610}
15611
15612impl Render for Editor {
15613    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15614        let settings = ThemeSettings::get_global(cx);
15615
15616        let mut text_style = match self.mode {
15617            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15618                color: cx.theme().colors().editor_foreground,
15619                font_family: settings.ui_font.family.clone(),
15620                font_features: settings.ui_font.features.clone(),
15621                font_fallbacks: settings.ui_font.fallbacks.clone(),
15622                font_size: rems(0.875).into(),
15623                font_weight: settings.ui_font.weight,
15624                line_height: relative(settings.buffer_line_height.value()),
15625                ..Default::default()
15626            },
15627            EditorMode::Full => TextStyle {
15628                color: cx.theme().colors().editor_foreground,
15629                font_family: settings.buffer_font.family.clone(),
15630                font_features: settings.buffer_font.features.clone(),
15631                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15632                font_size: settings.buffer_font_size().into(),
15633                font_weight: settings.buffer_font.weight,
15634                line_height: relative(settings.buffer_line_height.value()),
15635                ..Default::default()
15636            },
15637        };
15638        if let Some(text_style_refinement) = &self.text_style_refinement {
15639            text_style.refine(text_style_refinement)
15640        }
15641
15642        let background = match self.mode {
15643            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15644            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15645            EditorMode::Full => cx.theme().colors().editor_background,
15646        };
15647
15648        EditorElement::new(
15649            &cx.entity(),
15650            EditorStyle {
15651                background,
15652                local_player: cx.theme().players().local(),
15653                text: text_style,
15654                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15655                syntax: cx.theme().syntax().clone(),
15656                status: cx.theme().status().clone(),
15657                inlay_hints_style: make_inlay_hints_style(cx),
15658                inline_completion_styles: make_suggestion_styles(cx),
15659                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15660            },
15661        )
15662    }
15663}
15664
15665impl EntityInputHandler for Editor {
15666    fn text_for_range(
15667        &mut self,
15668        range_utf16: Range<usize>,
15669        adjusted_range: &mut Option<Range<usize>>,
15670        _: &mut Window,
15671        cx: &mut Context<Self>,
15672    ) -> Option<String> {
15673        let snapshot = self.buffer.read(cx).read(cx);
15674        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15675        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15676        if (start.0..end.0) != range_utf16 {
15677            adjusted_range.replace(start.0..end.0);
15678        }
15679        Some(snapshot.text_for_range(start..end).collect())
15680    }
15681
15682    fn selected_text_range(
15683        &mut self,
15684        ignore_disabled_input: bool,
15685        _: &mut Window,
15686        cx: &mut Context<Self>,
15687    ) -> Option<UTF16Selection> {
15688        // Prevent the IME menu from appearing when holding down an alphabetic key
15689        // while input is disabled.
15690        if !ignore_disabled_input && !self.input_enabled {
15691            return None;
15692        }
15693
15694        let selection = self.selections.newest::<OffsetUtf16>(cx);
15695        let range = selection.range();
15696
15697        Some(UTF16Selection {
15698            range: range.start.0..range.end.0,
15699            reversed: selection.reversed,
15700        })
15701    }
15702
15703    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15704        let snapshot = self.buffer.read(cx).read(cx);
15705        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15706        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15707    }
15708
15709    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15710        self.clear_highlights::<InputComposition>(cx);
15711        self.ime_transaction.take();
15712    }
15713
15714    fn replace_text_in_range(
15715        &mut self,
15716        range_utf16: Option<Range<usize>>,
15717        text: &str,
15718        window: &mut Window,
15719        cx: &mut Context<Self>,
15720    ) {
15721        if !self.input_enabled {
15722            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15723            return;
15724        }
15725
15726        self.transact(window, cx, |this, window, cx| {
15727            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15728                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15729                Some(this.selection_replacement_ranges(range_utf16, cx))
15730            } else {
15731                this.marked_text_ranges(cx)
15732            };
15733
15734            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15735                let newest_selection_id = this.selections.newest_anchor().id;
15736                this.selections
15737                    .all::<OffsetUtf16>(cx)
15738                    .iter()
15739                    .zip(ranges_to_replace.iter())
15740                    .find_map(|(selection, range)| {
15741                        if selection.id == newest_selection_id {
15742                            Some(
15743                                (range.start.0 as isize - selection.head().0 as isize)
15744                                    ..(range.end.0 as isize - selection.head().0 as isize),
15745                            )
15746                        } else {
15747                            None
15748                        }
15749                    })
15750            });
15751
15752            cx.emit(EditorEvent::InputHandled {
15753                utf16_range_to_replace: range_to_replace,
15754                text: text.into(),
15755            });
15756
15757            if let Some(new_selected_ranges) = new_selected_ranges {
15758                this.change_selections(None, window, cx, |selections| {
15759                    selections.select_ranges(new_selected_ranges)
15760                });
15761                this.backspace(&Default::default(), window, cx);
15762            }
15763
15764            this.handle_input(text, window, cx);
15765        });
15766
15767        if let Some(transaction) = self.ime_transaction {
15768            self.buffer.update(cx, |buffer, cx| {
15769                buffer.group_until_transaction(transaction, cx);
15770            });
15771        }
15772
15773        self.unmark_text(window, cx);
15774    }
15775
15776    fn replace_and_mark_text_in_range(
15777        &mut self,
15778        range_utf16: Option<Range<usize>>,
15779        text: &str,
15780        new_selected_range_utf16: Option<Range<usize>>,
15781        window: &mut Window,
15782        cx: &mut Context<Self>,
15783    ) {
15784        if !self.input_enabled {
15785            return;
15786        }
15787
15788        let transaction = self.transact(window, cx, |this, window, cx| {
15789            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15790                let snapshot = this.buffer.read(cx).read(cx);
15791                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15792                    for marked_range in &mut marked_ranges {
15793                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15794                        marked_range.start.0 += relative_range_utf16.start;
15795                        marked_range.start =
15796                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15797                        marked_range.end =
15798                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15799                    }
15800                }
15801                Some(marked_ranges)
15802            } else if let Some(range_utf16) = range_utf16 {
15803                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15804                Some(this.selection_replacement_ranges(range_utf16, cx))
15805            } else {
15806                None
15807            };
15808
15809            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15810                let newest_selection_id = this.selections.newest_anchor().id;
15811                this.selections
15812                    .all::<OffsetUtf16>(cx)
15813                    .iter()
15814                    .zip(ranges_to_replace.iter())
15815                    .find_map(|(selection, range)| {
15816                        if selection.id == newest_selection_id {
15817                            Some(
15818                                (range.start.0 as isize - selection.head().0 as isize)
15819                                    ..(range.end.0 as isize - selection.head().0 as isize),
15820                            )
15821                        } else {
15822                            None
15823                        }
15824                    })
15825            });
15826
15827            cx.emit(EditorEvent::InputHandled {
15828                utf16_range_to_replace: range_to_replace,
15829                text: text.into(),
15830            });
15831
15832            if let Some(ranges) = ranges_to_replace {
15833                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15834            }
15835
15836            let marked_ranges = {
15837                let snapshot = this.buffer.read(cx).read(cx);
15838                this.selections
15839                    .disjoint_anchors()
15840                    .iter()
15841                    .map(|selection| {
15842                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15843                    })
15844                    .collect::<Vec<_>>()
15845            };
15846
15847            if text.is_empty() {
15848                this.unmark_text(window, cx);
15849            } else {
15850                this.highlight_text::<InputComposition>(
15851                    marked_ranges.clone(),
15852                    HighlightStyle {
15853                        underline: Some(UnderlineStyle {
15854                            thickness: px(1.),
15855                            color: None,
15856                            wavy: false,
15857                        }),
15858                        ..Default::default()
15859                    },
15860                    cx,
15861                );
15862            }
15863
15864            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15865            let use_autoclose = this.use_autoclose;
15866            let use_auto_surround = this.use_auto_surround;
15867            this.set_use_autoclose(false);
15868            this.set_use_auto_surround(false);
15869            this.handle_input(text, window, cx);
15870            this.set_use_autoclose(use_autoclose);
15871            this.set_use_auto_surround(use_auto_surround);
15872
15873            if let Some(new_selected_range) = new_selected_range_utf16 {
15874                let snapshot = this.buffer.read(cx).read(cx);
15875                let new_selected_ranges = marked_ranges
15876                    .into_iter()
15877                    .map(|marked_range| {
15878                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15879                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15880                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15881                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15882                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15883                    })
15884                    .collect::<Vec<_>>();
15885
15886                drop(snapshot);
15887                this.change_selections(None, window, cx, |selections| {
15888                    selections.select_ranges(new_selected_ranges)
15889                });
15890            }
15891        });
15892
15893        self.ime_transaction = self.ime_transaction.or(transaction);
15894        if let Some(transaction) = self.ime_transaction {
15895            self.buffer.update(cx, |buffer, cx| {
15896                buffer.group_until_transaction(transaction, cx);
15897            });
15898        }
15899
15900        if self.text_highlights::<InputComposition>(cx).is_none() {
15901            self.ime_transaction.take();
15902        }
15903    }
15904
15905    fn bounds_for_range(
15906        &mut self,
15907        range_utf16: Range<usize>,
15908        element_bounds: gpui::Bounds<Pixels>,
15909        window: &mut Window,
15910        cx: &mut Context<Self>,
15911    ) -> Option<gpui::Bounds<Pixels>> {
15912        let text_layout_details = self.text_layout_details(window);
15913        let gpui::Point {
15914            x: em_width,
15915            y: line_height,
15916        } = self.character_size(window);
15917
15918        let snapshot = self.snapshot(window, cx);
15919        let scroll_position = snapshot.scroll_position();
15920        let scroll_left = scroll_position.x * em_width;
15921
15922        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15923        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15924            + self.gutter_dimensions.width
15925            + self.gutter_dimensions.margin;
15926        let y = line_height * (start.row().as_f32() - scroll_position.y);
15927
15928        Some(Bounds {
15929            origin: element_bounds.origin + point(x, y),
15930            size: size(em_width, line_height),
15931        })
15932    }
15933}
15934
15935trait SelectionExt {
15936    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15937    fn spanned_rows(
15938        &self,
15939        include_end_if_at_line_start: bool,
15940        map: &DisplaySnapshot,
15941    ) -> Range<MultiBufferRow>;
15942}
15943
15944impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15945    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15946        let start = self
15947            .start
15948            .to_point(&map.buffer_snapshot)
15949            .to_display_point(map);
15950        let end = self
15951            .end
15952            .to_point(&map.buffer_snapshot)
15953            .to_display_point(map);
15954        if self.reversed {
15955            end..start
15956        } else {
15957            start..end
15958        }
15959    }
15960
15961    fn spanned_rows(
15962        &self,
15963        include_end_if_at_line_start: bool,
15964        map: &DisplaySnapshot,
15965    ) -> Range<MultiBufferRow> {
15966        let start = self.start.to_point(&map.buffer_snapshot);
15967        let mut end = self.end.to_point(&map.buffer_snapshot);
15968        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15969            end.row -= 1;
15970        }
15971
15972        let buffer_start = map.prev_line_boundary(start).0;
15973        let buffer_end = map.next_line_boundary(end).0;
15974        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15975    }
15976}
15977
15978impl<T: InvalidationRegion> InvalidationStack<T> {
15979    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15980    where
15981        S: Clone + ToOffset,
15982    {
15983        while let Some(region) = self.last() {
15984            let all_selections_inside_invalidation_ranges =
15985                if selections.len() == region.ranges().len() {
15986                    selections
15987                        .iter()
15988                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15989                        .all(|(selection, invalidation_range)| {
15990                            let head = selection.head().to_offset(buffer);
15991                            invalidation_range.start <= head && invalidation_range.end >= head
15992                        })
15993                } else {
15994                    false
15995                };
15996
15997            if all_selections_inside_invalidation_ranges {
15998                break;
15999            } else {
16000                self.pop();
16001            }
16002        }
16003    }
16004}
16005
16006impl<T> Default for InvalidationStack<T> {
16007    fn default() -> Self {
16008        Self(Default::default())
16009    }
16010}
16011
16012impl<T> Deref for InvalidationStack<T> {
16013    type Target = Vec<T>;
16014
16015    fn deref(&self) -> &Self::Target {
16016        &self.0
16017    }
16018}
16019
16020impl<T> DerefMut for InvalidationStack<T> {
16021    fn deref_mut(&mut self) -> &mut Self::Target {
16022        &mut self.0
16023    }
16024}
16025
16026impl InvalidationRegion for SnippetState {
16027    fn ranges(&self) -> &[Range<Anchor>] {
16028        &self.ranges[self.active_index]
16029    }
16030}
16031
16032pub fn diagnostic_block_renderer(
16033    diagnostic: Diagnostic,
16034    max_message_rows: Option<u8>,
16035    allow_closing: bool,
16036    _is_valid: bool,
16037) -> RenderBlock {
16038    let (text_without_backticks, code_ranges) =
16039        highlight_diagnostic_message(&diagnostic, max_message_rows);
16040
16041    Arc::new(move |cx: &mut BlockContext| {
16042        let group_id: SharedString = cx.block_id.to_string().into();
16043
16044        let mut text_style = cx.window.text_style().clone();
16045        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16046        let theme_settings = ThemeSettings::get_global(cx);
16047        text_style.font_family = theme_settings.buffer_font.family.clone();
16048        text_style.font_style = theme_settings.buffer_font.style;
16049        text_style.font_features = theme_settings.buffer_font.features.clone();
16050        text_style.font_weight = theme_settings.buffer_font.weight;
16051
16052        let multi_line_diagnostic = diagnostic.message.contains('\n');
16053
16054        let buttons = |diagnostic: &Diagnostic| {
16055            if multi_line_diagnostic {
16056                v_flex()
16057            } else {
16058                h_flex()
16059            }
16060            .when(allow_closing, |div| {
16061                div.children(diagnostic.is_primary.then(|| {
16062                    IconButton::new("close-block", IconName::XCircle)
16063                        .icon_color(Color::Muted)
16064                        .size(ButtonSize::Compact)
16065                        .style(ButtonStyle::Transparent)
16066                        .visible_on_hover(group_id.clone())
16067                        .on_click(move |_click, window, cx| {
16068                            window.dispatch_action(Box::new(Cancel), cx)
16069                        })
16070                        .tooltip(|window, cx| {
16071                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16072                        })
16073                }))
16074            })
16075            .child(
16076                IconButton::new("copy-block", IconName::Copy)
16077                    .icon_color(Color::Muted)
16078                    .size(ButtonSize::Compact)
16079                    .style(ButtonStyle::Transparent)
16080                    .visible_on_hover(group_id.clone())
16081                    .on_click({
16082                        let message = diagnostic.message.clone();
16083                        move |_click, _, cx| {
16084                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16085                        }
16086                    })
16087                    .tooltip(Tooltip::text("Copy diagnostic message")),
16088            )
16089        };
16090
16091        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16092            AvailableSpace::min_size(),
16093            cx.window,
16094            cx.app,
16095        );
16096
16097        h_flex()
16098            .id(cx.block_id)
16099            .group(group_id.clone())
16100            .relative()
16101            .size_full()
16102            .block_mouse_down()
16103            .pl(cx.gutter_dimensions.width)
16104            .w(cx.max_width - cx.gutter_dimensions.full_width())
16105            .child(
16106                div()
16107                    .flex()
16108                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16109                    .flex_shrink(),
16110            )
16111            .child(buttons(&diagnostic))
16112            .child(div().flex().flex_shrink_0().child(
16113                StyledText::new(text_without_backticks.clone()).with_highlights(
16114                    &text_style,
16115                    code_ranges.iter().map(|range| {
16116                        (
16117                            range.clone(),
16118                            HighlightStyle {
16119                                font_weight: Some(FontWeight::BOLD),
16120                                ..Default::default()
16121                            },
16122                        )
16123                    }),
16124                ),
16125            ))
16126            .into_any_element()
16127    })
16128}
16129
16130fn inline_completion_edit_text(
16131    current_snapshot: &BufferSnapshot,
16132    edits: &[(Range<Anchor>, String)],
16133    edit_preview: &EditPreview,
16134    include_deletions: bool,
16135    cx: &App,
16136) -> HighlightedText {
16137    let edits = edits
16138        .iter()
16139        .map(|(anchor, text)| {
16140            (
16141                anchor.start.text_anchor..anchor.end.text_anchor,
16142                text.clone(),
16143            )
16144        })
16145        .collect::<Vec<_>>();
16146
16147    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16148}
16149
16150pub fn highlight_diagnostic_message(
16151    diagnostic: &Diagnostic,
16152    mut max_message_rows: Option<u8>,
16153) -> (SharedString, Vec<Range<usize>>) {
16154    let mut text_without_backticks = String::new();
16155    let mut code_ranges = Vec::new();
16156
16157    if let Some(source) = &diagnostic.source {
16158        text_without_backticks.push_str(source);
16159        code_ranges.push(0..source.len());
16160        text_without_backticks.push_str(": ");
16161    }
16162
16163    let mut prev_offset = 0;
16164    let mut in_code_block = false;
16165    let has_row_limit = max_message_rows.is_some();
16166    let mut newline_indices = diagnostic
16167        .message
16168        .match_indices('\n')
16169        .filter(|_| has_row_limit)
16170        .map(|(ix, _)| ix)
16171        .fuse()
16172        .peekable();
16173
16174    for (quote_ix, _) in diagnostic
16175        .message
16176        .match_indices('`')
16177        .chain([(diagnostic.message.len(), "")])
16178    {
16179        let mut first_newline_ix = None;
16180        let mut last_newline_ix = None;
16181        while let Some(newline_ix) = newline_indices.peek() {
16182            if *newline_ix < quote_ix {
16183                if first_newline_ix.is_none() {
16184                    first_newline_ix = Some(*newline_ix);
16185                }
16186                last_newline_ix = Some(*newline_ix);
16187
16188                if let Some(rows_left) = &mut max_message_rows {
16189                    if *rows_left == 0 {
16190                        break;
16191                    } else {
16192                        *rows_left -= 1;
16193                    }
16194                }
16195                let _ = newline_indices.next();
16196            } else {
16197                break;
16198            }
16199        }
16200        let prev_len = text_without_backticks.len();
16201        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16202        text_without_backticks.push_str(new_text);
16203        if in_code_block {
16204            code_ranges.push(prev_len..text_without_backticks.len());
16205        }
16206        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16207        in_code_block = !in_code_block;
16208        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16209            text_without_backticks.push_str("...");
16210            break;
16211        }
16212    }
16213
16214    (text_without_backticks.into(), code_ranges)
16215}
16216
16217fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16218    match severity {
16219        DiagnosticSeverity::ERROR => colors.error,
16220        DiagnosticSeverity::WARNING => colors.warning,
16221        DiagnosticSeverity::INFORMATION => colors.info,
16222        DiagnosticSeverity::HINT => colors.info,
16223        _ => colors.ignored,
16224    }
16225}
16226
16227pub fn styled_runs_for_code_label<'a>(
16228    label: &'a CodeLabel,
16229    syntax_theme: &'a theme::SyntaxTheme,
16230) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16231    let fade_out = HighlightStyle {
16232        fade_out: Some(0.35),
16233        ..Default::default()
16234    };
16235
16236    let mut prev_end = label.filter_range.end;
16237    label
16238        .runs
16239        .iter()
16240        .enumerate()
16241        .flat_map(move |(ix, (range, highlight_id))| {
16242            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16243                style
16244            } else {
16245                return Default::default();
16246            };
16247            let mut muted_style = style;
16248            muted_style.highlight(fade_out);
16249
16250            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16251            if range.start >= label.filter_range.end {
16252                if range.start > prev_end {
16253                    runs.push((prev_end..range.start, fade_out));
16254                }
16255                runs.push((range.clone(), muted_style));
16256            } else if range.end <= label.filter_range.end {
16257                runs.push((range.clone(), style));
16258            } else {
16259                runs.push((range.start..label.filter_range.end, style));
16260                runs.push((label.filter_range.end..range.end, muted_style));
16261            }
16262            prev_end = cmp::max(prev_end, range.end);
16263
16264            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16265                runs.push((prev_end..label.text.len(), fade_out));
16266            }
16267
16268            runs
16269        })
16270}
16271
16272pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16273    let mut prev_index = 0;
16274    let mut prev_codepoint: Option<char> = None;
16275    text.char_indices()
16276        .chain([(text.len(), '\0')])
16277        .filter_map(move |(index, codepoint)| {
16278            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16279            let is_boundary = index == text.len()
16280                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16281                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16282            if is_boundary {
16283                let chunk = &text[prev_index..index];
16284                prev_index = index;
16285                Some(chunk)
16286            } else {
16287                None
16288            }
16289        })
16290}
16291
16292pub trait RangeToAnchorExt: Sized {
16293    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16294
16295    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16296        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16297        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16298    }
16299}
16300
16301impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16302    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16303        let start_offset = self.start.to_offset(snapshot);
16304        let end_offset = self.end.to_offset(snapshot);
16305        if start_offset == end_offset {
16306            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16307        } else {
16308            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16309        }
16310    }
16311}
16312
16313pub trait RowExt {
16314    fn as_f32(&self) -> f32;
16315
16316    fn next_row(&self) -> Self;
16317
16318    fn previous_row(&self) -> Self;
16319
16320    fn minus(&self, other: Self) -> u32;
16321}
16322
16323impl RowExt for DisplayRow {
16324    fn as_f32(&self) -> f32 {
16325        self.0 as f32
16326    }
16327
16328    fn next_row(&self) -> Self {
16329        Self(self.0 + 1)
16330    }
16331
16332    fn previous_row(&self) -> Self {
16333        Self(self.0.saturating_sub(1))
16334    }
16335
16336    fn minus(&self, other: Self) -> u32 {
16337        self.0 - other.0
16338    }
16339}
16340
16341impl RowExt for MultiBufferRow {
16342    fn as_f32(&self) -> f32 {
16343        self.0 as f32
16344    }
16345
16346    fn next_row(&self) -> Self {
16347        Self(self.0 + 1)
16348    }
16349
16350    fn previous_row(&self) -> Self {
16351        Self(self.0.saturating_sub(1))
16352    }
16353
16354    fn minus(&self, other: Self) -> u32 {
16355        self.0 - other.0
16356    }
16357}
16358
16359trait RowRangeExt {
16360    type Row;
16361
16362    fn len(&self) -> usize;
16363
16364    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16365}
16366
16367impl RowRangeExt for Range<MultiBufferRow> {
16368    type Row = MultiBufferRow;
16369
16370    fn len(&self) -> usize {
16371        (self.end.0 - self.start.0) as usize
16372    }
16373
16374    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16375        (self.start.0..self.end.0).map(MultiBufferRow)
16376    }
16377}
16378
16379impl RowRangeExt for Range<DisplayRow> {
16380    type Row = DisplayRow;
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 = DisplayRow> {
16387        (self.start.0..self.end.0).map(DisplayRow)
16388    }
16389}
16390
16391/// If select range has more than one line, we
16392/// just point the cursor to range.start.
16393fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16394    if range.start.row == range.end.row {
16395        range
16396    } else {
16397        range.start..range.start
16398    }
16399}
16400pub struct KillRing(ClipboardItem);
16401impl Global for KillRing {}
16402
16403const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16404
16405fn all_edits_insertions_or_deletions(
16406    edits: &Vec<(Range<Anchor>, String)>,
16407    snapshot: &MultiBufferSnapshot,
16408) -> bool {
16409    let mut all_insertions = true;
16410    let mut all_deletions = true;
16411
16412    for (range, new_text) in edits.iter() {
16413        let range_is_empty = range.to_offset(&snapshot).is_empty();
16414        let text_is_empty = new_text.is_empty();
16415
16416        if range_is_empty != text_is_empty {
16417            if range_is_empty {
16418                all_deletions = false;
16419            } else {
16420                all_insertions = false;
16421            }
16422        } else {
16423            return false;
16424        }
16425
16426        if !all_insertions && !all_deletions {
16427            return false;
16428        }
16429    }
16430    all_insertions || all_deletions
16431}