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 blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   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
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   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::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   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, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   80    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   81    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   82    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   83    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   84    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   85    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   86    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::{EditPredictionProvider, 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, DiskState, EditPredictionsMode, EditPreview,
  100    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, 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    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{
  163    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  164    ThemeColors, ThemeSettings,
  165};
  166use ui::{
  167    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  168    Tooltip,
  169};
  170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  171use workspace::item::{ItemHandle, PreviewTabsSettings};
  172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  173use workspace::{
  174    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  175};
  176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  177
  178use crate::hover_links::{find_url, find_url_from_range};
  179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  180
  181pub const FILE_HEADER_HEIGHT: u32 = 2;
  182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  186const MAX_LINE_LEN: usize = 1024;
  187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  190#[doc(hidden)]
  191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  192
  193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  195
  196pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  197pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  198
  199pub fn render_parsed_markdown(
  200    element_id: impl Into<ElementId>,
  201    parsed: &language::ParsedMarkdown,
  202    editor_style: &EditorStyle,
  203    workspace: Option<WeakEntity<Workspace>>,
  204    cx: &mut App,
  205) -> InteractiveText {
  206    let code_span_background_color = cx
  207        .theme()
  208        .colors()
  209        .editor_document_highlight_read_background;
  210
  211    let highlights = gpui::combine_highlights(
  212        parsed.highlights.iter().filter_map(|(range, highlight)| {
  213            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  214            Some((range.clone(), highlight))
  215        }),
  216        parsed
  217            .regions
  218            .iter()
  219            .zip(&parsed.region_ranges)
  220            .filter_map(|(region, range)| {
  221                if region.code {
  222                    Some((
  223                        range.clone(),
  224                        HighlightStyle {
  225                            background_color: Some(code_span_background_color),
  226                            ..Default::default()
  227                        },
  228                    ))
  229                } else {
  230                    None
  231                }
  232            }),
  233    );
  234
  235    let mut links = Vec::new();
  236    let mut link_ranges = Vec::new();
  237    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  238        if let Some(link) = region.link.clone() {
  239            links.push(link);
  240            link_ranges.push(range.clone());
  241        }
  242    }
  243
  244    InteractiveText::new(
  245        element_id,
  246        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  247    )
  248    .on_click(
  249        link_ranges,
  250        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  251            markdown::Link::Web { url } => cx.open_url(url),
  252            markdown::Link::Path { path } => {
  253                if let Some(workspace) = &workspace {
  254                    _ = workspace.update(cx, |workspace, cx| {
  255                        workspace
  256                            .open_abs_path(path.clone(), false, window, cx)
  257                            .detach();
  258                    });
  259                }
  260            }
  261        },
  262    )
  263}
  264
  265#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  266pub enum InlayId {
  267    InlineCompletion(usize),
  268    Hint(usize),
  269}
  270
  271impl InlayId {
  272    fn id(&self) -> usize {
  273        match self {
  274            Self::InlineCompletion(id) => *id,
  275            Self::Hint(id) => *id,
  276        }
  277    }
  278}
  279
  280enum DocumentHighlightRead {}
  281enum DocumentHighlightWrite {}
  282enum InputComposition {}
  283
  284#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  285pub enum Navigated {
  286    Yes,
  287    No,
  288}
  289
  290impl Navigated {
  291    pub fn from_bool(yes: bool) -> Navigated {
  292        if yes {
  293            Navigated::Yes
  294        } else {
  295            Navigated::No
  296        }
  297    }
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    workspace::register_project_item::<Editor>(cx);
  308    workspace::FollowableViewRegistry::register::<Editor>(cx);
  309    workspace::register_serializable_item::<Editor>(cx);
  310
  311    cx.observe_new(
  312        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  313            workspace.register_action(Editor::new_file);
  314            workspace.register_action(Editor::new_file_vertical);
  315            workspace.register_action(Editor::new_file_horizontal);
  316            workspace.register_action(Editor::cancel_language_server_work);
  317        },
  318    )
  319    .detach();
  320
  321    cx.on_action(move |_: &workspace::NewFile, cx| {
  322        let app_state = workspace::AppState::global(cx);
  323        if let Some(app_state) = app_state.upgrade() {
  324            workspace::open_new(
  325                Default::default(),
  326                app_state,
  327                cx,
  328                |workspace, window, cx| {
  329                    Editor::new_file(workspace, &Default::default(), window, cx)
  330                },
  331            )
  332            .detach();
  333        }
  334    });
  335    cx.on_action(move |_: &workspace::NewWindow, cx| {
  336        let app_state = workspace::AppState::global(cx);
  337        if let Some(app_state) = app_state.upgrade() {
  338            workspace::open_new(
  339                Default::default(),
  340                app_state,
  341                cx,
  342                |workspace, window, cx| {
  343                    cx.activate(true);
  344                    Editor::new_file(workspace, &Default::default(), window, cx)
  345                },
  346            )
  347            .detach();
  348        }
  349    });
  350}
  351
  352pub struct SearchWithinRange;
  353
  354trait InvalidationRegion {
  355    fn ranges(&self) -> &[Range<Anchor>];
  356}
  357
  358#[derive(Clone, Debug, PartialEq)]
  359pub enum SelectPhase {
  360    Begin {
  361        position: DisplayPoint,
  362        add: bool,
  363        click_count: usize,
  364    },
  365    BeginColumnar {
  366        position: DisplayPoint,
  367        reset: bool,
  368        goal_column: u32,
  369    },
  370    Extend {
  371        position: DisplayPoint,
  372        click_count: usize,
  373    },
  374    Update {
  375        position: DisplayPoint,
  376        goal_column: u32,
  377        scroll_delta: gpui::Point<f32>,
  378    },
  379    End,
  380}
  381
  382#[derive(Clone, Debug)]
  383pub enum SelectMode {
  384    Character,
  385    Word(Range<Anchor>),
  386    Line(Range<Anchor>),
  387    All,
  388}
  389
  390#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  391pub enum EditorMode {
  392    SingleLine { auto_width: bool },
  393    AutoHeight { max_lines: usize },
  394    Full,
  395}
  396
  397#[derive(Copy, Clone, Debug)]
  398pub enum SoftWrap {
  399    /// Prefer not to wrap at all.
  400    ///
  401    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  402    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  403    GitDiff,
  404    /// Prefer a single line generally, unless an overly long line is encountered.
  405    None,
  406    /// Soft wrap lines that exceed the editor width.
  407    EditorWidth,
  408    /// Soft wrap lines at the preferred line length.
  409    Column(u32),
  410    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  411    Bounded(u32),
  412}
  413
  414#[derive(Clone)]
  415pub struct EditorStyle {
  416    pub background: Hsla,
  417    pub local_player: PlayerColor,
  418    pub text: TextStyle,
  419    pub scrollbar_width: Pixels,
  420    pub syntax: Arc<SyntaxTheme>,
  421    pub status: StatusColors,
  422    pub inlay_hints_style: HighlightStyle,
  423    pub inline_completion_styles: InlineCompletionStyles,
  424    pub unnecessary_code_fade: f32,
  425}
  426
  427impl Default for EditorStyle {
  428    fn default() -> Self {
  429        Self {
  430            background: Hsla::default(),
  431            local_player: PlayerColor::default(),
  432            text: TextStyle::default(),
  433            scrollbar_width: Pixels::default(),
  434            syntax: Default::default(),
  435            // HACK: Status colors don't have a real default.
  436            // We should look into removing the status colors from the editor
  437            // style and retrieve them directly from the theme.
  438            status: StatusColors::dark(),
  439            inlay_hints_style: HighlightStyle::default(),
  440            inline_completion_styles: InlineCompletionStyles {
  441                insertion: HighlightStyle::default(),
  442                whitespace: HighlightStyle::default(),
  443            },
  444            unnecessary_code_fade: Default::default(),
  445        }
  446    }
  447}
  448
  449pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  450    let show_background = language_settings::language_settings(None, None, cx)
  451        .inlay_hints
  452        .show_background;
  453
  454    HighlightStyle {
  455        color: Some(cx.theme().status().hint),
  456        background_color: show_background.then(|| cx.theme().status().hint_background),
  457        ..HighlightStyle::default()
  458    }
  459}
  460
  461pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  462    InlineCompletionStyles {
  463        insertion: HighlightStyle {
  464            color: Some(cx.theme().status().predictive),
  465            ..HighlightStyle::default()
  466        },
  467        whitespace: HighlightStyle {
  468            background_color: Some(cx.theme().status().created_background),
  469            ..HighlightStyle::default()
  470        },
  471    }
  472}
  473
  474type CompletionId = usize;
  475
  476pub(crate) enum EditDisplayMode {
  477    TabAccept,
  478    DiffPopover,
  479    Inline,
  480}
  481
  482enum InlineCompletion {
  483    Edit {
  484        edits: Vec<(Range<Anchor>, String)>,
  485        edit_preview: Option<EditPreview>,
  486        display_mode: EditDisplayMode,
  487        snapshot: BufferSnapshot,
  488    },
  489    Move {
  490        target: Anchor,
  491        snapshot: BufferSnapshot,
  492    },
  493}
  494
  495struct InlineCompletionState {
  496    inlay_ids: Vec<InlayId>,
  497    completion: InlineCompletion,
  498    completion_id: Option<SharedString>,
  499    invalidation_range: Range<Anchor>,
  500}
  501
  502enum EditPredictionSettings {
  503    Disabled,
  504    Enabled {
  505        show_in_menu: bool,
  506        preview_requires_modifier: bool,
  507    },
  508}
  509
  510enum InlineCompletionHighlight {}
  511
  512pub enum MenuInlineCompletionsPolicy {
  513    Never,
  514    ByProvider,
  515}
  516
  517pub enum EditPredictionPreview {
  518    /// Modifier is not pressed
  519    Inactive,
  520    /// Modifier pressed
  521    Active {
  522        previous_scroll_position: Option<ScrollAnchor>,
  523    },
  524}
  525
  526#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  527struct EditorActionId(usize);
  528
  529impl EditorActionId {
  530    pub fn post_inc(&mut self) -> Self {
  531        let answer = self.0;
  532
  533        *self = Self(answer + 1);
  534
  535        Self(answer)
  536    }
  537}
  538
  539// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  540// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  541
  542type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  543type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  544
  545#[derive(Default)]
  546struct ScrollbarMarkerState {
  547    scrollbar_size: Size<Pixels>,
  548    dirty: bool,
  549    markers: Arc<[PaintQuad]>,
  550    pending_refresh: Option<Task<Result<()>>>,
  551}
  552
  553impl ScrollbarMarkerState {
  554    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  555        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  556    }
  557}
  558
  559#[derive(Clone, Debug)]
  560struct RunnableTasks {
  561    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  562    offset: MultiBufferOffset,
  563    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  564    column: u32,
  565    // Values of all named captures, including those starting with '_'
  566    extra_variables: HashMap<String, String>,
  567    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  568    context_range: Range<BufferOffset>,
  569}
  570
  571impl RunnableTasks {
  572    fn resolve<'a>(
  573        &'a self,
  574        cx: &'a task::TaskContext,
  575    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  576        self.templates.iter().filter_map(|(kind, template)| {
  577            template
  578                .resolve_task(&kind.to_id_base(), cx)
  579                .map(|task| (kind.clone(), task))
  580        })
  581    }
  582}
  583
  584#[derive(Clone)]
  585struct ResolvedTasks {
  586    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  587    position: Anchor,
  588}
  589#[derive(Copy, Clone, Debug)]
  590struct MultiBufferOffset(usize);
  591#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  592struct BufferOffset(usize);
  593
  594// Addons allow storing per-editor state in other crates (e.g. Vim)
  595pub trait Addon: 'static {
  596    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  597
  598    fn render_buffer_header_controls(
  599        &self,
  600        _: &ExcerptInfo,
  601        _: &Window,
  602        _: &App,
  603    ) -> Option<AnyElement> {
  604        None
  605    }
  606
  607    fn to_any(&self) -> &dyn std::any::Any;
  608}
  609
  610#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  611pub enum IsVimMode {
  612    Yes,
  613    No,
  614}
  615
  616/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  617///
  618/// See the [module level documentation](self) for more information.
  619pub struct Editor {
  620    focus_handle: FocusHandle,
  621    last_focused_descendant: Option<WeakFocusHandle>,
  622    /// The text buffer being edited
  623    buffer: Entity<MultiBuffer>,
  624    /// Map of how text in the buffer should be displayed.
  625    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  626    pub display_map: Entity<DisplayMap>,
  627    pub selections: SelectionsCollection,
  628    pub scroll_manager: ScrollManager,
  629    /// When inline assist editors are linked, they all render cursors because
  630    /// typing enters text into each of them, even the ones that aren't focused.
  631    pub(crate) show_cursor_when_unfocused: bool,
  632    columnar_selection_tail: Option<Anchor>,
  633    add_selections_state: Option<AddSelectionsState>,
  634    select_next_state: Option<SelectNextState>,
  635    select_prev_state: Option<SelectNextState>,
  636    selection_history: SelectionHistory,
  637    autoclose_regions: Vec<AutocloseRegion>,
  638    snippet_stack: InvalidationStack<SnippetState>,
  639    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  640    ime_transaction: Option<TransactionId>,
  641    active_diagnostics: Option<ActiveDiagnosticGroup>,
  642    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  643
  644    // TODO: make this a access method
  645    pub project: Option<Entity<Project>>,
  646    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  647    completion_provider: Option<Box<dyn CompletionProvider>>,
  648    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  649    blink_manager: Entity<BlinkManager>,
  650    show_cursor_names: bool,
  651    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  652    pub show_local_selections: bool,
  653    mode: EditorMode,
  654    show_breadcrumbs: bool,
  655    show_gutter: bool,
  656    show_scrollbars: bool,
  657    show_line_numbers: Option<bool>,
  658    use_relative_line_numbers: Option<bool>,
  659    show_git_diff_gutter: Option<bool>,
  660    show_code_actions: Option<bool>,
  661    show_runnables: Option<bool>,
  662    show_wrap_guides: Option<bool>,
  663    show_indent_guides: Option<bool>,
  664    placeholder_text: Option<Arc<str>>,
  665    highlight_order: usize,
  666    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  667    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  668    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  669    scrollbar_marker_state: ScrollbarMarkerState,
  670    active_indent_guides_state: ActiveIndentGuidesState,
  671    nav_history: Option<ItemNavHistory>,
  672    context_menu: RefCell<Option<CodeContextMenu>>,
  673    mouse_context_menu: Option<MouseContextMenu>,
  674    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  675    signature_help_state: SignatureHelpState,
  676    auto_signature_help: Option<bool>,
  677    find_all_references_task_sources: Vec<Anchor>,
  678    next_completion_id: CompletionId,
  679    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  680    code_actions_task: Option<Task<Result<()>>>,
  681    document_highlights_task: Option<Task<()>>,
  682    linked_editing_range_task: Option<Task<Option<()>>>,
  683    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  684    pending_rename: Option<RenameState>,
  685    searchable: bool,
  686    cursor_shape: CursorShape,
  687    current_line_highlight: Option<CurrentLineHighlight>,
  688    collapse_matches: bool,
  689    autoindent_mode: Option<AutoindentMode>,
  690    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  691    input_enabled: bool,
  692    use_modal_editing: bool,
  693    read_only: bool,
  694    leader_peer_id: Option<PeerId>,
  695    remote_id: Option<ViewId>,
  696    hover_state: HoverState,
  697    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  698    gutter_hovered: bool,
  699    hovered_link_state: Option<HoveredLinkState>,
  700    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  701    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  702    active_inline_completion: Option<InlineCompletionState>,
  703    /// Used to prevent flickering as the user types while the menu is open
  704    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  705    edit_prediction_settings: EditPredictionSettings,
  706    inline_completions_hidden_for_vim_mode: bool,
  707    show_inline_completions_override: Option<bool>,
  708    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  709    edit_prediction_preview: EditPredictionPreview,
  710    edit_prediction_cursor_on_leading_whitespace: bool,
  711    edit_prediction_requires_modifier_in_leading_space: bool,
  712    inlay_hint_cache: InlayHintCache,
  713    next_inlay_id: usize,
  714    _subscriptions: Vec<Subscription>,
  715    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  716    gutter_dimensions: GutterDimensions,
  717    style: Option<EditorStyle>,
  718    text_style_refinement: Option<TextStyleRefinement>,
  719    next_editor_action_id: EditorActionId,
  720    editor_actions:
  721        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  722    use_autoclose: bool,
  723    use_auto_surround: bool,
  724    auto_replace_emoji_shortcode: bool,
  725    show_git_blame_gutter: bool,
  726    show_git_blame_inline: bool,
  727    show_git_blame_inline_delay_task: Option<Task<()>>,
  728    distinguish_unstaged_diff_hunks: bool,
  729    git_blame_inline_enabled: bool,
  730    serialize_dirty_buffers: bool,
  731    show_selection_menu: Option<bool>,
  732    blame: Option<Entity<GitBlame>>,
  733    blame_subscription: Option<Subscription>,
  734    custom_context_menu: Option<
  735        Box<
  736            dyn 'static
  737                + Fn(
  738                    &mut Self,
  739                    DisplayPoint,
  740                    &mut Window,
  741                    &mut Context<Self>,
  742                ) -> Option<Entity<ui::ContextMenu>>,
  743        >,
  744    >,
  745    last_bounds: Option<Bounds<Pixels>>,
  746    last_position_map: Option<Rc<PositionMap>>,
  747    expect_bounds_change: Option<Bounds<Pixels>>,
  748    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  749    tasks_update_task: Option<Task<()>>,
  750    in_project_search: bool,
  751    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  752    breadcrumb_header: Option<String>,
  753    focused_block: Option<FocusedBlock>,
  754    next_scroll_position: NextScrollCursorCenterTopBottom,
  755    addons: HashMap<TypeId, Box<dyn Addon>>,
  756    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  757    selection_mark_mode: bool,
  758    toggle_fold_multiple_buffers: Task<()>,
  759    _scroll_cursor_center_top_bottom_task: Task<()>,
  760}
  761
  762#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  763enum NextScrollCursorCenterTopBottom {
  764    #[default]
  765    Center,
  766    Top,
  767    Bottom,
  768}
  769
  770impl NextScrollCursorCenterTopBottom {
  771    fn next(&self) -> Self {
  772        match self {
  773            Self::Center => Self::Top,
  774            Self::Top => Self::Bottom,
  775            Self::Bottom => Self::Center,
  776        }
  777    }
  778}
  779
  780#[derive(Clone)]
  781pub struct EditorSnapshot {
  782    pub mode: EditorMode,
  783    show_gutter: bool,
  784    show_line_numbers: Option<bool>,
  785    show_git_diff_gutter: Option<bool>,
  786    show_code_actions: Option<bool>,
  787    show_runnables: Option<bool>,
  788    git_blame_gutter_max_author_length: Option<usize>,
  789    pub display_snapshot: DisplaySnapshot,
  790    pub placeholder_text: Option<Arc<str>>,
  791    is_focused: bool,
  792    scroll_anchor: ScrollAnchor,
  793    ongoing_scroll: OngoingScroll,
  794    current_line_highlight: CurrentLineHighlight,
  795    gutter_hovered: bool,
  796}
  797
  798const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  799
  800#[derive(Default, Debug, Clone, Copy)]
  801pub struct GutterDimensions {
  802    pub left_padding: Pixels,
  803    pub right_padding: Pixels,
  804    pub width: Pixels,
  805    pub margin: Pixels,
  806    pub git_blame_entries_width: Option<Pixels>,
  807}
  808
  809impl GutterDimensions {
  810    /// The full width of the space taken up by the gutter.
  811    pub fn full_width(&self) -> Pixels {
  812        self.margin + self.width
  813    }
  814
  815    /// The width of the space reserved for the fold indicators,
  816    /// use alongside 'justify_end' and `gutter_width` to
  817    /// right align content with the line numbers
  818    pub fn fold_area_width(&self) -> Pixels {
  819        self.margin + self.right_padding
  820    }
  821}
  822
  823#[derive(Debug)]
  824pub struct RemoteSelection {
  825    pub replica_id: ReplicaId,
  826    pub selection: Selection<Anchor>,
  827    pub cursor_shape: CursorShape,
  828    pub peer_id: PeerId,
  829    pub line_mode: bool,
  830    pub participant_index: Option<ParticipantIndex>,
  831    pub user_name: Option<SharedString>,
  832}
  833
  834#[derive(Clone, Debug)]
  835struct SelectionHistoryEntry {
  836    selections: Arc<[Selection<Anchor>]>,
  837    select_next_state: Option<SelectNextState>,
  838    select_prev_state: Option<SelectNextState>,
  839    add_selections_state: Option<AddSelectionsState>,
  840}
  841
  842enum SelectionHistoryMode {
  843    Normal,
  844    Undoing,
  845    Redoing,
  846}
  847
  848#[derive(Clone, PartialEq, Eq, Hash)]
  849struct HoveredCursor {
  850    replica_id: u16,
  851    selection_id: usize,
  852}
  853
  854impl Default for SelectionHistoryMode {
  855    fn default() -> Self {
  856        Self::Normal
  857    }
  858}
  859
  860#[derive(Default)]
  861struct SelectionHistory {
  862    #[allow(clippy::type_complexity)]
  863    selections_by_transaction:
  864        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  865    mode: SelectionHistoryMode,
  866    undo_stack: VecDeque<SelectionHistoryEntry>,
  867    redo_stack: VecDeque<SelectionHistoryEntry>,
  868}
  869
  870impl SelectionHistory {
  871    fn insert_transaction(
  872        &mut self,
  873        transaction_id: TransactionId,
  874        selections: Arc<[Selection<Anchor>]>,
  875    ) {
  876        self.selections_by_transaction
  877            .insert(transaction_id, (selections, None));
  878    }
  879
  880    #[allow(clippy::type_complexity)]
  881    fn transaction(
  882        &self,
  883        transaction_id: TransactionId,
  884    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  885        self.selections_by_transaction.get(&transaction_id)
  886    }
  887
  888    #[allow(clippy::type_complexity)]
  889    fn transaction_mut(
  890        &mut self,
  891        transaction_id: TransactionId,
  892    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  893        self.selections_by_transaction.get_mut(&transaction_id)
  894    }
  895
  896    fn push(&mut self, entry: SelectionHistoryEntry) {
  897        if !entry.selections.is_empty() {
  898            match self.mode {
  899                SelectionHistoryMode::Normal => {
  900                    self.push_undo(entry);
  901                    self.redo_stack.clear();
  902                }
  903                SelectionHistoryMode::Undoing => self.push_redo(entry),
  904                SelectionHistoryMode::Redoing => self.push_undo(entry),
  905            }
  906        }
  907    }
  908
  909    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  910        if self
  911            .undo_stack
  912            .back()
  913            .map_or(true, |e| e.selections != entry.selections)
  914        {
  915            self.undo_stack.push_back(entry);
  916            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  917                self.undo_stack.pop_front();
  918            }
  919        }
  920    }
  921
  922    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  923        if self
  924            .redo_stack
  925            .back()
  926            .map_or(true, |e| e.selections != entry.selections)
  927        {
  928            self.redo_stack.push_back(entry);
  929            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  930                self.redo_stack.pop_front();
  931            }
  932        }
  933    }
  934}
  935
  936struct RowHighlight {
  937    index: usize,
  938    range: Range<Anchor>,
  939    color: Hsla,
  940    should_autoscroll: bool,
  941}
  942
  943#[derive(Clone, Debug)]
  944struct AddSelectionsState {
  945    above: bool,
  946    stack: Vec<usize>,
  947}
  948
  949#[derive(Clone)]
  950struct SelectNextState {
  951    query: AhoCorasick,
  952    wordwise: bool,
  953    done: bool,
  954}
  955
  956impl std::fmt::Debug for SelectNextState {
  957    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  958        f.debug_struct(std::any::type_name::<Self>())
  959            .field("wordwise", &self.wordwise)
  960            .field("done", &self.done)
  961            .finish()
  962    }
  963}
  964
  965#[derive(Debug)]
  966struct AutocloseRegion {
  967    selection_id: usize,
  968    range: Range<Anchor>,
  969    pair: BracketPair,
  970}
  971
  972#[derive(Debug)]
  973struct SnippetState {
  974    ranges: Vec<Vec<Range<Anchor>>>,
  975    active_index: usize,
  976    choices: Vec<Option<Vec<String>>>,
  977}
  978
  979#[doc(hidden)]
  980pub struct RenameState {
  981    pub range: Range<Anchor>,
  982    pub old_name: Arc<str>,
  983    pub editor: Entity<Editor>,
  984    block_id: CustomBlockId,
  985}
  986
  987struct InvalidationStack<T>(Vec<T>);
  988
  989struct RegisteredInlineCompletionProvider {
  990    provider: Arc<dyn InlineCompletionProviderHandle>,
  991    _subscription: Subscription,
  992}
  993
  994#[derive(Debug)]
  995struct ActiveDiagnosticGroup {
  996    primary_range: Range<Anchor>,
  997    primary_message: String,
  998    group_id: usize,
  999    blocks: HashMap<CustomBlockId, Diagnostic>,
 1000    is_valid: bool,
 1001}
 1002
 1003#[derive(Serialize, Deserialize, Clone, Debug)]
 1004pub struct ClipboardSelection {
 1005    pub len: usize,
 1006    pub is_entire_line: bool,
 1007    pub first_line_indent: u32,
 1008}
 1009
 1010#[derive(Debug)]
 1011pub(crate) struct NavigationData {
 1012    cursor_anchor: Anchor,
 1013    cursor_position: Point,
 1014    scroll_anchor: ScrollAnchor,
 1015    scroll_top_row: u32,
 1016}
 1017
 1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1019pub enum GotoDefinitionKind {
 1020    Symbol,
 1021    Declaration,
 1022    Type,
 1023    Implementation,
 1024}
 1025
 1026#[derive(Debug, Clone)]
 1027enum InlayHintRefreshReason {
 1028    Toggle(bool),
 1029    SettingsChange(InlayHintSettings),
 1030    NewLinesShown,
 1031    BufferEdited(HashSet<Arc<Language>>),
 1032    RefreshRequested,
 1033    ExcerptsRemoved(Vec<ExcerptId>),
 1034}
 1035
 1036impl InlayHintRefreshReason {
 1037    fn description(&self) -> &'static str {
 1038        match self {
 1039            Self::Toggle(_) => "toggle",
 1040            Self::SettingsChange(_) => "settings change",
 1041            Self::NewLinesShown => "new lines shown",
 1042            Self::BufferEdited(_) => "buffer edited",
 1043            Self::RefreshRequested => "refresh requested",
 1044            Self::ExcerptsRemoved(_) => "excerpts removed",
 1045        }
 1046    }
 1047}
 1048
 1049pub enum FormatTarget {
 1050    Buffers,
 1051    Ranges(Vec<Range<MultiBufferPoint>>),
 1052}
 1053
 1054pub(crate) struct FocusedBlock {
 1055    id: BlockId,
 1056    focus_handle: WeakFocusHandle,
 1057}
 1058
 1059#[derive(Clone)]
 1060enum JumpData {
 1061    MultiBufferRow {
 1062        row: MultiBufferRow,
 1063        line_offset_from_top: u32,
 1064    },
 1065    MultiBufferPoint {
 1066        excerpt_id: ExcerptId,
 1067        position: Point,
 1068        anchor: text::Anchor,
 1069        line_offset_from_top: u32,
 1070    },
 1071}
 1072
 1073pub enum MultibufferSelectionMode {
 1074    First,
 1075    All,
 1076}
 1077
 1078impl Editor {
 1079    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1080        let buffer = cx.new(|cx| Buffer::local("", cx));
 1081        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1082        Self::new(
 1083            EditorMode::SingleLine { auto_width: false },
 1084            buffer,
 1085            None,
 1086            false,
 1087            window,
 1088            cx,
 1089        )
 1090    }
 1091
 1092    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1093        let buffer = cx.new(|cx| Buffer::local("", cx));
 1094        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1095        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1096    }
 1097
 1098    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1099        let buffer = cx.new(|cx| Buffer::local("", cx));
 1100        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1101        Self::new(
 1102            EditorMode::SingleLine { auto_width: true },
 1103            buffer,
 1104            None,
 1105            false,
 1106            window,
 1107            cx,
 1108        )
 1109    }
 1110
 1111    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1112        let buffer = cx.new(|cx| Buffer::local("", cx));
 1113        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1114        Self::new(
 1115            EditorMode::AutoHeight { max_lines },
 1116            buffer,
 1117            None,
 1118            false,
 1119            window,
 1120            cx,
 1121        )
 1122    }
 1123
 1124    pub fn for_buffer(
 1125        buffer: Entity<Buffer>,
 1126        project: Option<Entity<Project>>,
 1127        window: &mut Window,
 1128        cx: &mut Context<Self>,
 1129    ) -> Self {
 1130        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1131        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1132    }
 1133
 1134    pub fn for_multibuffer(
 1135        buffer: Entity<MultiBuffer>,
 1136        project: Option<Entity<Project>>,
 1137        show_excerpt_controls: bool,
 1138        window: &mut Window,
 1139        cx: &mut Context<Self>,
 1140    ) -> Self {
 1141        Self::new(
 1142            EditorMode::Full,
 1143            buffer,
 1144            project,
 1145            show_excerpt_controls,
 1146            window,
 1147            cx,
 1148        )
 1149    }
 1150
 1151    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1152        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1153        let mut clone = Self::new(
 1154            self.mode,
 1155            self.buffer.clone(),
 1156            self.project.clone(),
 1157            show_excerpt_controls,
 1158            window,
 1159            cx,
 1160        );
 1161        self.display_map.update(cx, |display_map, cx| {
 1162            let snapshot = display_map.snapshot(cx);
 1163            clone.display_map.update(cx, |display_map, cx| {
 1164                display_map.set_state(&snapshot, cx);
 1165            });
 1166        });
 1167        clone.selections.clone_state(&self.selections);
 1168        clone.scroll_manager.clone_state(&self.scroll_manager);
 1169        clone.searchable = self.searchable;
 1170        clone
 1171    }
 1172
 1173    pub fn new(
 1174        mode: EditorMode,
 1175        buffer: Entity<MultiBuffer>,
 1176        project: Option<Entity<Project>>,
 1177        show_excerpt_controls: bool,
 1178        window: &mut Window,
 1179        cx: &mut Context<Self>,
 1180    ) -> Self {
 1181        let style = window.text_style();
 1182        let font_size = style.font_size.to_pixels(window.rem_size());
 1183        let editor = cx.entity().downgrade();
 1184        let fold_placeholder = FoldPlaceholder {
 1185            constrain_width: true,
 1186            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1187                let editor = editor.clone();
 1188                div()
 1189                    .id(fold_id)
 1190                    .bg(cx.theme().colors().ghost_element_background)
 1191                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1192                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1193                    .rounded_sm()
 1194                    .size_full()
 1195                    .cursor_pointer()
 1196                    .child("")
 1197                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1198                    .on_click(move |_, _window, cx| {
 1199                        editor
 1200                            .update(cx, |editor, cx| {
 1201                                editor.unfold_ranges(
 1202                                    &[fold_range.start..fold_range.end],
 1203                                    true,
 1204                                    false,
 1205                                    cx,
 1206                                );
 1207                                cx.stop_propagation();
 1208                            })
 1209                            .ok();
 1210                    })
 1211                    .into_any()
 1212            }),
 1213            merge_adjacent: true,
 1214            ..Default::default()
 1215        };
 1216        let display_map = cx.new(|cx| {
 1217            DisplayMap::new(
 1218                buffer.clone(),
 1219                style.font(),
 1220                font_size,
 1221                None,
 1222                show_excerpt_controls,
 1223                FILE_HEADER_HEIGHT,
 1224                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1225                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1226                fold_placeholder,
 1227                cx,
 1228            )
 1229        });
 1230
 1231        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1232
 1233        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1234
 1235        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1236            .then(|| language_settings::SoftWrap::None);
 1237
 1238        let mut project_subscriptions = Vec::new();
 1239        if mode == EditorMode::Full {
 1240            if let Some(project) = project.as_ref() {
 1241                if buffer.read(cx).is_singleton() {
 1242                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1243                        cx.emit(EditorEvent::TitleChanged);
 1244                    }));
 1245                }
 1246                project_subscriptions.push(cx.subscribe_in(
 1247                    project,
 1248                    window,
 1249                    |editor, _, event, window, cx| {
 1250                        if let project::Event::RefreshInlayHints = event {
 1251                            editor
 1252                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1253                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1254                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1255                                let focus_handle = editor.focus_handle(cx);
 1256                                if focus_handle.is_focused(window) {
 1257                                    let snapshot = buffer.read(cx).snapshot();
 1258                                    for (range, snippet) in snippet_edits {
 1259                                        let editor_range =
 1260                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1261                                        editor
 1262                                            .insert_snippet(
 1263                                                &[editor_range],
 1264                                                snippet.clone(),
 1265                                                window,
 1266                                                cx,
 1267                                            )
 1268                                            .ok();
 1269                                    }
 1270                                }
 1271                            }
 1272                        }
 1273                    },
 1274                ));
 1275                if let Some(task_inventory) = project
 1276                    .read(cx)
 1277                    .task_store()
 1278                    .read(cx)
 1279                    .task_inventory()
 1280                    .cloned()
 1281                {
 1282                    project_subscriptions.push(cx.observe_in(
 1283                        &task_inventory,
 1284                        window,
 1285                        |editor, _, window, cx| {
 1286                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1287                        },
 1288                    ));
 1289                }
 1290            }
 1291        }
 1292
 1293        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1294
 1295        let inlay_hint_settings =
 1296            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1297        let focus_handle = cx.focus_handle();
 1298        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1299            .detach();
 1300        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1301            .detach();
 1302        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1303            .detach();
 1304        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1305            .detach();
 1306
 1307        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1308            Some(false)
 1309        } else {
 1310            None
 1311        };
 1312
 1313        let mut code_action_providers = Vec::new();
 1314        if let Some(project) = project.clone() {
 1315            get_uncommitted_diff_for_buffer(
 1316                &project,
 1317                buffer.read(cx).all_buffers(),
 1318                buffer.clone(),
 1319                cx,
 1320            );
 1321            code_action_providers.push(Rc::new(project) as Rc<_>);
 1322        }
 1323
 1324        let mut this = Self {
 1325            focus_handle,
 1326            show_cursor_when_unfocused: false,
 1327            last_focused_descendant: None,
 1328            buffer: buffer.clone(),
 1329            display_map: display_map.clone(),
 1330            selections,
 1331            scroll_manager: ScrollManager::new(cx),
 1332            columnar_selection_tail: None,
 1333            add_selections_state: None,
 1334            select_next_state: None,
 1335            select_prev_state: None,
 1336            selection_history: Default::default(),
 1337            autoclose_regions: Default::default(),
 1338            snippet_stack: Default::default(),
 1339            select_larger_syntax_node_stack: Vec::new(),
 1340            ime_transaction: Default::default(),
 1341            active_diagnostics: None,
 1342            soft_wrap_mode_override,
 1343            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1344            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1345            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1346            project,
 1347            blink_manager: blink_manager.clone(),
 1348            show_local_selections: true,
 1349            show_scrollbars: true,
 1350            mode,
 1351            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1352            show_gutter: mode == EditorMode::Full,
 1353            show_line_numbers: None,
 1354            use_relative_line_numbers: None,
 1355            show_git_diff_gutter: None,
 1356            show_code_actions: None,
 1357            show_runnables: None,
 1358            show_wrap_guides: None,
 1359            show_indent_guides,
 1360            placeholder_text: None,
 1361            highlight_order: 0,
 1362            highlighted_rows: HashMap::default(),
 1363            background_highlights: Default::default(),
 1364            gutter_highlights: TreeMap::default(),
 1365            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1366            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1367            nav_history: None,
 1368            context_menu: RefCell::new(None),
 1369            mouse_context_menu: None,
 1370            completion_tasks: Default::default(),
 1371            signature_help_state: SignatureHelpState::default(),
 1372            auto_signature_help: None,
 1373            find_all_references_task_sources: Vec::new(),
 1374            next_completion_id: 0,
 1375            next_inlay_id: 0,
 1376            code_action_providers,
 1377            available_code_actions: Default::default(),
 1378            code_actions_task: Default::default(),
 1379            document_highlights_task: Default::default(),
 1380            linked_editing_range_task: Default::default(),
 1381            pending_rename: Default::default(),
 1382            searchable: true,
 1383            cursor_shape: EditorSettings::get_global(cx)
 1384                .cursor_shape
 1385                .unwrap_or_default(),
 1386            current_line_highlight: None,
 1387            autoindent_mode: Some(AutoindentMode::EachLine),
 1388            collapse_matches: false,
 1389            workspace: None,
 1390            input_enabled: true,
 1391            use_modal_editing: mode == EditorMode::Full,
 1392            read_only: false,
 1393            use_autoclose: true,
 1394            use_auto_surround: true,
 1395            auto_replace_emoji_shortcode: false,
 1396            leader_peer_id: None,
 1397            remote_id: None,
 1398            hover_state: Default::default(),
 1399            pending_mouse_down: None,
 1400            hovered_link_state: Default::default(),
 1401            edit_prediction_provider: None,
 1402            active_inline_completion: None,
 1403            stale_inline_completion_in_menu: None,
 1404            edit_prediction_preview: EditPredictionPreview::Inactive,
 1405            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1406
 1407            gutter_hovered: false,
 1408            pixel_position_of_newest_cursor: None,
 1409            last_bounds: None,
 1410            last_position_map: None,
 1411            expect_bounds_change: None,
 1412            gutter_dimensions: GutterDimensions::default(),
 1413            style: None,
 1414            show_cursor_names: false,
 1415            hovered_cursors: Default::default(),
 1416            next_editor_action_id: EditorActionId::default(),
 1417            editor_actions: Rc::default(),
 1418            inline_completions_hidden_for_vim_mode: false,
 1419            show_inline_completions_override: None,
 1420            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1421            edit_prediction_settings: EditPredictionSettings::Disabled,
 1422            edit_prediction_cursor_on_leading_whitespace: false,
 1423            edit_prediction_requires_modifier_in_leading_space: true,
 1424            custom_context_menu: None,
 1425            show_git_blame_gutter: false,
 1426            show_git_blame_inline: false,
 1427            distinguish_unstaged_diff_hunks: false,
 1428            show_selection_menu: None,
 1429            show_git_blame_inline_delay_task: None,
 1430            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1431            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1432                .session
 1433                .restore_unsaved_buffers,
 1434            blame: None,
 1435            blame_subscription: None,
 1436            tasks: Default::default(),
 1437            _subscriptions: vec![
 1438                cx.observe(&buffer, Self::on_buffer_changed),
 1439                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1440                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1441                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1442                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1443                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1444                cx.observe_window_activation(window, |editor, window, cx| {
 1445                    let active = window.is_window_active();
 1446                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1447                        if active {
 1448                            blink_manager.enable(cx);
 1449                        } else {
 1450                            blink_manager.disable(cx);
 1451                        }
 1452                    });
 1453                }),
 1454            ],
 1455            tasks_update_task: None,
 1456            linked_edit_ranges: Default::default(),
 1457            in_project_search: false,
 1458            previous_search_ranges: None,
 1459            breadcrumb_header: None,
 1460            focused_block: None,
 1461            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1462            addons: HashMap::default(),
 1463            registered_buffers: HashMap::default(),
 1464            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1465            selection_mark_mode: false,
 1466            toggle_fold_multiple_buffers: Task::ready(()),
 1467            text_style_refinement: None,
 1468        };
 1469        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1470        this._subscriptions.extend(project_subscriptions);
 1471
 1472        this.end_selection(window, cx);
 1473        this.scroll_manager.show_scrollbar(window, cx);
 1474
 1475        if mode == EditorMode::Full {
 1476            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1477            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1478
 1479            if this.git_blame_inline_enabled {
 1480                this.git_blame_inline_enabled = true;
 1481                this.start_git_blame_inline(false, window, cx);
 1482            }
 1483
 1484            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1485                if let Some(project) = this.project.as_ref() {
 1486                    let lsp_store = project.read(cx).lsp_store();
 1487                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1488                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1489                    });
 1490                    this.registered_buffers
 1491                        .insert(buffer.read(cx).remote_id(), handle);
 1492                }
 1493            }
 1494        }
 1495
 1496        this.report_editor_event("Editor Opened", None, cx);
 1497        this
 1498    }
 1499
 1500    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1501        self.mouse_context_menu
 1502            .as_ref()
 1503            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1504    }
 1505
 1506    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1507        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1508    }
 1509
 1510    fn key_context_internal(
 1511        &self,
 1512        has_active_edit_prediction: bool,
 1513        window: &Window,
 1514        cx: &App,
 1515    ) -> KeyContext {
 1516        let mut key_context = KeyContext::new_with_defaults();
 1517        key_context.add("Editor");
 1518        let mode = match self.mode {
 1519            EditorMode::SingleLine { .. } => "single_line",
 1520            EditorMode::AutoHeight { .. } => "auto_height",
 1521            EditorMode::Full => "full",
 1522        };
 1523
 1524        if EditorSettings::jupyter_enabled(cx) {
 1525            key_context.add("jupyter");
 1526        }
 1527
 1528        key_context.set("mode", mode);
 1529        if self.pending_rename.is_some() {
 1530            key_context.add("renaming");
 1531        }
 1532
 1533        match self.context_menu.borrow().as_ref() {
 1534            Some(CodeContextMenu::Completions(_)) => {
 1535                key_context.add("menu");
 1536                key_context.add("showing_completions");
 1537            }
 1538            Some(CodeContextMenu::CodeActions(_)) => {
 1539                key_context.add("menu");
 1540                key_context.add("showing_code_actions")
 1541            }
 1542            None => {}
 1543        }
 1544
 1545        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1546        if !self.focus_handle(cx).contains_focused(window, cx)
 1547            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1548        {
 1549            for addon in self.addons.values() {
 1550                addon.extend_key_context(&mut key_context, cx)
 1551            }
 1552        }
 1553
 1554        if let Some(extension) = self
 1555            .buffer
 1556            .read(cx)
 1557            .as_singleton()
 1558            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1559        {
 1560            key_context.set("extension", extension.to_string());
 1561        }
 1562
 1563        if has_active_edit_prediction {
 1564            if self.edit_prediction_in_conflict() {
 1565                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1566            } else {
 1567                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1568                key_context.add("copilot_suggestion");
 1569            }
 1570        }
 1571
 1572        if self.selection_mark_mode {
 1573            key_context.add("selection_mode");
 1574        }
 1575
 1576        key_context
 1577    }
 1578
 1579    pub fn edit_prediction_in_conflict(&self) -> bool {
 1580        if !self.show_edit_predictions_in_menu() {
 1581            return false;
 1582        }
 1583
 1584        let showing_completions = self
 1585            .context_menu
 1586            .borrow()
 1587            .as_ref()
 1588            .map_or(false, |context| {
 1589                matches!(context, CodeContextMenu::Completions(_))
 1590            });
 1591
 1592        showing_completions
 1593            || self.edit_prediction_requires_modifier()
 1594            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1595            // bindings to insert tab characters.
 1596            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1597    }
 1598
 1599    pub fn accept_edit_prediction_keybind(
 1600        &self,
 1601        window: &Window,
 1602        cx: &App,
 1603    ) -> AcceptEditPredictionBinding {
 1604        let key_context = self.key_context_internal(true, window, cx);
 1605        let in_conflict = self.edit_prediction_in_conflict();
 1606
 1607        AcceptEditPredictionBinding(
 1608            window
 1609                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1610                .into_iter()
 1611                .filter(|binding| {
 1612                    !in_conflict
 1613                        || binding
 1614                            .keystrokes()
 1615                            .first()
 1616                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1617                })
 1618                .rev()
 1619                .min_by_key(|binding| {
 1620                    binding
 1621                        .keystrokes()
 1622                        .first()
 1623                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1624                }),
 1625        )
 1626    }
 1627
 1628    pub fn new_file(
 1629        workspace: &mut Workspace,
 1630        _: &workspace::NewFile,
 1631        window: &mut Window,
 1632        cx: &mut Context<Workspace>,
 1633    ) {
 1634        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1635            "Failed to create buffer",
 1636            window,
 1637            cx,
 1638            |e, _, _| match e.error_code() {
 1639                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1640                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1641                e.error_tag("required").unwrap_or("the latest version")
 1642            )),
 1643                _ => None,
 1644            },
 1645        );
 1646    }
 1647
 1648    pub fn new_in_workspace(
 1649        workspace: &mut Workspace,
 1650        window: &mut Window,
 1651        cx: &mut Context<Workspace>,
 1652    ) -> Task<Result<Entity<Editor>>> {
 1653        let project = workspace.project().clone();
 1654        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1655
 1656        cx.spawn_in(window, |workspace, mut cx| async move {
 1657            let buffer = create.await?;
 1658            workspace.update_in(&mut cx, |workspace, window, cx| {
 1659                let editor =
 1660                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1661                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1662                editor
 1663            })
 1664        })
 1665    }
 1666
 1667    fn new_file_vertical(
 1668        workspace: &mut Workspace,
 1669        _: &workspace::NewFileSplitVertical,
 1670        window: &mut Window,
 1671        cx: &mut Context<Workspace>,
 1672    ) {
 1673        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1674    }
 1675
 1676    fn new_file_horizontal(
 1677        workspace: &mut Workspace,
 1678        _: &workspace::NewFileSplitHorizontal,
 1679        window: &mut Window,
 1680        cx: &mut Context<Workspace>,
 1681    ) {
 1682        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1683    }
 1684
 1685    fn new_file_in_direction(
 1686        workspace: &mut Workspace,
 1687        direction: SplitDirection,
 1688        window: &mut Window,
 1689        cx: &mut Context<Workspace>,
 1690    ) {
 1691        let project = workspace.project().clone();
 1692        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1693
 1694        cx.spawn_in(window, |workspace, mut cx| async move {
 1695            let buffer = create.await?;
 1696            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1697                workspace.split_item(
 1698                    direction,
 1699                    Box::new(
 1700                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1701                    ),
 1702                    window,
 1703                    cx,
 1704                )
 1705            })?;
 1706            anyhow::Ok(())
 1707        })
 1708        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1709            match e.error_code() {
 1710                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1711                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1712                e.error_tag("required").unwrap_or("the latest version")
 1713            )),
 1714                _ => None,
 1715            }
 1716        });
 1717    }
 1718
 1719    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1720        self.leader_peer_id
 1721    }
 1722
 1723    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1724        &self.buffer
 1725    }
 1726
 1727    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1728        self.workspace.as_ref()?.0.upgrade()
 1729    }
 1730
 1731    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1732        self.buffer().read(cx).title(cx)
 1733    }
 1734
 1735    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1736        let git_blame_gutter_max_author_length = self
 1737            .render_git_blame_gutter(cx)
 1738            .then(|| {
 1739                if let Some(blame) = self.blame.as_ref() {
 1740                    let max_author_length =
 1741                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1742                    Some(max_author_length)
 1743                } else {
 1744                    None
 1745                }
 1746            })
 1747            .flatten();
 1748
 1749        EditorSnapshot {
 1750            mode: self.mode,
 1751            show_gutter: self.show_gutter,
 1752            show_line_numbers: self.show_line_numbers,
 1753            show_git_diff_gutter: self.show_git_diff_gutter,
 1754            show_code_actions: self.show_code_actions,
 1755            show_runnables: self.show_runnables,
 1756            git_blame_gutter_max_author_length,
 1757            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1758            scroll_anchor: self.scroll_manager.anchor(),
 1759            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1760            placeholder_text: self.placeholder_text.clone(),
 1761            is_focused: self.focus_handle.is_focused(window),
 1762            current_line_highlight: self
 1763                .current_line_highlight
 1764                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1765            gutter_hovered: self.gutter_hovered,
 1766        }
 1767    }
 1768
 1769    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1770        self.buffer.read(cx).language_at(point, cx)
 1771    }
 1772
 1773    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1774        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1775    }
 1776
 1777    pub fn active_excerpt(
 1778        &self,
 1779        cx: &App,
 1780    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1781        self.buffer
 1782            .read(cx)
 1783            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1784    }
 1785
 1786    pub fn mode(&self) -> EditorMode {
 1787        self.mode
 1788    }
 1789
 1790    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1791        self.collaboration_hub.as_deref()
 1792    }
 1793
 1794    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1795        self.collaboration_hub = Some(hub);
 1796    }
 1797
 1798    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1799        self.in_project_search = in_project_search;
 1800    }
 1801
 1802    pub fn set_custom_context_menu(
 1803        &mut self,
 1804        f: impl 'static
 1805            + Fn(
 1806                &mut Self,
 1807                DisplayPoint,
 1808                &mut Window,
 1809                &mut Context<Self>,
 1810            ) -> Option<Entity<ui::ContextMenu>>,
 1811    ) {
 1812        self.custom_context_menu = Some(Box::new(f))
 1813    }
 1814
 1815    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1816        self.completion_provider = provider;
 1817    }
 1818
 1819    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1820        self.semantics_provider.clone()
 1821    }
 1822
 1823    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1824        self.semantics_provider = provider;
 1825    }
 1826
 1827    pub fn set_edit_prediction_provider<T>(
 1828        &mut self,
 1829        provider: Option<Entity<T>>,
 1830        window: &mut Window,
 1831        cx: &mut Context<Self>,
 1832    ) where
 1833        T: EditPredictionProvider,
 1834    {
 1835        self.edit_prediction_provider =
 1836            provider.map(|provider| RegisteredInlineCompletionProvider {
 1837                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1838                    if this.focus_handle.is_focused(window) {
 1839                        this.update_visible_inline_completion(window, cx);
 1840                    }
 1841                }),
 1842                provider: Arc::new(provider),
 1843            });
 1844        self.refresh_inline_completion(false, false, window, cx);
 1845    }
 1846
 1847    pub fn placeholder_text(&self) -> Option<&str> {
 1848        self.placeholder_text.as_deref()
 1849    }
 1850
 1851    pub fn set_placeholder_text(
 1852        &mut self,
 1853        placeholder_text: impl Into<Arc<str>>,
 1854        cx: &mut Context<Self>,
 1855    ) {
 1856        let placeholder_text = Some(placeholder_text.into());
 1857        if self.placeholder_text != placeholder_text {
 1858            self.placeholder_text = placeholder_text;
 1859            cx.notify();
 1860        }
 1861    }
 1862
 1863    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1864        self.cursor_shape = cursor_shape;
 1865
 1866        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1867        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1868
 1869        cx.notify();
 1870    }
 1871
 1872    pub fn set_current_line_highlight(
 1873        &mut self,
 1874        current_line_highlight: Option<CurrentLineHighlight>,
 1875    ) {
 1876        self.current_line_highlight = current_line_highlight;
 1877    }
 1878
 1879    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1880        self.collapse_matches = collapse_matches;
 1881    }
 1882
 1883    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1884        let buffers = self.buffer.read(cx).all_buffers();
 1885        let Some(lsp_store) = self.lsp_store(cx) else {
 1886            return;
 1887        };
 1888        lsp_store.update(cx, |lsp_store, cx| {
 1889            for buffer in buffers {
 1890                self.registered_buffers
 1891                    .entry(buffer.read(cx).remote_id())
 1892                    .or_insert_with(|| {
 1893                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1894                    });
 1895            }
 1896        })
 1897    }
 1898
 1899    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1900        if self.collapse_matches {
 1901            return range.start..range.start;
 1902        }
 1903        range.clone()
 1904    }
 1905
 1906    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1907        if self.display_map.read(cx).clip_at_line_ends != clip {
 1908            self.display_map
 1909                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1910        }
 1911    }
 1912
 1913    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1914        self.input_enabled = input_enabled;
 1915    }
 1916
 1917    pub fn set_inline_completions_hidden_for_vim_mode(
 1918        &mut self,
 1919        hidden: bool,
 1920        window: &mut Window,
 1921        cx: &mut Context<Self>,
 1922    ) {
 1923        if hidden != self.inline_completions_hidden_for_vim_mode {
 1924            self.inline_completions_hidden_for_vim_mode = hidden;
 1925            if hidden {
 1926                self.update_visible_inline_completion(window, cx);
 1927            } else {
 1928                self.refresh_inline_completion(true, false, window, cx);
 1929            }
 1930        }
 1931    }
 1932
 1933    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1934        self.menu_inline_completions_policy = value;
 1935    }
 1936
 1937    pub fn set_autoindent(&mut self, autoindent: bool) {
 1938        if autoindent {
 1939            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1940        } else {
 1941            self.autoindent_mode = None;
 1942        }
 1943    }
 1944
 1945    pub fn read_only(&self, cx: &App) -> bool {
 1946        self.read_only || self.buffer.read(cx).read_only()
 1947    }
 1948
 1949    pub fn set_read_only(&mut self, read_only: bool) {
 1950        self.read_only = read_only;
 1951    }
 1952
 1953    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1954        self.use_autoclose = autoclose;
 1955    }
 1956
 1957    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1958        self.use_auto_surround = auto_surround;
 1959    }
 1960
 1961    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1962        self.auto_replace_emoji_shortcode = auto_replace;
 1963    }
 1964
 1965    pub fn toggle_inline_completions(
 1966        &mut self,
 1967        _: &ToggleEditPrediction,
 1968        window: &mut Window,
 1969        cx: &mut Context<Self>,
 1970    ) {
 1971        if self.show_inline_completions_override.is_some() {
 1972            self.set_show_edit_predictions(None, window, cx);
 1973        } else {
 1974            let show_edit_predictions = !self.edit_predictions_enabled();
 1975            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1976        }
 1977    }
 1978
 1979    pub fn set_show_edit_predictions(
 1980        &mut self,
 1981        show_edit_predictions: Option<bool>,
 1982        window: &mut Window,
 1983        cx: &mut Context<Self>,
 1984    ) {
 1985        self.show_inline_completions_override = show_edit_predictions;
 1986        self.refresh_inline_completion(false, true, window, cx);
 1987    }
 1988
 1989    fn inline_completions_disabled_in_scope(
 1990        &self,
 1991        buffer: &Entity<Buffer>,
 1992        buffer_position: language::Anchor,
 1993        cx: &App,
 1994    ) -> bool {
 1995        let snapshot = buffer.read(cx).snapshot();
 1996        let settings = snapshot.settings_at(buffer_position, cx);
 1997
 1998        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1999            return false;
 2000        };
 2001
 2002        scope.override_name().map_or(false, |scope_name| {
 2003            settings
 2004                .edit_predictions_disabled_in
 2005                .iter()
 2006                .any(|s| s == scope_name)
 2007        })
 2008    }
 2009
 2010    pub fn set_use_modal_editing(&mut self, to: bool) {
 2011        self.use_modal_editing = to;
 2012    }
 2013
 2014    pub fn use_modal_editing(&self) -> bool {
 2015        self.use_modal_editing
 2016    }
 2017
 2018    fn selections_did_change(
 2019        &mut self,
 2020        local: bool,
 2021        old_cursor_position: &Anchor,
 2022        show_completions: bool,
 2023        window: &mut Window,
 2024        cx: &mut Context<Self>,
 2025    ) {
 2026        window.invalidate_character_coordinates();
 2027
 2028        // Copy selections to primary selection buffer
 2029        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2030        if local {
 2031            let selections = self.selections.all::<usize>(cx);
 2032            let buffer_handle = self.buffer.read(cx).read(cx);
 2033
 2034            let mut text = String::new();
 2035            for (index, selection) in selections.iter().enumerate() {
 2036                let text_for_selection = buffer_handle
 2037                    .text_for_range(selection.start..selection.end)
 2038                    .collect::<String>();
 2039
 2040                text.push_str(&text_for_selection);
 2041                if index != selections.len() - 1 {
 2042                    text.push('\n');
 2043                }
 2044            }
 2045
 2046            if !text.is_empty() {
 2047                cx.write_to_primary(ClipboardItem::new_string(text));
 2048            }
 2049        }
 2050
 2051        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2052            self.buffer.update(cx, |buffer, cx| {
 2053                buffer.set_active_selections(
 2054                    &self.selections.disjoint_anchors(),
 2055                    self.selections.line_mode,
 2056                    self.cursor_shape,
 2057                    cx,
 2058                )
 2059            });
 2060        }
 2061        let display_map = self
 2062            .display_map
 2063            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2064        let buffer = &display_map.buffer_snapshot;
 2065        self.add_selections_state = None;
 2066        self.select_next_state = None;
 2067        self.select_prev_state = None;
 2068        self.select_larger_syntax_node_stack.clear();
 2069        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2070        self.snippet_stack
 2071            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2072        self.take_rename(false, window, cx);
 2073
 2074        let new_cursor_position = self.selections.newest_anchor().head();
 2075
 2076        self.push_to_nav_history(
 2077            *old_cursor_position,
 2078            Some(new_cursor_position.to_point(buffer)),
 2079            cx,
 2080        );
 2081
 2082        if local {
 2083            let new_cursor_position = self.selections.newest_anchor().head();
 2084            let mut context_menu = self.context_menu.borrow_mut();
 2085            let completion_menu = match context_menu.as_ref() {
 2086                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2087                _ => {
 2088                    *context_menu = None;
 2089                    None
 2090                }
 2091            };
 2092            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2093                if !self.registered_buffers.contains_key(&buffer_id) {
 2094                    if let Some(lsp_store) = self.lsp_store(cx) {
 2095                        lsp_store.update(cx, |lsp_store, cx| {
 2096                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2097                                return;
 2098                            };
 2099                            self.registered_buffers.insert(
 2100                                buffer_id,
 2101                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2102                            );
 2103                        })
 2104                    }
 2105                }
 2106            }
 2107
 2108            if let Some(completion_menu) = completion_menu {
 2109                let cursor_position = new_cursor_position.to_offset(buffer);
 2110                let (word_range, kind) =
 2111                    buffer.surrounding_word(completion_menu.initial_position, true);
 2112                if kind == Some(CharKind::Word)
 2113                    && word_range.to_inclusive().contains(&cursor_position)
 2114                {
 2115                    let mut completion_menu = completion_menu.clone();
 2116                    drop(context_menu);
 2117
 2118                    let query = Self::completion_query(buffer, cursor_position);
 2119                    cx.spawn(move |this, mut cx| async move {
 2120                        completion_menu
 2121                            .filter(query.as_deref(), cx.background_executor().clone())
 2122                            .await;
 2123
 2124                        this.update(&mut cx, |this, cx| {
 2125                            let mut context_menu = this.context_menu.borrow_mut();
 2126                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2127                            else {
 2128                                return;
 2129                            };
 2130
 2131                            if menu.id > completion_menu.id {
 2132                                return;
 2133                            }
 2134
 2135                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2136                            drop(context_menu);
 2137                            cx.notify();
 2138                        })
 2139                    })
 2140                    .detach();
 2141
 2142                    if show_completions {
 2143                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2144                    }
 2145                } else {
 2146                    drop(context_menu);
 2147                    self.hide_context_menu(window, cx);
 2148                }
 2149            } else {
 2150                drop(context_menu);
 2151            }
 2152
 2153            hide_hover(self, cx);
 2154
 2155            if old_cursor_position.to_display_point(&display_map).row()
 2156                != new_cursor_position.to_display_point(&display_map).row()
 2157            {
 2158                self.available_code_actions.take();
 2159            }
 2160            self.refresh_code_actions(window, cx);
 2161            self.refresh_document_highlights(cx);
 2162            refresh_matching_bracket_highlights(self, window, cx);
 2163            self.update_visible_inline_completion(window, cx);
 2164            self.edit_prediction_requires_modifier_in_leading_space = true;
 2165            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2166            if self.git_blame_inline_enabled {
 2167                self.start_inline_blame_timer(window, cx);
 2168            }
 2169        }
 2170
 2171        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2172        cx.emit(EditorEvent::SelectionsChanged { local });
 2173
 2174        if self.selections.disjoint_anchors().len() == 1 {
 2175            cx.emit(SearchEvent::ActiveMatchChanged)
 2176        }
 2177        cx.notify();
 2178    }
 2179
 2180    pub fn change_selections<R>(
 2181        &mut self,
 2182        autoscroll: Option<Autoscroll>,
 2183        window: &mut Window,
 2184        cx: &mut Context<Self>,
 2185        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2186    ) -> R {
 2187        self.change_selections_inner(autoscroll, true, window, cx, change)
 2188    }
 2189
 2190    pub fn change_selections_inner<R>(
 2191        &mut self,
 2192        autoscroll: Option<Autoscroll>,
 2193        request_completions: bool,
 2194        window: &mut Window,
 2195        cx: &mut Context<Self>,
 2196        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2197    ) -> R {
 2198        let old_cursor_position = self.selections.newest_anchor().head();
 2199        self.push_to_selection_history();
 2200
 2201        let (changed, result) = self.selections.change_with(cx, change);
 2202
 2203        if changed {
 2204            if let Some(autoscroll) = autoscroll {
 2205                self.request_autoscroll(autoscroll, cx);
 2206            }
 2207            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2208
 2209            if self.should_open_signature_help_automatically(
 2210                &old_cursor_position,
 2211                self.signature_help_state.backspace_pressed(),
 2212                cx,
 2213            ) {
 2214                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2215            }
 2216            self.signature_help_state.set_backspace_pressed(false);
 2217        }
 2218
 2219        result
 2220    }
 2221
 2222    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2223    where
 2224        I: IntoIterator<Item = (Range<S>, T)>,
 2225        S: ToOffset,
 2226        T: Into<Arc<str>>,
 2227    {
 2228        if self.read_only(cx) {
 2229            return;
 2230        }
 2231
 2232        self.buffer
 2233            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2234    }
 2235
 2236    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2237    where
 2238        I: IntoIterator<Item = (Range<S>, T)>,
 2239        S: ToOffset,
 2240        T: Into<Arc<str>>,
 2241    {
 2242        if self.read_only(cx) {
 2243            return;
 2244        }
 2245
 2246        self.buffer.update(cx, |buffer, cx| {
 2247            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2248        });
 2249    }
 2250
 2251    pub fn edit_with_block_indent<I, S, T>(
 2252        &mut self,
 2253        edits: I,
 2254        original_indent_columns: Vec<u32>,
 2255        cx: &mut Context<Self>,
 2256    ) where
 2257        I: IntoIterator<Item = (Range<S>, T)>,
 2258        S: ToOffset,
 2259        T: Into<Arc<str>>,
 2260    {
 2261        if self.read_only(cx) {
 2262            return;
 2263        }
 2264
 2265        self.buffer.update(cx, |buffer, cx| {
 2266            buffer.edit(
 2267                edits,
 2268                Some(AutoindentMode::Block {
 2269                    original_indent_columns,
 2270                }),
 2271                cx,
 2272            )
 2273        });
 2274    }
 2275
 2276    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2277        self.hide_context_menu(window, cx);
 2278
 2279        match phase {
 2280            SelectPhase::Begin {
 2281                position,
 2282                add,
 2283                click_count,
 2284            } => self.begin_selection(position, add, click_count, window, cx),
 2285            SelectPhase::BeginColumnar {
 2286                position,
 2287                goal_column,
 2288                reset,
 2289            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2290            SelectPhase::Extend {
 2291                position,
 2292                click_count,
 2293            } => self.extend_selection(position, click_count, window, cx),
 2294            SelectPhase::Update {
 2295                position,
 2296                goal_column,
 2297                scroll_delta,
 2298            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2299            SelectPhase::End => self.end_selection(window, cx),
 2300        }
 2301    }
 2302
 2303    fn extend_selection(
 2304        &mut self,
 2305        position: DisplayPoint,
 2306        click_count: usize,
 2307        window: &mut Window,
 2308        cx: &mut Context<Self>,
 2309    ) {
 2310        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2311        let tail = self.selections.newest::<usize>(cx).tail();
 2312        self.begin_selection(position, false, click_count, window, cx);
 2313
 2314        let position = position.to_offset(&display_map, Bias::Left);
 2315        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2316
 2317        let mut pending_selection = self
 2318            .selections
 2319            .pending_anchor()
 2320            .expect("extend_selection not called with pending selection");
 2321        if position >= tail {
 2322            pending_selection.start = tail_anchor;
 2323        } else {
 2324            pending_selection.end = tail_anchor;
 2325            pending_selection.reversed = true;
 2326        }
 2327
 2328        let mut pending_mode = self.selections.pending_mode().unwrap();
 2329        match &mut pending_mode {
 2330            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2331            _ => {}
 2332        }
 2333
 2334        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2335            s.set_pending(pending_selection, pending_mode)
 2336        });
 2337    }
 2338
 2339    fn begin_selection(
 2340        &mut self,
 2341        position: DisplayPoint,
 2342        add: bool,
 2343        click_count: usize,
 2344        window: &mut Window,
 2345        cx: &mut Context<Self>,
 2346    ) {
 2347        if !self.focus_handle.is_focused(window) {
 2348            self.last_focused_descendant = None;
 2349            window.focus(&self.focus_handle);
 2350        }
 2351
 2352        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2353        let buffer = &display_map.buffer_snapshot;
 2354        let newest_selection = self.selections.newest_anchor().clone();
 2355        let position = display_map.clip_point(position, Bias::Left);
 2356
 2357        let start;
 2358        let end;
 2359        let mode;
 2360        let mut auto_scroll;
 2361        match click_count {
 2362            1 => {
 2363                start = buffer.anchor_before(position.to_point(&display_map));
 2364                end = start;
 2365                mode = SelectMode::Character;
 2366                auto_scroll = true;
 2367            }
 2368            2 => {
 2369                let range = movement::surrounding_word(&display_map, position);
 2370                start = buffer.anchor_before(range.start.to_point(&display_map));
 2371                end = buffer.anchor_before(range.end.to_point(&display_map));
 2372                mode = SelectMode::Word(start..end);
 2373                auto_scroll = true;
 2374            }
 2375            3 => {
 2376                let position = display_map
 2377                    .clip_point(position, Bias::Left)
 2378                    .to_point(&display_map);
 2379                let line_start = display_map.prev_line_boundary(position).0;
 2380                let next_line_start = buffer.clip_point(
 2381                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2382                    Bias::Left,
 2383                );
 2384                start = buffer.anchor_before(line_start);
 2385                end = buffer.anchor_before(next_line_start);
 2386                mode = SelectMode::Line(start..end);
 2387                auto_scroll = true;
 2388            }
 2389            _ => {
 2390                start = buffer.anchor_before(0);
 2391                end = buffer.anchor_before(buffer.len());
 2392                mode = SelectMode::All;
 2393                auto_scroll = false;
 2394            }
 2395        }
 2396        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2397
 2398        let point_to_delete: Option<usize> = {
 2399            let selected_points: Vec<Selection<Point>> =
 2400                self.selections.disjoint_in_range(start..end, cx);
 2401
 2402            if !add || click_count > 1 {
 2403                None
 2404            } else if !selected_points.is_empty() {
 2405                Some(selected_points[0].id)
 2406            } else {
 2407                let clicked_point_already_selected =
 2408                    self.selections.disjoint.iter().find(|selection| {
 2409                        selection.start.to_point(buffer) == start.to_point(buffer)
 2410                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2411                    });
 2412
 2413                clicked_point_already_selected.map(|selection| selection.id)
 2414            }
 2415        };
 2416
 2417        let selections_count = self.selections.count();
 2418
 2419        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2420            if let Some(point_to_delete) = point_to_delete {
 2421                s.delete(point_to_delete);
 2422
 2423                if selections_count == 1 {
 2424                    s.set_pending_anchor_range(start..end, mode);
 2425                }
 2426            } else {
 2427                if !add {
 2428                    s.clear_disjoint();
 2429                } else if click_count > 1 {
 2430                    s.delete(newest_selection.id)
 2431                }
 2432
 2433                s.set_pending_anchor_range(start..end, mode);
 2434            }
 2435        });
 2436    }
 2437
 2438    fn begin_columnar_selection(
 2439        &mut self,
 2440        position: DisplayPoint,
 2441        goal_column: u32,
 2442        reset: bool,
 2443        window: &mut Window,
 2444        cx: &mut Context<Self>,
 2445    ) {
 2446        if !self.focus_handle.is_focused(window) {
 2447            self.last_focused_descendant = None;
 2448            window.focus(&self.focus_handle);
 2449        }
 2450
 2451        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2452
 2453        if reset {
 2454            let pointer_position = display_map
 2455                .buffer_snapshot
 2456                .anchor_before(position.to_point(&display_map));
 2457
 2458            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2459                s.clear_disjoint();
 2460                s.set_pending_anchor_range(
 2461                    pointer_position..pointer_position,
 2462                    SelectMode::Character,
 2463                );
 2464            });
 2465        }
 2466
 2467        let tail = self.selections.newest::<Point>(cx).tail();
 2468        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2469
 2470        if !reset {
 2471            self.select_columns(
 2472                tail.to_display_point(&display_map),
 2473                position,
 2474                goal_column,
 2475                &display_map,
 2476                window,
 2477                cx,
 2478            );
 2479        }
 2480    }
 2481
 2482    fn update_selection(
 2483        &mut self,
 2484        position: DisplayPoint,
 2485        goal_column: u32,
 2486        scroll_delta: gpui::Point<f32>,
 2487        window: &mut Window,
 2488        cx: &mut Context<Self>,
 2489    ) {
 2490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2491
 2492        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2493            let tail = tail.to_display_point(&display_map);
 2494            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2495        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2496            let buffer = self.buffer.read(cx).snapshot(cx);
 2497            let head;
 2498            let tail;
 2499            let mode = self.selections.pending_mode().unwrap();
 2500            match &mode {
 2501                SelectMode::Character => {
 2502                    head = position.to_point(&display_map);
 2503                    tail = pending.tail().to_point(&buffer);
 2504                }
 2505                SelectMode::Word(original_range) => {
 2506                    let original_display_range = original_range.start.to_display_point(&display_map)
 2507                        ..original_range.end.to_display_point(&display_map);
 2508                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2509                        ..original_display_range.end.to_point(&display_map);
 2510                    if movement::is_inside_word(&display_map, position)
 2511                        || original_display_range.contains(&position)
 2512                    {
 2513                        let word_range = movement::surrounding_word(&display_map, position);
 2514                        if word_range.start < original_display_range.start {
 2515                            head = word_range.start.to_point(&display_map);
 2516                        } else {
 2517                            head = word_range.end.to_point(&display_map);
 2518                        }
 2519                    } else {
 2520                        head = position.to_point(&display_map);
 2521                    }
 2522
 2523                    if head <= original_buffer_range.start {
 2524                        tail = original_buffer_range.end;
 2525                    } else {
 2526                        tail = original_buffer_range.start;
 2527                    }
 2528                }
 2529                SelectMode::Line(original_range) => {
 2530                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2531
 2532                    let position = display_map
 2533                        .clip_point(position, Bias::Left)
 2534                        .to_point(&display_map);
 2535                    let line_start = display_map.prev_line_boundary(position).0;
 2536                    let next_line_start = buffer.clip_point(
 2537                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2538                        Bias::Left,
 2539                    );
 2540
 2541                    if line_start < original_range.start {
 2542                        head = line_start
 2543                    } else {
 2544                        head = next_line_start
 2545                    }
 2546
 2547                    if head <= original_range.start {
 2548                        tail = original_range.end;
 2549                    } else {
 2550                        tail = original_range.start;
 2551                    }
 2552                }
 2553                SelectMode::All => {
 2554                    return;
 2555                }
 2556            };
 2557
 2558            if head < tail {
 2559                pending.start = buffer.anchor_before(head);
 2560                pending.end = buffer.anchor_before(tail);
 2561                pending.reversed = true;
 2562            } else {
 2563                pending.start = buffer.anchor_before(tail);
 2564                pending.end = buffer.anchor_before(head);
 2565                pending.reversed = false;
 2566            }
 2567
 2568            self.change_selections(None, window, cx, |s| {
 2569                s.set_pending(pending, mode);
 2570            });
 2571        } else {
 2572            log::error!("update_selection dispatched with no pending selection");
 2573            return;
 2574        }
 2575
 2576        self.apply_scroll_delta(scroll_delta, window, cx);
 2577        cx.notify();
 2578    }
 2579
 2580    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2581        self.columnar_selection_tail.take();
 2582        if self.selections.pending_anchor().is_some() {
 2583            let selections = self.selections.all::<usize>(cx);
 2584            self.change_selections(None, window, cx, |s| {
 2585                s.select(selections);
 2586                s.clear_pending();
 2587            });
 2588        }
 2589    }
 2590
 2591    fn select_columns(
 2592        &mut self,
 2593        tail: DisplayPoint,
 2594        head: DisplayPoint,
 2595        goal_column: u32,
 2596        display_map: &DisplaySnapshot,
 2597        window: &mut Window,
 2598        cx: &mut Context<Self>,
 2599    ) {
 2600        let start_row = cmp::min(tail.row(), head.row());
 2601        let end_row = cmp::max(tail.row(), head.row());
 2602        let start_column = cmp::min(tail.column(), goal_column);
 2603        let end_column = cmp::max(tail.column(), goal_column);
 2604        let reversed = start_column < tail.column();
 2605
 2606        let selection_ranges = (start_row.0..=end_row.0)
 2607            .map(DisplayRow)
 2608            .filter_map(|row| {
 2609                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2610                    let start = display_map
 2611                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2612                        .to_point(display_map);
 2613                    let end = display_map
 2614                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2615                        .to_point(display_map);
 2616                    if reversed {
 2617                        Some(end..start)
 2618                    } else {
 2619                        Some(start..end)
 2620                    }
 2621                } else {
 2622                    None
 2623                }
 2624            })
 2625            .collect::<Vec<_>>();
 2626
 2627        self.change_selections(None, window, cx, |s| {
 2628            s.select_ranges(selection_ranges);
 2629        });
 2630        cx.notify();
 2631    }
 2632
 2633    pub fn has_pending_nonempty_selection(&self) -> bool {
 2634        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2635            Some(Selection { start, end, .. }) => start != end,
 2636            None => false,
 2637        };
 2638
 2639        pending_nonempty_selection
 2640            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2641    }
 2642
 2643    pub fn has_pending_selection(&self) -> bool {
 2644        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2645    }
 2646
 2647    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2648        self.selection_mark_mode = false;
 2649
 2650        if self.clear_expanded_diff_hunks(cx) {
 2651            cx.notify();
 2652            return;
 2653        }
 2654        if self.dismiss_menus_and_popups(true, window, cx) {
 2655            return;
 2656        }
 2657
 2658        if self.mode == EditorMode::Full
 2659            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2660        {
 2661            return;
 2662        }
 2663
 2664        cx.propagate();
 2665    }
 2666
 2667    pub fn dismiss_menus_and_popups(
 2668        &mut self,
 2669        is_user_requested: bool,
 2670        window: &mut Window,
 2671        cx: &mut Context<Self>,
 2672    ) -> bool {
 2673        if self.take_rename(false, window, cx).is_some() {
 2674            return true;
 2675        }
 2676
 2677        if hide_hover(self, cx) {
 2678            return true;
 2679        }
 2680
 2681        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2682            return true;
 2683        }
 2684
 2685        if self.hide_context_menu(window, cx).is_some() {
 2686            return true;
 2687        }
 2688
 2689        if self.mouse_context_menu.take().is_some() {
 2690            return true;
 2691        }
 2692
 2693        if is_user_requested && self.discard_inline_completion(true, cx) {
 2694            return true;
 2695        }
 2696
 2697        if self.snippet_stack.pop().is_some() {
 2698            return true;
 2699        }
 2700
 2701        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2702            self.dismiss_diagnostics(cx);
 2703            return true;
 2704        }
 2705
 2706        false
 2707    }
 2708
 2709    fn linked_editing_ranges_for(
 2710        &self,
 2711        selection: Range<text::Anchor>,
 2712        cx: &App,
 2713    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2714        if self.linked_edit_ranges.is_empty() {
 2715            return None;
 2716        }
 2717        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2718            selection.end.buffer_id.and_then(|end_buffer_id| {
 2719                if selection.start.buffer_id != Some(end_buffer_id) {
 2720                    return None;
 2721                }
 2722                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2723                let snapshot = buffer.read(cx).snapshot();
 2724                self.linked_edit_ranges
 2725                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2726                    .map(|ranges| (ranges, snapshot, buffer))
 2727            })?;
 2728        use text::ToOffset as TO;
 2729        // find offset from the start of current range to current cursor position
 2730        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2731
 2732        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2733        let start_difference = start_offset - start_byte_offset;
 2734        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2735        let end_difference = end_offset - start_byte_offset;
 2736        // Current range has associated linked ranges.
 2737        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2738        for range in linked_ranges.iter() {
 2739            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2740            let end_offset = start_offset + end_difference;
 2741            let start_offset = start_offset + start_difference;
 2742            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2743                continue;
 2744            }
 2745            if self.selections.disjoint_anchor_ranges().any(|s| {
 2746                if s.start.buffer_id != selection.start.buffer_id
 2747                    || s.end.buffer_id != selection.end.buffer_id
 2748                {
 2749                    return false;
 2750                }
 2751                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2752                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2753            }) {
 2754                continue;
 2755            }
 2756            let start = buffer_snapshot.anchor_after(start_offset);
 2757            let end = buffer_snapshot.anchor_after(end_offset);
 2758            linked_edits
 2759                .entry(buffer.clone())
 2760                .or_default()
 2761                .push(start..end);
 2762        }
 2763        Some(linked_edits)
 2764    }
 2765
 2766    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2767        let text: Arc<str> = text.into();
 2768
 2769        if self.read_only(cx) {
 2770            return;
 2771        }
 2772
 2773        let selections = self.selections.all_adjusted(cx);
 2774        let mut bracket_inserted = false;
 2775        let mut edits = Vec::new();
 2776        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2777        let mut new_selections = Vec::with_capacity(selections.len());
 2778        let mut new_autoclose_regions = Vec::new();
 2779        let snapshot = self.buffer.read(cx).read(cx);
 2780
 2781        for (selection, autoclose_region) in
 2782            self.selections_with_autoclose_regions(selections, &snapshot)
 2783        {
 2784            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2785                // Determine if the inserted text matches the opening or closing
 2786                // bracket of any of this language's bracket pairs.
 2787                let mut bracket_pair = None;
 2788                let mut is_bracket_pair_start = false;
 2789                let mut is_bracket_pair_end = false;
 2790                if !text.is_empty() {
 2791                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2792                    //  and they are removing the character that triggered IME popup.
 2793                    for (pair, enabled) in scope.brackets() {
 2794                        if !pair.close && !pair.surround {
 2795                            continue;
 2796                        }
 2797
 2798                        if enabled && pair.start.ends_with(text.as_ref()) {
 2799                            let prefix_len = pair.start.len() - text.len();
 2800                            let preceding_text_matches_prefix = prefix_len == 0
 2801                                || (selection.start.column >= (prefix_len as u32)
 2802                                    && snapshot.contains_str_at(
 2803                                        Point::new(
 2804                                            selection.start.row,
 2805                                            selection.start.column - (prefix_len as u32),
 2806                                        ),
 2807                                        &pair.start[..prefix_len],
 2808                                    ));
 2809                            if preceding_text_matches_prefix {
 2810                                bracket_pair = Some(pair.clone());
 2811                                is_bracket_pair_start = true;
 2812                                break;
 2813                            }
 2814                        }
 2815                        if pair.end.as_str() == text.as_ref() {
 2816                            bracket_pair = Some(pair.clone());
 2817                            is_bracket_pair_end = true;
 2818                            break;
 2819                        }
 2820                    }
 2821                }
 2822
 2823                if let Some(bracket_pair) = bracket_pair {
 2824                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2825                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2826                    let auto_surround =
 2827                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2828                    if selection.is_empty() {
 2829                        if is_bracket_pair_start {
 2830                            // If the inserted text is a suffix of an opening bracket and the
 2831                            // selection is preceded by the rest of the opening bracket, then
 2832                            // insert the closing bracket.
 2833                            let following_text_allows_autoclose = snapshot
 2834                                .chars_at(selection.start)
 2835                                .next()
 2836                                .map_or(true, |c| scope.should_autoclose_before(c));
 2837
 2838                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2839                                && bracket_pair.start.len() == 1
 2840                            {
 2841                                let target = bracket_pair.start.chars().next().unwrap();
 2842                                let current_line_count = snapshot
 2843                                    .reversed_chars_at(selection.start)
 2844                                    .take_while(|&c| c != '\n')
 2845                                    .filter(|&c| c == target)
 2846                                    .count();
 2847                                current_line_count % 2 == 1
 2848                            } else {
 2849                                false
 2850                            };
 2851
 2852                            if autoclose
 2853                                && bracket_pair.close
 2854                                && following_text_allows_autoclose
 2855                                && !is_closing_quote
 2856                            {
 2857                                let anchor = snapshot.anchor_before(selection.end);
 2858                                new_selections.push((selection.map(|_| anchor), text.len()));
 2859                                new_autoclose_regions.push((
 2860                                    anchor,
 2861                                    text.len(),
 2862                                    selection.id,
 2863                                    bracket_pair.clone(),
 2864                                ));
 2865                                edits.push((
 2866                                    selection.range(),
 2867                                    format!("{}{}", text, bracket_pair.end).into(),
 2868                                ));
 2869                                bracket_inserted = true;
 2870                                continue;
 2871                            }
 2872                        }
 2873
 2874                        if let Some(region) = autoclose_region {
 2875                            // If the selection is followed by an auto-inserted closing bracket,
 2876                            // then don't insert that closing bracket again; just move the selection
 2877                            // past the closing bracket.
 2878                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2879                                && text.as_ref() == region.pair.end.as_str();
 2880                            if should_skip {
 2881                                let anchor = snapshot.anchor_after(selection.end);
 2882                                new_selections
 2883                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2884                                continue;
 2885                            }
 2886                        }
 2887
 2888                        let always_treat_brackets_as_autoclosed = snapshot
 2889                            .settings_at(selection.start, cx)
 2890                            .always_treat_brackets_as_autoclosed;
 2891                        if always_treat_brackets_as_autoclosed
 2892                            && is_bracket_pair_end
 2893                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2894                        {
 2895                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2896                            // and the inserted text is a closing bracket and the selection is followed
 2897                            // by the closing bracket then move the selection past the closing bracket.
 2898                            let anchor = snapshot.anchor_after(selection.end);
 2899                            new_selections.push((selection.map(|_| anchor), text.len()));
 2900                            continue;
 2901                        }
 2902                    }
 2903                    // If an opening bracket is 1 character long and is typed while
 2904                    // text is selected, then surround that text with the bracket pair.
 2905                    else if auto_surround
 2906                        && bracket_pair.surround
 2907                        && is_bracket_pair_start
 2908                        && bracket_pair.start.chars().count() == 1
 2909                    {
 2910                        edits.push((selection.start..selection.start, text.clone()));
 2911                        edits.push((
 2912                            selection.end..selection.end,
 2913                            bracket_pair.end.as_str().into(),
 2914                        ));
 2915                        bracket_inserted = true;
 2916                        new_selections.push((
 2917                            Selection {
 2918                                id: selection.id,
 2919                                start: snapshot.anchor_after(selection.start),
 2920                                end: snapshot.anchor_before(selection.end),
 2921                                reversed: selection.reversed,
 2922                                goal: selection.goal,
 2923                            },
 2924                            0,
 2925                        ));
 2926                        continue;
 2927                    }
 2928                }
 2929            }
 2930
 2931            if self.auto_replace_emoji_shortcode
 2932                && selection.is_empty()
 2933                && text.as_ref().ends_with(':')
 2934            {
 2935                if let Some(possible_emoji_short_code) =
 2936                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2937                {
 2938                    if !possible_emoji_short_code.is_empty() {
 2939                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2940                            let emoji_shortcode_start = Point::new(
 2941                                selection.start.row,
 2942                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2943                            );
 2944
 2945                            // Remove shortcode from buffer
 2946                            edits.push((
 2947                                emoji_shortcode_start..selection.start,
 2948                                "".to_string().into(),
 2949                            ));
 2950                            new_selections.push((
 2951                                Selection {
 2952                                    id: selection.id,
 2953                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2954                                    end: snapshot.anchor_before(selection.start),
 2955                                    reversed: selection.reversed,
 2956                                    goal: selection.goal,
 2957                                },
 2958                                0,
 2959                            ));
 2960
 2961                            // Insert emoji
 2962                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2963                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2964                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2965
 2966                            continue;
 2967                        }
 2968                    }
 2969                }
 2970            }
 2971
 2972            // If not handling any auto-close operation, then just replace the selected
 2973            // text with the given input and move the selection to the end of the
 2974            // newly inserted text.
 2975            let anchor = snapshot.anchor_after(selection.end);
 2976            if !self.linked_edit_ranges.is_empty() {
 2977                let start_anchor = snapshot.anchor_before(selection.start);
 2978
 2979                let is_word_char = text.chars().next().map_or(true, |char| {
 2980                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2981                    classifier.is_word(char)
 2982                });
 2983
 2984                if is_word_char {
 2985                    if let Some(ranges) = self
 2986                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2987                    {
 2988                        for (buffer, edits) in ranges {
 2989                            linked_edits
 2990                                .entry(buffer.clone())
 2991                                .or_default()
 2992                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2993                        }
 2994                    }
 2995                }
 2996            }
 2997
 2998            new_selections.push((selection.map(|_| anchor), 0));
 2999            edits.push((selection.start..selection.end, text.clone()));
 3000        }
 3001
 3002        drop(snapshot);
 3003
 3004        self.transact(window, cx, |this, window, cx| {
 3005            this.buffer.update(cx, |buffer, cx| {
 3006                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3007            });
 3008            for (buffer, edits) in linked_edits {
 3009                buffer.update(cx, |buffer, cx| {
 3010                    let snapshot = buffer.snapshot();
 3011                    let edits = edits
 3012                        .into_iter()
 3013                        .map(|(range, text)| {
 3014                            use text::ToPoint as TP;
 3015                            let end_point = TP::to_point(&range.end, &snapshot);
 3016                            let start_point = TP::to_point(&range.start, &snapshot);
 3017                            (start_point..end_point, text)
 3018                        })
 3019                        .sorted_by_key(|(range, _)| range.start)
 3020                        .collect::<Vec<_>>();
 3021                    buffer.edit(edits, None, cx);
 3022                })
 3023            }
 3024            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3025            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3026            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3027            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3028                .zip(new_selection_deltas)
 3029                .map(|(selection, delta)| Selection {
 3030                    id: selection.id,
 3031                    start: selection.start + delta,
 3032                    end: selection.end + delta,
 3033                    reversed: selection.reversed,
 3034                    goal: SelectionGoal::None,
 3035                })
 3036                .collect::<Vec<_>>();
 3037
 3038            let mut i = 0;
 3039            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3040                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3041                let start = map.buffer_snapshot.anchor_before(position);
 3042                let end = map.buffer_snapshot.anchor_after(position);
 3043                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3044                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3045                        Ordering::Less => i += 1,
 3046                        Ordering::Greater => break,
 3047                        Ordering::Equal => {
 3048                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3049                                Ordering::Less => i += 1,
 3050                                Ordering::Equal => break,
 3051                                Ordering::Greater => break,
 3052                            }
 3053                        }
 3054                    }
 3055                }
 3056                this.autoclose_regions.insert(
 3057                    i,
 3058                    AutocloseRegion {
 3059                        selection_id,
 3060                        range: start..end,
 3061                        pair,
 3062                    },
 3063                );
 3064            }
 3065
 3066            let had_active_inline_completion = this.has_active_inline_completion();
 3067            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3068                s.select(new_selections)
 3069            });
 3070
 3071            if !bracket_inserted {
 3072                if let Some(on_type_format_task) =
 3073                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3074                {
 3075                    on_type_format_task.detach_and_log_err(cx);
 3076                }
 3077            }
 3078
 3079            let editor_settings = EditorSettings::get_global(cx);
 3080            if bracket_inserted
 3081                && (editor_settings.auto_signature_help
 3082                    || editor_settings.show_signature_help_after_edits)
 3083            {
 3084                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3085            }
 3086
 3087            let trigger_in_words =
 3088                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3089            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3090            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3091            this.refresh_inline_completion(true, false, window, cx);
 3092        });
 3093    }
 3094
 3095    fn find_possible_emoji_shortcode_at_position(
 3096        snapshot: &MultiBufferSnapshot,
 3097        position: Point,
 3098    ) -> Option<String> {
 3099        let mut chars = Vec::new();
 3100        let mut found_colon = false;
 3101        for char in snapshot.reversed_chars_at(position).take(100) {
 3102            // Found a possible emoji shortcode in the middle of the buffer
 3103            if found_colon {
 3104                if char.is_whitespace() {
 3105                    chars.reverse();
 3106                    return Some(chars.iter().collect());
 3107                }
 3108                // If the previous character is not a whitespace, we are in the middle of a word
 3109                // and we only want to complete the shortcode if the word is made up of other emojis
 3110                let mut containing_word = String::new();
 3111                for ch in snapshot
 3112                    .reversed_chars_at(position)
 3113                    .skip(chars.len() + 1)
 3114                    .take(100)
 3115                {
 3116                    if ch.is_whitespace() {
 3117                        break;
 3118                    }
 3119                    containing_word.push(ch);
 3120                }
 3121                let containing_word = containing_word.chars().rev().collect::<String>();
 3122                if util::word_consists_of_emojis(containing_word.as_str()) {
 3123                    chars.reverse();
 3124                    return Some(chars.iter().collect());
 3125                }
 3126            }
 3127
 3128            if char.is_whitespace() || !char.is_ascii() {
 3129                return None;
 3130            }
 3131            if char == ':' {
 3132                found_colon = true;
 3133            } else {
 3134                chars.push(char);
 3135            }
 3136        }
 3137        // Found a possible emoji shortcode at the beginning of the buffer
 3138        chars.reverse();
 3139        Some(chars.iter().collect())
 3140    }
 3141
 3142    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3143        self.transact(window, cx, |this, window, cx| {
 3144            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3145                let selections = this.selections.all::<usize>(cx);
 3146                let multi_buffer = this.buffer.read(cx);
 3147                let buffer = multi_buffer.snapshot(cx);
 3148                selections
 3149                    .iter()
 3150                    .map(|selection| {
 3151                        let start_point = selection.start.to_point(&buffer);
 3152                        let mut indent =
 3153                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3154                        indent.len = cmp::min(indent.len, start_point.column);
 3155                        let start = selection.start;
 3156                        let end = selection.end;
 3157                        let selection_is_empty = start == end;
 3158                        let language_scope = buffer.language_scope_at(start);
 3159                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3160                            &language_scope
 3161                        {
 3162                            let leading_whitespace_len = buffer
 3163                                .reversed_chars_at(start)
 3164                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3165                                .map(|c| c.len_utf8())
 3166                                .sum::<usize>();
 3167
 3168                            let trailing_whitespace_len = buffer
 3169                                .chars_at(end)
 3170                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3171                                .map(|c| c.len_utf8())
 3172                                .sum::<usize>();
 3173
 3174                            let insert_extra_newline =
 3175                                language.brackets().any(|(pair, enabled)| {
 3176                                    let pair_start = pair.start.trim_end();
 3177                                    let pair_end = pair.end.trim_start();
 3178
 3179                                    enabled
 3180                                        && pair.newline
 3181                                        && buffer.contains_str_at(
 3182                                            end + trailing_whitespace_len,
 3183                                            pair_end,
 3184                                        )
 3185                                        && buffer.contains_str_at(
 3186                                            (start - leading_whitespace_len)
 3187                                                .saturating_sub(pair_start.len()),
 3188                                            pair_start,
 3189                                        )
 3190                                });
 3191
 3192                            // Comment extension on newline is allowed only for cursor selections
 3193                            let comment_delimiter = maybe!({
 3194                                if !selection_is_empty {
 3195                                    return None;
 3196                                }
 3197
 3198                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3199                                    return None;
 3200                                }
 3201
 3202                                let delimiters = language.line_comment_prefixes();
 3203                                let max_len_of_delimiter =
 3204                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3205                                let (snapshot, range) =
 3206                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3207
 3208                                let mut index_of_first_non_whitespace = 0;
 3209                                let comment_candidate = snapshot
 3210                                    .chars_for_range(range)
 3211                                    .skip_while(|c| {
 3212                                        let should_skip = c.is_whitespace();
 3213                                        if should_skip {
 3214                                            index_of_first_non_whitespace += 1;
 3215                                        }
 3216                                        should_skip
 3217                                    })
 3218                                    .take(max_len_of_delimiter)
 3219                                    .collect::<String>();
 3220                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3221                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3222                                })?;
 3223                                let cursor_is_placed_after_comment_marker =
 3224                                    index_of_first_non_whitespace + comment_prefix.len()
 3225                                        <= start_point.column as usize;
 3226                                if cursor_is_placed_after_comment_marker {
 3227                                    Some(comment_prefix.clone())
 3228                                } else {
 3229                                    None
 3230                                }
 3231                            });
 3232                            (comment_delimiter, insert_extra_newline)
 3233                        } else {
 3234                            (None, false)
 3235                        };
 3236
 3237                        let capacity_for_delimiter = comment_delimiter
 3238                            .as_deref()
 3239                            .map(str::len)
 3240                            .unwrap_or_default();
 3241                        let mut new_text =
 3242                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3243                        new_text.push('\n');
 3244                        new_text.extend(indent.chars());
 3245                        if let Some(delimiter) = &comment_delimiter {
 3246                            new_text.push_str(delimiter);
 3247                        }
 3248                        if insert_extra_newline {
 3249                            new_text = new_text.repeat(2);
 3250                        }
 3251
 3252                        let anchor = buffer.anchor_after(end);
 3253                        let new_selection = selection.map(|_| anchor);
 3254                        (
 3255                            (start..end, new_text),
 3256                            (insert_extra_newline, new_selection),
 3257                        )
 3258                    })
 3259                    .unzip()
 3260            };
 3261
 3262            this.edit_with_autoindent(edits, cx);
 3263            let buffer = this.buffer.read(cx).snapshot(cx);
 3264            let new_selections = selection_fixup_info
 3265                .into_iter()
 3266                .map(|(extra_newline_inserted, new_selection)| {
 3267                    let mut cursor = new_selection.end.to_point(&buffer);
 3268                    if extra_newline_inserted {
 3269                        cursor.row -= 1;
 3270                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3271                    }
 3272                    new_selection.map(|_| cursor)
 3273                })
 3274                .collect();
 3275
 3276            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3277                s.select(new_selections)
 3278            });
 3279            this.refresh_inline_completion(true, false, window, cx);
 3280        });
 3281    }
 3282
 3283    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3284        let buffer = self.buffer.read(cx);
 3285        let snapshot = buffer.snapshot(cx);
 3286
 3287        let mut edits = Vec::new();
 3288        let mut rows = Vec::new();
 3289
 3290        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3291            let cursor = selection.head();
 3292            let row = cursor.row;
 3293
 3294            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3295
 3296            let newline = "\n".to_string();
 3297            edits.push((start_of_line..start_of_line, newline));
 3298
 3299            rows.push(row + rows_inserted as u32);
 3300        }
 3301
 3302        self.transact(window, cx, |editor, window, cx| {
 3303            editor.edit(edits, cx);
 3304
 3305            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3306                let mut index = 0;
 3307                s.move_cursors_with(|map, _, _| {
 3308                    let row = rows[index];
 3309                    index += 1;
 3310
 3311                    let point = Point::new(row, 0);
 3312                    let boundary = map.next_line_boundary(point).1;
 3313                    let clipped = map.clip_point(boundary, Bias::Left);
 3314
 3315                    (clipped, SelectionGoal::None)
 3316                });
 3317            });
 3318
 3319            let mut indent_edits = Vec::new();
 3320            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3321            for row in rows {
 3322                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3323                for (row, indent) in indents {
 3324                    if indent.len == 0 {
 3325                        continue;
 3326                    }
 3327
 3328                    let text = match indent.kind {
 3329                        IndentKind::Space => " ".repeat(indent.len as usize),
 3330                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3331                    };
 3332                    let point = Point::new(row.0, 0);
 3333                    indent_edits.push((point..point, text));
 3334                }
 3335            }
 3336            editor.edit(indent_edits, cx);
 3337        });
 3338    }
 3339
 3340    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3341        let buffer = self.buffer.read(cx);
 3342        let snapshot = buffer.snapshot(cx);
 3343
 3344        let mut edits = Vec::new();
 3345        let mut rows = Vec::new();
 3346        let mut rows_inserted = 0;
 3347
 3348        for selection in self.selections.all_adjusted(cx) {
 3349            let cursor = selection.head();
 3350            let row = cursor.row;
 3351
 3352            let point = Point::new(row + 1, 0);
 3353            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3354
 3355            let newline = "\n".to_string();
 3356            edits.push((start_of_line..start_of_line, newline));
 3357
 3358            rows_inserted += 1;
 3359            rows.push(row + rows_inserted);
 3360        }
 3361
 3362        self.transact(window, cx, |editor, window, cx| {
 3363            editor.edit(edits, cx);
 3364
 3365            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3366                let mut index = 0;
 3367                s.move_cursors_with(|map, _, _| {
 3368                    let row = rows[index];
 3369                    index += 1;
 3370
 3371                    let point = Point::new(row, 0);
 3372                    let boundary = map.next_line_boundary(point).1;
 3373                    let clipped = map.clip_point(boundary, Bias::Left);
 3374
 3375                    (clipped, SelectionGoal::None)
 3376                });
 3377            });
 3378
 3379            let mut indent_edits = Vec::new();
 3380            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3381            for row in rows {
 3382                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3383                for (row, indent) in indents {
 3384                    if indent.len == 0 {
 3385                        continue;
 3386                    }
 3387
 3388                    let text = match indent.kind {
 3389                        IndentKind::Space => " ".repeat(indent.len as usize),
 3390                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3391                    };
 3392                    let point = Point::new(row.0, 0);
 3393                    indent_edits.push((point..point, text));
 3394                }
 3395            }
 3396            editor.edit(indent_edits, cx);
 3397        });
 3398    }
 3399
 3400    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3401        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3402            original_indent_columns: Vec::new(),
 3403        });
 3404        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3405    }
 3406
 3407    fn insert_with_autoindent_mode(
 3408        &mut self,
 3409        text: &str,
 3410        autoindent_mode: Option<AutoindentMode>,
 3411        window: &mut Window,
 3412        cx: &mut Context<Self>,
 3413    ) {
 3414        if self.read_only(cx) {
 3415            return;
 3416        }
 3417
 3418        let text: Arc<str> = text.into();
 3419        self.transact(window, cx, |this, window, cx| {
 3420            let old_selections = this.selections.all_adjusted(cx);
 3421            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3422                let anchors = {
 3423                    let snapshot = buffer.read(cx);
 3424                    old_selections
 3425                        .iter()
 3426                        .map(|s| {
 3427                            let anchor = snapshot.anchor_after(s.head());
 3428                            s.map(|_| anchor)
 3429                        })
 3430                        .collect::<Vec<_>>()
 3431                };
 3432                buffer.edit(
 3433                    old_selections
 3434                        .iter()
 3435                        .map(|s| (s.start..s.end, text.clone())),
 3436                    autoindent_mode,
 3437                    cx,
 3438                );
 3439                anchors
 3440            });
 3441
 3442            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3443                s.select_anchors(selection_anchors);
 3444            });
 3445
 3446            cx.notify();
 3447        });
 3448    }
 3449
 3450    fn trigger_completion_on_input(
 3451        &mut self,
 3452        text: &str,
 3453        trigger_in_words: bool,
 3454        window: &mut Window,
 3455        cx: &mut Context<Self>,
 3456    ) {
 3457        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3458            self.show_completions(
 3459                &ShowCompletions {
 3460                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3461                },
 3462                window,
 3463                cx,
 3464            );
 3465        } else {
 3466            self.hide_context_menu(window, cx);
 3467        }
 3468    }
 3469
 3470    fn is_completion_trigger(
 3471        &self,
 3472        text: &str,
 3473        trigger_in_words: bool,
 3474        cx: &mut Context<Self>,
 3475    ) -> bool {
 3476        let position = self.selections.newest_anchor().head();
 3477        let multibuffer = self.buffer.read(cx);
 3478        let Some(buffer) = position
 3479            .buffer_id
 3480            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3481        else {
 3482            return false;
 3483        };
 3484
 3485        if let Some(completion_provider) = &self.completion_provider {
 3486            completion_provider.is_completion_trigger(
 3487                &buffer,
 3488                position.text_anchor,
 3489                text,
 3490                trigger_in_words,
 3491                cx,
 3492            )
 3493        } else {
 3494            false
 3495        }
 3496    }
 3497
 3498    /// If any empty selections is touching the start of its innermost containing autoclose
 3499    /// region, expand it to select the brackets.
 3500    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3501        let selections = self.selections.all::<usize>(cx);
 3502        let buffer = self.buffer.read(cx).read(cx);
 3503        let new_selections = self
 3504            .selections_with_autoclose_regions(selections, &buffer)
 3505            .map(|(mut selection, region)| {
 3506                if !selection.is_empty() {
 3507                    return selection;
 3508                }
 3509
 3510                if let Some(region) = region {
 3511                    let mut range = region.range.to_offset(&buffer);
 3512                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3513                        range.start -= region.pair.start.len();
 3514                        if buffer.contains_str_at(range.start, &region.pair.start)
 3515                            && buffer.contains_str_at(range.end, &region.pair.end)
 3516                        {
 3517                            range.end += region.pair.end.len();
 3518                            selection.start = range.start;
 3519                            selection.end = range.end;
 3520
 3521                            return selection;
 3522                        }
 3523                    }
 3524                }
 3525
 3526                let always_treat_brackets_as_autoclosed = buffer
 3527                    .settings_at(selection.start, cx)
 3528                    .always_treat_brackets_as_autoclosed;
 3529
 3530                if !always_treat_brackets_as_autoclosed {
 3531                    return selection;
 3532                }
 3533
 3534                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3535                    for (pair, enabled) in scope.brackets() {
 3536                        if !enabled || !pair.close {
 3537                            continue;
 3538                        }
 3539
 3540                        if buffer.contains_str_at(selection.start, &pair.end) {
 3541                            let pair_start_len = pair.start.len();
 3542                            if buffer.contains_str_at(
 3543                                selection.start.saturating_sub(pair_start_len),
 3544                                &pair.start,
 3545                            ) {
 3546                                selection.start -= pair_start_len;
 3547                                selection.end += pair.end.len();
 3548
 3549                                return selection;
 3550                            }
 3551                        }
 3552                    }
 3553                }
 3554
 3555                selection
 3556            })
 3557            .collect();
 3558
 3559        drop(buffer);
 3560        self.change_selections(None, window, cx, |selections| {
 3561            selections.select(new_selections)
 3562        });
 3563    }
 3564
 3565    /// Iterate the given selections, and for each one, find the smallest surrounding
 3566    /// autoclose region. This uses the ordering of the selections and the autoclose
 3567    /// regions to avoid repeated comparisons.
 3568    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3569        &'a self,
 3570        selections: impl IntoIterator<Item = Selection<D>>,
 3571        buffer: &'a MultiBufferSnapshot,
 3572    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3573        let mut i = 0;
 3574        let mut regions = self.autoclose_regions.as_slice();
 3575        selections.into_iter().map(move |selection| {
 3576            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3577
 3578            let mut enclosing = None;
 3579            while let Some(pair_state) = regions.get(i) {
 3580                if pair_state.range.end.to_offset(buffer) < range.start {
 3581                    regions = &regions[i + 1..];
 3582                    i = 0;
 3583                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3584                    break;
 3585                } else {
 3586                    if pair_state.selection_id == selection.id {
 3587                        enclosing = Some(pair_state);
 3588                    }
 3589                    i += 1;
 3590                }
 3591            }
 3592
 3593            (selection, enclosing)
 3594        })
 3595    }
 3596
 3597    /// Remove any autoclose regions that no longer contain their selection.
 3598    fn invalidate_autoclose_regions(
 3599        &mut self,
 3600        mut selections: &[Selection<Anchor>],
 3601        buffer: &MultiBufferSnapshot,
 3602    ) {
 3603        self.autoclose_regions.retain(|state| {
 3604            let mut i = 0;
 3605            while let Some(selection) = selections.get(i) {
 3606                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3607                    selections = &selections[1..];
 3608                    continue;
 3609                }
 3610                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3611                    break;
 3612                }
 3613                if selection.id == state.selection_id {
 3614                    return true;
 3615                } else {
 3616                    i += 1;
 3617                }
 3618            }
 3619            false
 3620        });
 3621    }
 3622
 3623    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3624        let offset = position.to_offset(buffer);
 3625        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3626        if offset > word_range.start && kind == Some(CharKind::Word) {
 3627            Some(
 3628                buffer
 3629                    .text_for_range(word_range.start..offset)
 3630                    .collect::<String>(),
 3631            )
 3632        } else {
 3633            None
 3634        }
 3635    }
 3636
 3637    pub fn toggle_inlay_hints(
 3638        &mut self,
 3639        _: &ToggleInlayHints,
 3640        _: &mut Window,
 3641        cx: &mut Context<Self>,
 3642    ) {
 3643        self.refresh_inlay_hints(
 3644            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3645            cx,
 3646        );
 3647    }
 3648
 3649    pub fn inlay_hints_enabled(&self) -> bool {
 3650        self.inlay_hint_cache.enabled
 3651    }
 3652
 3653    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3654        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3655            return;
 3656        }
 3657
 3658        let reason_description = reason.description();
 3659        let ignore_debounce = matches!(
 3660            reason,
 3661            InlayHintRefreshReason::SettingsChange(_)
 3662                | InlayHintRefreshReason::Toggle(_)
 3663                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3664        );
 3665        let (invalidate_cache, required_languages) = match reason {
 3666            InlayHintRefreshReason::Toggle(enabled) => {
 3667                self.inlay_hint_cache.enabled = enabled;
 3668                if enabled {
 3669                    (InvalidationStrategy::RefreshRequested, None)
 3670                } else {
 3671                    self.inlay_hint_cache.clear();
 3672                    self.splice_inlays(
 3673                        &self
 3674                            .visible_inlay_hints(cx)
 3675                            .iter()
 3676                            .map(|inlay| inlay.id)
 3677                            .collect::<Vec<InlayId>>(),
 3678                        Vec::new(),
 3679                        cx,
 3680                    );
 3681                    return;
 3682                }
 3683            }
 3684            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3685                match self.inlay_hint_cache.update_settings(
 3686                    &self.buffer,
 3687                    new_settings,
 3688                    self.visible_inlay_hints(cx),
 3689                    cx,
 3690                ) {
 3691                    ControlFlow::Break(Some(InlaySplice {
 3692                        to_remove,
 3693                        to_insert,
 3694                    })) => {
 3695                        self.splice_inlays(&to_remove, to_insert, cx);
 3696                        return;
 3697                    }
 3698                    ControlFlow::Break(None) => return,
 3699                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3700                }
 3701            }
 3702            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3703                if let Some(InlaySplice {
 3704                    to_remove,
 3705                    to_insert,
 3706                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3707                {
 3708                    self.splice_inlays(&to_remove, to_insert, cx);
 3709                }
 3710                return;
 3711            }
 3712            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3713            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3714                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3715            }
 3716            InlayHintRefreshReason::RefreshRequested => {
 3717                (InvalidationStrategy::RefreshRequested, None)
 3718            }
 3719        };
 3720
 3721        if let Some(InlaySplice {
 3722            to_remove,
 3723            to_insert,
 3724        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3725            reason_description,
 3726            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3727            invalidate_cache,
 3728            ignore_debounce,
 3729            cx,
 3730        ) {
 3731            self.splice_inlays(&to_remove, to_insert, cx);
 3732        }
 3733    }
 3734
 3735    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3736        self.display_map
 3737            .read(cx)
 3738            .current_inlays()
 3739            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3740            .cloned()
 3741            .collect()
 3742    }
 3743
 3744    pub fn excerpts_for_inlay_hints_query(
 3745        &self,
 3746        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3747        cx: &mut Context<Editor>,
 3748    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3749        let Some(project) = self.project.as_ref() else {
 3750            return HashMap::default();
 3751        };
 3752        let project = project.read(cx);
 3753        let multi_buffer = self.buffer().read(cx);
 3754        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3755        let multi_buffer_visible_start = self
 3756            .scroll_manager
 3757            .anchor()
 3758            .anchor
 3759            .to_point(&multi_buffer_snapshot);
 3760        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3761            multi_buffer_visible_start
 3762                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3763            Bias::Left,
 3764        );
 3765        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3766        multi_buffer_snapshot
 3767            .range_to_buffer_ranges(multi_buffer_visible_range)
 3768            .into_iter()
 3769            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3770            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3771                let buffer_file = project::File::from_dyn(buffer.file())?;
 3772                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3773                let worktree_entry = buffer_worktree
 3774                    .read(cx)
 3775                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3776                if worktree_entry.is_ignored {
 3777                    return None;
 3778                }
 3779
 3780                let language = buffer.language()?;
 3781                if let Some(restrict_to_languages) = restrict_to_languages {
 3782                    if !restrict_to_languages.contains(language) {
 3783                        return None;
 3784                    }
 3785                }
 3786                Some((
 3787                    excerpt_id,
 3788                    (
 3789                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3790                        buffer.version().clone(),
 3791                        excerpt_visible_range,
 3792                    ),
 3793                ))
 3794            })
 3795            .collect()
 3796    }
 3797
 3798    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3799        TextLayoutDetails {
 3800            text_system: window.text_system().clone(),
 3801            editor_style: self.style.clone().unwrap(),
 3802            rem_size: window.rem_size(),
 3803            scroll_anchor: self.scroll_manager.anchor(),
 3804            visible_rows: self.visible_line_count(),
 3805            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3806        }
 3807    }
 3808
 3809    pub fn splice_inlays(
 3810        &self,
 3811        to_remove: &[InlayId],
 3812        to_insert: Vec<Inlay>,
 3813        cx: &mut Context<Self>,
 3814    ) {
 3815        self.display_map.update(cx, |display_map, cx| {
 3816            display_map.splice_inlays(to_remove, to_insert, cx)
 3817        });
 3818        cx.notify();
 3819    }
 3820
 3821    fn trigger_on_type_formatting(
 3822        &self,
 3823        input: String,
 3824        window: &mut Window,
 3825        cx: &mut Context<Self>,
 3826    ) -> Option<Task<Result<()>>> {
 3827        if input.len() != 1 {
 3828            return None;
 3829        }
 3830
 3831        let project = self.project.as_ref()?;
 3832        let position = self.selections.newest_anchor().head();
 3833        let (buffer, buffer_position) = self
 3834            .buffer
 3835            .read(cx)
 3836            .text_anchor_for_position(position, cx)?;
 3837
 3838        let settings = language_settings::language_settings(
 3839            buffer
 3840                .read(cx)
 3841                .language_at(buffer_position)
 3842                .map(|l| l.name()),
 3843            buffer.read(cx).file(),
 3844            cx,
 3845        );
 3846        if !settings.use_on_type_format {
 3847            return None;
 3848        }
 3849
 3850        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3851        // hence we do LSP request & edit on host side only — add formats to host's history.
 3852        let push_to_lsp_host_history = true;
 3853        // If this is not the host, append its history with new edits.
 3854        let push_to_client_history = project.read(cx).is_via_collab();
 3855
 3856        let on_type_formatting = project.update(cx, |project, cx| {
 3857            project.on_type_format(
 3858                buffer.clone(),
 3859                buffer_position,
 3860                input,
 3861                push_to_lsp_host_history,
 3862                cx,
 3863            )
 3864        });
 3865        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3866            if let Some(transaction) = on_type_formatting.await? {
 3867                if push_to_client_history {
 3868                    buffer
 3869                        .update(&mut cx, |buffer, _| {
 3870                            buffer.push_transaction(transaction, Instant::now());
 3871                        })
 3872                        .ok();
 3873                }
 3874                editor.update(&mut cx, |editor, cx| {
 3875                    editor.refresh_document_highlights(cx);
 3876                })?;
 3877            }
 3878            Ok(())
 3879        }))
 3880    }
 3881
 3882    pub fn show_completions(
 3883        &mut self,
 3884        options: &ShowCompletions,
 3885        window: &mut Window,
 3886        cx: &mut Context<Self>,
 3887    ) {
 3888        if self.pending_rename.is_some() {
 3889            return;
 3890        }
 3891
 3892        let Some(provider) = self.completion_provider.as_ref() else {
 3893            return;
 3894        };
 3895
 3896        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3897            return;
 3898        }
 3899
 3900        let position = self.selections.newest_anchor().head();
 3901        if position.diff_base_anchor.is_some() {
 3902            return;
 3903        }
 3904        let (buffer, buffer_position) =
 3905            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3906                output
 3907            } else {
 3908                return;
 3909            };
 3910        let show_completion_documentation = buffer
 3911            .read(cx)
 3912            .snapshot()
 3913            .settings_at(buffer_position, cx)
 3914            .show_completion_documentation;
 3915
 3916        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3917
 3918        let trigger_kind = match &options.trigger {
 3919            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3920                CompletionTriggerKind::TRIGGER_CHARACTER
 3921            }
 3922            _ => CompletionTriggerKind::INVOKED,
 3923        };
 3924        let completion_context = CompletionContext {
 3925            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3926                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3927                    Some(String::from(trigger))
 3928                } else {
 3929                    None
 3930                }
 3931            }),
 3932            trigger_kind,
 3933        };
 3934        let completions =
 3935            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3936        let sort_completions = provider.sort_completions();
 3937
 3938        let id = post_inc(&mut self.next_completion_id);
 3939        let task = cx.spawn_in(window, |editor, mut cx| {
 3940            async move {
 3941                editor.update(&mut cx, |this, _| {
 3942                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3943                })?;
 3944                let completions = completions.await.log_err();
 3945                let menu = if let Some(completions) = completions {
 3946                    let mut menu = CompletionsMenu::new(
 3947                        id,
 3948                        sort_completions,
 3949                        show_completion_documentation,
 3950                        position,
 3951                        buffer.clone(),
 3952                        completions.into(),
 3953                    );
 3954
 3955                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3956                        .await;
 3957
 3958                    menu.visible().then_some(menu)
 3959                } else {
 3960                    None
 3961                };
 3962
 3963                editor.update_in(&mut cx, |editor, window, cx| {
 3964                    match editor.context_menu.borrow().as_ref() {
 3965                        None => {}
 3966                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3967                            if prev_menu.id > id {
 3968                                return;
 3969                            }
 3970                        }
 3971                        _ => return,
 3972                    }
 3973
 3974                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3975                        let mut menu = menu.unwrap();
 3976                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3977
 3978                        *editor.context_menu.borrow_mut() =
 3979                            Some(CodeContextMenu::Completions(menu));
 3980
 3981                        if editor.show_edit_predictions_in_menu() {
 3982                            editor.update_visible_inline_completion(window, cx);
 3983                        } else {
 3984                            editor.discard_inline_completion(false, cx);
 3985                        }
 3986
 3987                        cx.notify();
 3988                    } else if editor.completion_tasks.len() <= 1 {
 3989                        // If there are no more completion tasks and the last menu was
 3990                        // empty, we should hide it.
 3991                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3992                        // If it was already hidden and we don't show inline
 3993                        // completions in the menu, we should also show the
 3994                        // inline-completion when available.
 3995                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3996                            editor.update_visible_inline_completion(window, cx);
 3997                        }
 3998                    }
 3999                })?;
 4000
 4001                Ok::<_, anyhow::Error>(())
 4002            }
 4003            .log_err()
 4004        });
 4005
 4006        self.completion_tasks.push((id, task));
 4007    }
 4008
 4009    pub fn confirm_completion(
 4010        &mut self,
 4011        action: &ConfirmCompletion,
 4012        window: &mut Window,
 4013        cx: &mut Context<Self>,
 4014    ) -> Option<Task<Result<()>>> {
 4015        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4016    }
 4017
 4018    pub fn compose_completion(
 4019        &mut self,
 4020        action: &ComposeCompletion,
 4021        window: &mut Window,
 4022        cx: &mut Context<Self>,
 4023    ) -> Option<Task<Result<()>>> {
 4024        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4025    }
 4026
 4027    fn do_completion(
 4028        &mut self,
 4029        item_ix: Option<usize>,
 4030        intent: CompletionIntent,
 4031        window: &mut Window,
 4032        cx: &mut Context<Editor>,
 4033    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4034        use language::ToOffset as _;
 4035
 4036        let completions_menu =
 4037            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4038                menu
 4039            } else {
 4040                return None;
 4041            };
 4042
 4043        let entries = completions_menu.entries.borrow();
 4044        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4045        if self.show_edit_predictions_in_menu() {
 4046            self.discard_inline_completion(true, cx);
 4047        }
 4048        let candidate_id = mat.candidate_id;
 4049        drop(entries);
 4050
 4051        let buffer_handle = completions_menu.buffer;
 4052        let completion = completions_menu
 4053            .completions
 4054            .borrow()
 4055            .get(candidate_id)?
 4056            .clone();
 4057        cx.stop_propagation();
 4058
 4059        let snippet;
 4060        let text;
 4061
 4062        if completion.is_snippet() {
 4063            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4064            text = snippet.as_ref().unwrap().text.clone();
 4065        } else {
 4066            snippet = None;
 4067            text = completion.new_text.clone();
 4068        };
 4069        let selections = self.selections.all::<usize>(cx);
 4070        let buffer = buffer_handle.read(cx);
 4071        let old_range = completion.old_range.to_offset(buffer);
 4072        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4073
 4074        let newest_selection = self.selections.newest_anchor();
 4075        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4076            return None;
 4077        }
 4078
 4079        let lookbehind = newest_selection
 4080            .start
 4081            .text_anchor
 4082            .to_offset(buffer)
 4083            .saturating_sub(old_range.start);
 4084        let lookahead = old_range
 4085            .end
 4086            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4087        let mut common_prefix_len = old_text
 4088            .bytes()
 4089            .zip(text.bytes())
 4090            .take_while(|(a, b)| a == b)
 4091            .count();
 4092
 4093        let snapshot = self.buffer.read(cx).snapshot(cx);
 4094        let mut range_to_replace: Option<Range<isize>> = None;
 4095        let mut ranges = Vec::new();
 4096        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4097        for selection in &selections {
 4098            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4099                let start = selection.start.saturating_sub(lookbehind);
 4100                let end = selection.end + lookahead;
 4101                if selection.id == newest_selection.id {
 4102                    range_to_replace = Some(
 4103                        ((start + common_prefix_len) as isize - selection.start as isize)
 4104                            ..(end as isize - selection.start as isize),
 4105                    );
 4106                }
 4107                ranges.push(start + common_prefix_len..end);
 4108            } else {
 4109                common_prefix_len = 0;
 4110                ranges.clear();
 4111                ranges.extend(selections.iter().map(|s| {
 4112                    if s.id == newest_selection.id {
 4113                        range_to_replace = Some(
 4114                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4115                                - selection.start as isize
 4116                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4117                                    - selection.start as isize,
 4118                        );
 4119                        old_range.clone()
 4120                    } else {
 4121                        s.start..s.end
 4122                    }
 4123                }));
 4124                break;
 4125            }
 4126            if !self.linked_edit_ranges.is_empty() {
 4127                let start_anchor = snapshot.anchor_before(selection.head());
 4128                let end_anchor = snapshot.anchor_after(selection.tail());
 4129                if let Some(ranges) = self
 4130                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4131                {
 4132                    for (buffer, edits) in ranges {
 4133                        linked_edits.entry(buffer.clone()).or_default().extend(
 4134                            edits
 4135                                .into_iter()
 4136                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4137                        );
 4138                    }
 4139                }
 4140            }
 4141        }
 4142        let text = &text[common_prefix_len..];
 4143
 4144        cx.emit(EditorEvent::InputHandled {
 4145            utf16_range_to_replace: range_to_replace,
 4146            text: text.into(),
 4147        });
 4148
 4149        self.transact(window, cx, |this, window, cx| {
 4150            if let Some(mut snippet) = snippet {
 4151                snippet.text = text.to_string();
 4152                for tabstop in snippet
 4153                    .tabstops
 4154                    .iter_mut()
 4155                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4156                {
 4157                    tabstop.start -= common_prefix_len as isize;
 4158                    tabstop.end -= common_prefix_len as isize;
 4159                }
 4160
 4161                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4162            } else {
 4163                this.buffer.update(cx, |buffer, cx| {
 4164                    buffer.edit(
 4165                        ranges.iter().map(|range| (range.clone(), text)),
 4166                        this.autoindent_mode.clone(),
 4167                        cx,
 4168                    );
 4169                });
 4170            }
 4171            for (buffer, edits) in linked_edits {
 4172                buffer.update(cx, |buffer, cx| {
 4173                    let snapshot = buffer.snapshot();
 4174                    let edits = edits
 4175                        .into_iter()
 4176                        .map(|(range, text)| {
 4177                            use text::ToPoint as TP;
 4178                            let end_point = TP::to_point(&range.end, &snapshot);
 4179                            let start_point = TP::to_point(&range.start, &snapshot);
 4180                            (start_point..end_point, text)
 4181                        })
 4182                        .sorted_by_key(|(range, _)| range.start)
 4183                        .collect::<Vec<_>>();
 4184                    buffer.edit(edits, None, cx);
 4185                })
 4186            }
 4187
 4188            this.refresh_inline_completion(true, false, window, cx);
 4189        });
 4190
 4191        let show_new_completions_on_confirm = completion
 4192            .confirm
 4193            .as_ref()
 4194            .map_or(false, |confirm| confirm(intent, window, cx));
 4195        if show_new_completions_on_confirm {
 4196            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4197        }
 4198
 4199        let provider = self.completion_provider.as_ref()?;
 4200        drop(completion);
 4201        let apply_edits = provider.apply_additional_edits_for_completion(
 4202            buffer_handle,
 4203            completions_menu.completions.clone(),
 4204            candidate_id,
 4205            true,
 4206            cx,
 4207        );
 4208
 4209        let editor_settings = EditorSettings::get_global(cx);
 4210        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4211            // After the code completion is finished, users often want to know what signatures are needed.
 4212            // so we should automatically call signature_help
 4213            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4214        }
 4215
 4216        Some(cx.foreground_executor().spawn(async move {
 4217            apply_edits.await?;
 4218            Ok(())
 4219        }))
 4220    }
 4221
 4222    pub fn toggle_code_actions(
 4223        &mut self,
 4224        action: &ToggleCodeActions,
 4225        window: &mut Window,
 4226        cx: &mut Context<Self>,
 4227    ) {
 4228        let mut context_menu = self.context_menu.borrow_mut();
 4229        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4230            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4231                // Toggle if we're selecting the same one
 4232                *context_menu = None;
 4233                cx.notify();
 4234                return;
 4235            } else {
 4236                // Otherwise, clear it and start a new one
 4237                *context_menu = None;
 4238                cx.notify();
 4239            }
 4240        }
 4241        drop(context_menu);
 4242        let snapshot = self.snapshot(window, cx);
 4243        let deployed_from_indicator = action.deployed_from_indicator;
 4244        let mut task = self.code_actions_task.take();
 4245        let action = action.clone();
 4246        cx.spawn_in(window, |editor, mut cx| async move {
 4247            while let Some(prev_task) = task {
 4248                prev_task.await.log_err();
 4249                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4250            }
 4251
 4252            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4253                if editor.focus_handle.is_focused(window) {
 4254                    let multibuffer_point = action
 4255                        .deployed_from_indicator
 4256                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4257                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4258                    let (buffer, buffer_row) = snapshot
 4259                        .buffer_snapshot
 4260                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4261                        .and_then(|(buffer_snapshot, range)| {
 4262                            editor
 4263                                .buffer
 4264                                .read(cx)
 4265                                .buffer(buffer_snapshot.remote_id())
 4266                                .map(|buffer| (buffer, range.start.row))
 4267                        })?;
 4268                    let (_, code_actions) = editor
 4269                        .available_code_actions
 4270                        .clone()
 4271                        .and_then(|(location, code_actions)| {
 4272                            let snapshot = location.buffer.read(cx).snapshot();
 4273                            let point_range = location.range.to_point(&snapshot);
 4274                            let point_range = point_range.start.row..=point_range.end.row;
 4275                            if point_range.contains(&buffer_row) {
 4276                                Some((location, code_actions))
 4277                            } else {
 4278                                None
 4279                            }
 4280                        })
 4281                        .unzip();
 4282                    let buffer_id = buffer.read(cx).remote_id();
 4283                    let tasks = editor
 4284                        .tasks
 4285                        .get(&(buffer_id, buffer_row))
 4286                        .map(|t| Arc::new(t.to_owned()));
 4287                    if tasks.is_none() && code_actions.is_none() {
 4288                        return None;
 4289                    }
 4290
 4291                    editor.completion_tasks.clear();
 4292                    editor.discard_inline_completion(false, cx);
 4293                    let task_context =
 4294                        tasks
 4295                            .as_ref()
 4296                            .zip(editor.project.clone())
 4297                            .map(|(tasks, project)| {
 4298                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4299                            });
 4300
 4301                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4302                        let task_context = match task_context {
 4303                            Some(task_context) => task_context.await,
 4304                            None => None,
 4305                        };
 4306                        let resolved_tasks =
 4307                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4308                                Rc::new(ResolvedTasks {
 4309                                    templates: tasks.resolve(&task_context).collect(),
 4310                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4311                                        multibuffer_point.row,
 4312                                        tasks.column,
 4313                                    )),
 4314                                })
 4315                            });
 4316                        let spawn_straight_away = resolved_tasks
 4317                            .as_ref()
 4318                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4319                            && code_actions
 4320                                .as_ref()
 4321                                .map_or(true, |actions| actions.is_empty());
 4322                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4323                            *editor.context_menu.borrow_mut() =
 4324                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4325                                    buffer,
 4326                                    actions: CodeActionContents {
 4327                                        tasks: resolved_tasks,
 4328                                        actions: code_actions,
 4329                                    },
 4330                                    selected_item: Default::default(),
 4331                                    scroll_handle: UniformListScrollHandle::default(),
 4332                                    deployed_from_indicator,
 4333                                }));
 4334                            if spawn_straight_away {
 4335                                if let Some(task) = editor.confirm_code_action(
 4336                                    &ConfirmCodeAction { item_ix: Some(0) },
 4337                                    window,
 4338                                    cx,
 4339                                ) {
 4340                                    cx.notify();
 4341                                    return task;
 4342                                }
 4343                            }
 4344                            cx.notify();
 4345                            Task::ready(Ok(()))
 4346                        }) {
 4347                            task.await
 4348                        } else {
 4349                            Ok(())
 4350                        }
 4351                    }))
 4352                } else {
 4353                    Some(Task::ready(Ok(())))
 4354                }
 4355            })?;
 4356            if let Some(task) = spawned_test_task {
 4357                task.await?;
 4358            }
 4359
 4360            Ok::<_, anyhow::Error>(())
 4361        })
 4362        .detach_and_log_err(cx);
 4363    }
 4364
 4365    pub fn confirm_code_action(
 4366        &mut self,
 4367        action: &ConfirmCodeAction,
 4368        window: &mut Window,
 4369        cx: &mut Context<Self>,
 4370    ) -> Option<Task<Result<()>>> {
 4371        let actions_menu =
 4372            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4373                menu
 4374            } else {
 4375                return None;
 4376            };
 4377        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4378        let action = actions_menu.actions.get(action_ix)?;
 4379        let title = action.label();
 4380        let buffer = actions_menu.buffer;
 4381        let workspace = self.workspace()?;
 4382
 4383        match action {
 4384            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4385                workspace.update(cx, |workspace, cx| {
 4386                    workspace::tasks::schedule_resolved_task(
 4387                        workspace,
 4388                        task_source_kind,
 4389                        resolved_task,
 4390                        false,
 4391                        cx,
 4392                    );
 4393
 4394                    Some(Task::ready(Ok(())))
 4395                })
 4396            }
 4397            CodeActionsItem::CodeAction {
 4398                excerpt_id,
 4399                action,
 4400                provider,
 4401            } => {
 4402                let apply_code_action =
 4403                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4404                let workspace = workspace.downgrade();
 4405                Some(cx.spawn_in(window, |editor, cx| async move {
 4406                    let project_transaction = apply_code_action.await?;
 4407                    Self::open_project_transaction(
 4408                        &editor,
 4409                        workspace,
 4410                        project_transaction,
 4411                        title,
 4412                        cx,
 4413                    )
 4414                    .await
 4415                }))
 4416            }
 4417        }
 4418    }
 4419
 4420    pub async fn open_project_transaction(
 4421        this: &WeakEntity<Editor>,
 4422        workspace: WeakEntity<Workspace>,
 4423        transaction: ProjectTransaction,
 4424        title: String,
 4425        mut cx: AsyncWindowContext,
 4426    ) -> Result<()> {
 4427        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4428        cx.update(|_, cx| {
 4429            entries.sort_unstable_by_key(|(buffer, _)| {
 4430                buffer.read(cx).file().map(|f| f.path().clone())
 4431            });
 4432        })?;
 4433
 4434        // If the project transaction's edits are all contained within this editor, then
 4435        // avoid opening a new editor to display them.
 4436
 4437        if let Some((buffer, transaction)) = entries.first() {
 4438            if entries.len() == 1 {
 4439                let excerpt = this.update(&mut cx, |editor, cx| {
 4440                    editor
 4441                        .buffer()
 4442                        .read(cx)
 4443                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4444                })?;
 4445                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4446                    if excerpted_buffer == *buffer {
 4447                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4448                            let excerpt_range = excerpt_range.to_offset(buffer);
 4449                            buffer
 4450                                .edited_ranges_for_transaction::<usize>(transaction)
 4451                                .all(|range| {
 4452                                    excerpt_range.start <= range.start
 4453                                        && excerpt_range.end >= range.end
 4454                                })
 4455                        })?;
 4456
 4457                        if all_edits_within_excerpt {
 4458                            return Ok(());
 4459                        }
 4460                    }
 4461                }
 4462            }
 4463        } else {
 4464            return Ok(());
 4465        }
 4466
 4467        let mut ranges_to_highlight = Vec::new();
 4468        let excerpt_buffer = cx.new(|cx| {
 4469            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4470            for (buffer_handle, transaction) in &entries {
 4471                let buffer = buffer_handle.read(cx);
 4472                ranges_to_highlight.extend(
 4473                    multibuffer.push_excerpts_with_context_lines(
 4474                        buffer_handle.clone(),
 4475                        buffer
 4476                            .edited_ranges_for_transaction::<usize>(transaction)
 4477                            .collect(),
 4478                        DEFAULT_MULTIBUFFER_CONTEXT,
 4479                        cx,
 4480                    ),
 4481                );
 4482            }
 4483            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4484            multibuffer
 4485        })?;
 4486
 4487        workspace.update_in(&mut cx, |workspace, window, cx| {
 4488            let project = workspace.project().clone();
 4489            let editor = cx
 4490                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4491            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4492            editor.update(cx, |editor, cx| {
 4493                editor.highlight_background::<Self>(
 4494                    &ranges_to_highlight,
 4495                    |theme| theme.editor_highlighted_line_background,
 4496                    cx,
 4497                );
 4498            });
 4499        })?;
 4500
 4501        Ok(())
 4502    }
 4503
 4504    pub fn clear_code_action_providers(&mut self) {
 4505        self.code_action_providers.clear();
 4506        self.available_code_actions.take();
 4507    }
 4508
 4509    pub fn add_code_action_provider(
 4510        &mut self,
 4511        provider: Rc<dyn CodeActionProvider>,
 4512        window: &mut Window,
 4513        cx: &mut Context<Self>,
 4514    ) {
 4515        if self
 4516            .code_action_providers
 4517            .iter()
 4518            .any(|existing_provider| existing_provider.id() == provider.id())
 4519        {
 4520            return;
 4521        }
 4522
 4523        self.code_action_providers.push(provider);
 4524        self.refresh_code_actions(window, cx);
 4525    }
 4526
 4527    pub fn remove_code_action_provider(
 4528        &mut self,
 4529        id: Arc<str>,
 4530        window: &mut Window,
 4531        cx: &mut Context<Self>,
 4532    ) {
 4533        self.code_action_providers
 4534            .retain(|provider| provider.id() != id);
 4535        self.refresh_code_actions(window, cx);
 4536    }
 4537
 4538    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4539        let buffer = self.buffer.read(cx);
 4540        let newest_selection = self.selections.newest_anchor().clone();
 4541        if newest_selection.head().diff_base_anchor.is_some() {
 4542            return None;
 4543        }
 4544        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4545        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4546        if start_buffer != end_buffer {
 4547            return None;
 4548        }
 4549
 4550        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4551            cx.background_executor()
 4552                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4553                .await;
 4554
 4555            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4556                let providers = this.code_action_providers.clone();
 4557                let tasks = this
 4558                    .code_action_providers
 4559                    .iter()
 4560                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4561                    .collect::<Vec<_>>();
 4562                (providers, tasks)
 4563            })?;
 4564
 4565            let mut actions = Vec::new();
 4566            for (provider, provider_actions) in
 4567                providers.into_iter().zip(future::join_all(tasks).await)
 4568            {
 4569                if let Some(provider_actions) = provider_actions.log_err() {
 4570                    actions.extend(provider_actions.into_iter().map(|action| {
 4571                        AvailableCodeAction {
 4572                            excerpt_id: newest_selection.start.excerpt_id,
 4573                            action,
 4574                            provider: provider.clone(),
 4575                        }
 4576                    }));
 4577                }
 4578            }
 4579
 4580            this.update(&mut cx, |this, cx| {
 4581                this.available_code_actions = if actions.is_empty() {
 4582                    None
 4583                } else {
 4584                    Some((
 4585                        Location {
 4586                            buffer: start_buffer,
 4587                            range: start..end,
 4588                        },
 4589                        actions.into(),
 4590                    ))
 4591                };
 4592                cx.notify();
 4593            })
 4594        }));
 4595        None
 4596    }
 4597
 4598    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4599        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4600            self.show_git_blame_inline = false;
 4601
 4602            self.show_git_blame_inline_delay_task =
 4603                Some(cx.spawn_in(window, |this, mut cx| async move {
 4604                    cx.background_executor().timer(delay).await;
 4605
 4606                    this.update(&mut cx, |this, cx| {
 4607                        this.show_git_blame_inline = true;
 4608                        cx.notify();
 4609                    })
 4610                    .log_err();
 4611                }));
 4612        }
 4613    }
 4614
 4615    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4616        if self.pending_rename.is_some() {
 4617            return None;
 4618        }
 4619
 4620        let provider = self.semantics_provider.clone()?;
 4621        let buffer = self.buffer.read(cx);
 4622        let newest_selection = self.selections.newest_anchor().clone();
 4623        let cursor_position = newest_selection.head();
 4624        let (cursor_buffer, cursor_buffer_position) =
 4625            buffer.text_anchor_for_position(cursor_position, cx)?;
 4626        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4627        if cursor_buffer != tail_buffer {
 4628            return None;
 4629        }
 4630        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4631        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4632            cx.background_executor()
 4633                .timer(Duration::from_millis(debounce))
 4634                .await;
 4635
 4636            let highlights = if let Some(highlights) = cx
 4637                .update(|cx| {
 4638                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4639                })
 4640                .ok()
 4641                .flatten()
 4642            {
 4643                highlights.await.log_err()
 4644            } else {
 4645                None
 4646            };
 4647
 4648            if let Some(highlights) = highlights {
 4649                this.update(&mut cx, |this, cx| {
 4650                    if this.pending_rename.is_some() {
 4651                        return;
 4652                    }
 4653
 4654                    let buffer_id = cursor_position.buffer_id;
 4655                    let buffer = this.buffer.read(cx);
 4656                    if !buffer
 4657                        .text_anchor_for_position(cursor_position, cx)
 4658                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4659                    {
 4660                        return;
 4661                    }
 4662
 4663                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4664                    let mut write_ranges = Vec::new();
 4665                    let mut read_ranges = Vec::new();
 4666                    for highlight in highlights {
 4667                        for (excerpt_id, excerpt_range) in
 4668                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4669                        {
 4670                            let start = highlight
 4671                                .range
 4672                                .start
 4673                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4674                            let end = highlight
 4675                                .range
 4676                                .end
 4677                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4678                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4679                                continue;
 4680                            }
 4681
 4682                            let range = Anchor {
 4683                                buffer_id,
 4684                                excerpt_id,
 4685                                text_anchor: start,
 4686                                diff_base_anchor: None,
 4687                            }..Anchor {
 4688                                buffer_id,
 4689                                excerpt_id,
 4690                                text_anchor: end,
 4691                                diff_base_anchor: None,
 4692                            };
 4693                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4694                                write_ranges.push(range);
 4695                            } else {
 4696                                read_ranges.push(range);
 4697                            }
 4698                        }
 4699                    }
 4700
 4701                    this.highlight_background::<DocumentHighlightRead>(
 4702                        &read_ranges,
 4703                        |theme| theme.editor_document_highlight_read_background,
 4704                        cx,
 4705                    );
 4706                    this.highlight_background::<DocumentHighlightWrite>(
 4707                        &write_ranges,
 4708                        |theme| theme.editor_document_highlight_write_background,
 4709                        cx,
 4710                    );
 4711                    cx.notify();
 4712                })
 4713                .log_err();
 4714            }
 4715        }));
 4716        None
 4717    }
 4718
 4719    pub fn refresh_inline_completion(
 4720        &mut self,
 4721        debounce: bool,
 4722        user_requested: bool,
 4723        window: &mut Window,
 4724        cx: &mut Context<Self>,
 4725    ) -> Option<()> {
 4726        let provider = self.edit_prediction_provider()?;
 4727        let cursor = self.selections.newest_anchor().head();
 4728        let (buffer, cursor_buffer_position) =
 4729            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4730
 4731        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4732            self.discard_inline_completion(false, cx);
 4733            return None;
 4734        }
 4735
 4736        if !user_requested
 4737            && (!self.should_show_edit_predictions()
 4738                || !self.is_focused(window)
 4739                || buffer.read(cx).is_empty())
 4740        {
 4741            self.discard_inline_completion(false, cx);
 4742            return None;
 4743        }
 4744
 4745        self.update_visible_inline_completion(window, cx);
 4746        provider.refresh(
 4747            self.project.clone(),
 4748            buffer,
 4749            cursor_buffer_position,
 4750            debounce,
 4751            cx,
 4752        );
 4753        Some(())
 4754    }
 4755
 4756    fn show_edit_predictions_in_menu(&self) -> bool {
 4757        match self.edit_prediction_settings {
 4758            EditPredictionSettings::Disabled => false,
 4759            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4760        }
 4761    }
 4762
 4763    pub fn edit_predictions_enabled(&self) -> bool {
 4764        match self.edit_prediction_settings {
 4765            EditPredictionSettings::Disabled => false,
 4766            EditPredictionSettings::Enabled { .. } => true,
 4767        }
 4768    }
 4769
 4770    fn edit_prediction_requires_modifier(&self) -> bool {
 4771        match self.edit_prediction_settings {
 4772            EditPredictionSettings::Disabled => false,
 4773            EditPredictionSettings::Enabled {
 4774                preview_requires_modifier,
 4775                ..
 4776            } => preview_requires_modifier,
 4777        }
 4778    }
 4779
 4780    fn edit_prediction_settings_at_position(
 4781        &self,
 4782        buffer: &Entity<Buffer>,
 4783        buffer_position: language::Anchor,
 4784        cx: &App,
 4785    ) -> EditPredictionSettings {
 4786        if self.mode != EditorMode::Full
 4787            || !self.show_inline_completions_override.unwrap_or(true)
 4788            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4789        {
 4790            return EditPredictionSettings::Disabled;
 4791        }
 4792
 4793        let buffer = buffer.read(cx);
 4794
 4795        let file = buffer.file();
 4796
 4797        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4798            return EditPredictionSettings::Disabled;
 4799        };
 4800
 4801        let by_provider = matches!(
 4802            self.menu_inline_completions_policy,
 4803            MenuInlineCompletionsPolicy::ByProvider
 4804        );
 4805
 4806        let show_in_menu = by_provider
 4807            && self
 4808                .edit_prediction_provider
 4809                .as_ref()
 4810                .map_or(false, |provider| {
 4811                    provider.provider.show_completions_in_menu()
 4812                });
 4813
 4814        let preview_requires_modifier =
 4815            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4816
 4817        EditPredictionSettings::Enabled {
 4818            show_in_menu,
 4819            preview_requires_modifier,
 4820        }
 4821    }
 4822
 4823    fn should_show_edit_predictions(&self) -> bool {
 4824        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4825    }
 4826
 4827    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4828        matches!(
 4829            self.edit_prediction_preview,
 4830            EditPredictionPreview::Active { .. }
 4831        )
 4832    }
 4833
 4834    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4835        let cursor = self.selections.newest_anchor().head();
 4836        if let Some((buffer, cursor_position)) =
 4837            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4838        {
 4839            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4840        } else {
 4841            false
 4842        }
 4843    }
 4844
 4845    fn inline_completions_enabled_in_buffer(
 4846        &self,
 4847        buffer: &Entity<Buffer>,
 4848        buffer_position: language::Anchor,
 4849        cx: &App,
 4850    ) -> bool {
 4851        maybe!({
 4852            let provider = self.edit_prediction_provider()?;
 4853            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4854                return Some(false);
 4855            }
 4856            let buffer = buffer.read(cx);
 4857            let Some(file) = buffer.file() else {
 4858                return Some(true);
 4859            };
 4860            let settings = all_language_settings(Some(file), cx);
 4861            Some(settings.inline_completions_enabled_for_path(file.path()))
 4862        })
 4863        .unwrap_or(false)
 4864    }
 4865
 4866    fn cycle_inline_completion(
 4867        &mut self,
 4868        direction: Direction,
 4869        window: &mut Window,
 4870        cx: &mut Context<Self>,
 4871    ) -> Option<()> {
 4872        let provider = self.edit_prediction_provider()?;
 4873        let cursor = self.selections.newest_anchor().head();
 4874        let (buffer, cursor_buffer_position) =
 4875            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4876        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4877            return None;
 4878        }
 4879
 4880        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4881        self.update_visible_inline_completion(window, cx);
 4882
 4883        Some(())
 4884    }
 4885
 4886    pub fn show_inline_completion(
 4887        &mut self,
 4888        _: &ShowEditPrediction,
 4889        window: &mut Window,
 4890        cx: &mut Context<Self>,
 4891    ) {
 4892        if !self.has_active_inline_completion() {
 4893            self.refresh_inline_completion(false, true, window, cx);
 4894            return;
 4895        }
 4896
 4897        self.update_visible_inline_completion(window, cx);
 4898    }
 4899
 4900    pub fn display_cursor_names(
 4901        &mut self,
 4902        _: &DisplayCursorNames,
 4903        window: &mut Window,
 4904        cx: &mut Context<Self>,
 4905    ) {
 4906        self.show_cursor_names(window, cx);
 4907    }
 4908
 4909    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4910        self.show_cursor_names = true;
 4911        cx.notify();
 4912        cx.spawn_in(window, |this, mut cx| async move {
 4913            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4914            this.update(&mut cx, |this, cx| {
 4915                this.show_cursor_names = false;
 4916                cx.notify()
 4917            })
 4918            .ok()
 4919        })
 4920        .detach();
 4921    }
 4922
 4923    pub fn next_edit_prediction(
 4924        &mut self,
 4925        _: &NextEditPrediction,
 4926        window: &mut Window,
 4927        cx: &mut Context<Self>,
 4928    ) {
 4929        if self.has_active_inline_completion() {
 4930            self.cycle_inline_completion(Direction::Next, window, cx);
 4931        } else {
 4932            let is_copilot_disabled = self
 4933                .refresh_inline_completion(false, true, window, cx)
 4934                .is_none();
 4935            if is_copilot_disabled {
 4936                cx.propagate();
 4937            }
 4938        }
 4939    }
 4940
 4941    pub fn previous_edit_prediction(
 4942        &mut self,
 4943        _: &PreviousEditPrediction,
 4944        window: &mut Window,
 4945        cx: &mut Context<Self>,
 4946    ) {
 4947        if self.has_active_inline_completion() {
 4948            self.cycle_inline_completion(Direction::Prev, window, cx);
 4949        } else {
 4950            let is_copilot_disabled = self
 4951                .refresh_inline_completion(false, true, window, cx)
 4952                .is_none();
 4953            if is_copilot_disabled {
 4954                cx.propagate();
 4955            }
 4956        }
 4957    }
 4958
 4959    pub fn accept_edit_prediction(
 4960        &mut self,
 4961        _: &AcceptEditPrediction,
 4962        window: &mut Window,
 4963        cx: &mut Context<Self>,
 4964    ) {
 4965        if self.show_edit_predictions_in_menu() {
 4966            self.hide_context_menu(window, cx);
 4967        }
 4968
 4969        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4970            return;
 4971        };
 4972
 4973        self.report_inline_completion_event(
 4974            active_inline_completion.completion_id.clone(),
 4975            true,
 4976            cx,
 4977        );
 4978
 4979        match &active_inline_completion.completion {
 4980            InlineCompletion::Move { target, .. } => {
 4981                let target = *target;
 4982
 4983                if let Some(position_map) = &self.last_position_map {
 4984                    if position_map
 4985                        .visible_row_range
 4986                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4987                        || !self.edit_prediction_requires_modifier()
 4988                    {
 4989                        self.unfold_ranges(&[target..target], true, false, cx);
 4990                        // Note that this is also done in vim's handler of the Tab action.
 4991                        self.change_selections(
 4992                            Some(Autoscroll::newest()),
 4993                            window,
 4994                            cx,
 4995                            |selections| {
 4996                                selections.select_anchor_ranges([target..target]);
 4997                            },
 4998                        );
 4999                        self.clear_row_highlights::<EditPredictionPreview>();
 5000
 5001                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5002                            previous_scroll_position: None,
 5003                        };
 5004                    } else {
 5005                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5006                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5007                        };
 5008                        self.highlight_rows::<EditPredictionPreview>(
 5009                            target..target,
 5010                            cx.theme().colors().editor_highlighted_line_background,
 5011                            true,
 5012                            cx,
 5013                        );
 5014                        self.request_autoscroll(Autoscroll::fit(), cx);
 5015                    }
 5016                }
 5017            }
 5018            InlineCompletion::Edit { edits, .. } => {
 5019                if let Some(provider) = self.edit_prediction_provider() {
 5020                    provider.accept(cx);
 5021                }
 5022
 5023                let snapshot = self.buffer.read(cx).snapshot(cx);
 5024                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5025
 5026                self.buffer.update(cx, |buffer, cx| {
 5027                    buffer.edit(edits.iter().cloned(), None, cx)
 5028                });
 5029
 5030                self.change_selections(None, window, cx, |s| {
 5031                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5032                });
 5033
 5034                self.update_visible_inline_completion(window, cx);
 5035                if self.active_inline_completion.is_none() {
 5036                    self.refresh_inline_completion(true, true, window, cx);
 5037                }
 5038
 5039                cx.notify();
 5040            }
 5041        }
 5042
 5043        self.edit_prediction_requires_modifier_in_leading_space = false;
 5044    }
 5045
 5046    pub fn accept_partial_inline_completion(
 5047        &mut self,
 5048        _: &AcceptPartialEditPrediction,
 5049        window: &mut Window,
 5050        cx: &mut Context<Self>,
 5051    ) {
 5052        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5053            return;
 5054        };
 5055        if self.selections.count() != 1 {
 5056            return;
 5057        }
 5058
 5059        self.report_inline_completion_event(
 5060            active_inline_completion.completion_id.clone(),
 5061            true,
 5062            cx,
 5063        );
 5064
 5065        match &active_inline_completion.completion {
 5066            InlineCompletion::Move { target, .. } => {
 5067                let target = *target;
 5068                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5069                    selections.select_anchor_ranges([target..target]);
 5070                });
 5071            }
 5072            InlineCompletion::Edit { edits, .. } => {
 5073                // Find an insertion that starts at the cursor position.
 5074                let snapshot = self.buffer.read(cx).snapshot(cx);
 5075                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5076                let insertion = edits.iter().find_map(|(range, text)| {
 5077                    let range = range.to_offset(&snapshot);
 5078                    if range.is_empty() && range.start == cursor_offset {
 5079                        Some(text)
 5080                    } else {
 5081                        None
 5082                    }
 5083                });
 5084
 5085                if let Some(text) = insertion {
 5086                    let mut partial_completion = text
 5087                        .chars()
 5088                        .by_ref()
 5089                        .take_while(|c| c.is_alphabetic())
 5090                        .collect::<String>();
 5091                    if partial_completion.is_empty() {
 5092                        partial_completion = text
 5093                            .chars()
 5094                            .by_ref()
 5095                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5096                            .collect::<String>();
 5097                    }
 5098
 5099                    cx.emit(EditorEvent::InputHandled {
 5100                        utf16_range_to_replace: None,
 5101                        text: partial_completion.clone().into(),
 5102                    });
 5103
 5104                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5105
 5106                    self.refresh_inline_completion(true, true, window, cx);
 5107                    cx.notify();
 5108                } else {
 5109                    self.accept_edit_prediction(&Default::default(), window, cx);
 5110                }
 5111            }
 5112        }
 5113    }
 5114
 5115    fn discard_inline_completion(
 5116        &mut self,
 5117        should_report_inline_completion_event: bool,
 5118        cx: &mut Context<Self>,
 5119    ) -> bool {
 5120        if should_report_inline_completion_event {
 5121            let completion_id = self
 5122                .active_inline_completion
 5123                .as_ref()
 5124                .and_then(|active_completion| active_completion.completion_id.clone());
 5125
 5126            self.report_inline_completion_event(completion_id, false, cx);
 5127        }
 5128
 5129        if let Some(provider) = self.edit_prediction_provider() {
 5130            provider.discard(cx);
 5131        }
 5132
 5133        self.take_active_inline_completion(cx)
 5134    }
 5135
 5136    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5137        let Some(provider) = self.edit_prediction_provider() else {
 5138            return;
 5139        };
 5140
 5141        let Some((_, buffer, _)) = self
 5142            .buffer
 5143            .read(cx)
 5144            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5145        else {
 5146            return;
 5147        };
 5148
 5149        let extension = buffer
 5150            .read(cx)
 5151            .file()
 5152            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5153
 5154        let event_type = match accepted {
 5155            true => "Edit Prediction Accepted",
 5156            false => "Edit Prediction Discarded",
 5157        };
 5158        telemetry::event!(
 5159            event_type,
 5160            provider = provider.name(),
 5161            prediction_id = id,
 5162            suggestion_accepted = accepted,
 5163            file_extension = extension,
 5164        );
 5165    }
 5166
 5167    pub fn has_active_inline_completion(&self) -> bool {
 5168        self.active_inline_completion.is_some()
 5169    }
 5170
 5171    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5172        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5173            return false;
 5174        };
 5175
 5176        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5177        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5178        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5179        true
 5180    }
 5181
 5182    /// Returns true when we're displaying the edit prediction popover below the cursor
 5183    /// like we are not previewing and the LSP autocomplete menu is visible
 5184    /// or we are in `when_holding_modifier` mode.
 5185    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5186        if self.edit_prediction_preview_is_active()
 5187            || !self.show_edit_predictions_in_menu()
 5188            || !self.edit_predictions_enabled()
 5189        {
 5190            return false;
 5191        }
 5192
 5193        if self.has_visible_completions_menu() {
 5194            return true;
 5195        }
 5196
 5197        has_completion && self.edit_prediction_requires_modifier()
 5198    }
 5199
 5200    fn handle_modifiers_changed(
 5201        &mut self,
 5202        modifiers: Modifiers,
 5203        position_map: &PositionMap,
 5204        window: &mut Window,
 5205        cx: &mut Context<Self>,
 5206    ) {
 5207        if self.show_edit_predictions_in_menu() {
 5208            self.update_edit_prediction_preview(&modifiers, window, cx);
 5209        }
 5210
 5211        let mouse_position = window.mouse_position();
 5212        if !position_map.text_hitbox.is_hovered(window) {
 5213            return;
 5214        }
 5215
 5216        self.update_hovered_link(
 5217            position_map.point_for_position(mouse_position),
 5218            &position_map.snapshot,
 5219            modifiers,
 5220            window,
 5221            cx,
 5222        )
 5223    }
 5224
 5225    fn update_edit_prediction_preview(
 5226        &mut self,
 5227        modifiers: &Modifiers,
 5228        window: &mut Window,
 5229        cx: &mut Context<Self>,
 5230    ) {
 5231        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5232        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5233            return;
 5234        };
 5235
 5236        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5237            if matches!(
 5238                self.edit_prediction_preview,
 5239                EditPredictionPreview::Inactive
 5240            ) {
 5241                self.edit_prediction_preview = EditPredictionPreview::Active {
 5242                    previous_scroll_position: None,
 5243                };
 5244
 5245                self.update_visible_inline_completion(window, cx);
 5246                cx.notify();
 5247            }
 5248        } else if let EditPredictionPreview::Active {
 5249            previous_scroll_position,
 5250        } = self.edit_prediction_preview
 5251        {
 5252            if let (Some(previous_scroll_position), Some(position_map)) =
 5253                (previous_scroll_position, self.last_position_map.as_ref())
 5254            {
 5255                self.set_scroll_position(
 5256                    previous_scroll_position
 5257                        .scroll_position(&position_map.snapshot.display_snapshot),
 5258                    window,
 5259                    cx,
 5260                );
 5261            }
 5262
 5263            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5264            self.clear_row_highlights::<EditPredictionPreview>();
 5265            self.update_visible_inline_completion(window, cx);
 5266            cx.notify();
 5267        }
 5268    }
 5269
 5270    fn update_visible_inline_completion(
 5271        &mut self,
 5272        _window: &mut Window,
 5273        cx: &mut Context<Self>,
 5274    ) -> Option<()> {
 5275        let selection = self.selections.newest_anchor();
 5276        let cursor = selection.head();
 5277        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5278        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5279        let excerpt_id = cursor.excerpt_id;
 5280
 5281        let show_in_menu = self.show_edit_predictions_in_menu();
 5282        let completions_menu_has_precedence = !show_in_menu
 5283            && (self.context_menu.borrow().is_some()
 5284                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5285
 5286        if completions_menu_has_precedence
 5287            || !offset_selection.is_empty()
 5288            || self
 5289                .active_inline_completion
 5290                .as_ref()
 5291                .map_or(false, |completion| {
 5292                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5293                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5294                    !invalidation_range.contains(&offset_selection.head())
 5295                })
 5296        {
 5297            self.discard_inline_completion(false, cx);
 5298            return None;
 5299        }
 5300
 5301        self.take_active_inline_completion(cx);
 5302        let Some(provider) = self.edit_prediction_provider() else {
 5303            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5304            return None;
 5305        };
 5306
 5307        let (buffer, cursor_buffer_position) =
 5308            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5309
 5310        self.edit_prediction_settings =
 5311            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5312
 5313        self.edit_prediction_cursor_on_leading_whitespace =
 5314            multibuffer.is_line_whitespace_upto(cursor);
 5315
 5316        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5317        let edits = inline_completion
 5318            .edits
 5319            .into_iter()
 5320            .flat_map(|(range, new_text)| {
 5321                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5322                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5323                Some((start..end, new_text))
 5324            })
 5325            .collect::<Vec<_>>();
 5326        if edits.is_empty() {
 5327            return None;
 5328        }
 5329
 5330        let first_edit_start = edits.first().unwrap().0.start;
 5331        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5332        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5333
 5334        let last_edit_end = edits.last().unwrap().0.end;
 5335        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5336        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5337
 5338        let cursor_row = cursor.to_point(&multibuffer).row;
 5339
 5340        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5341
 5342        let mut inlay_ids = Vec::new();
 5343        let invalidation_row_range;
 5344        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5345            Some(cursor_row..edit_end_row)
 5346        } else if cursor_row > edit_end_row {
 5347            Some(edit_start_row..cursor_row)
 5348        } else {
 5349            None
 5350        };
 5351        let is_move =
 5352            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5353        let completion = if is_move {
 5354            invalidation_row_range =
 5355                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5356            let target = first_edit_start;
 5357            InlineCompletion::Move { target, snapshot }
 5358        } else {
 5359            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5360                && !self.inline_completions_hidden_for_vim_mode;
 5361
 5362            if show_completions_in_buffer {
 5363                if edits
 5364                    .iter()
 5365                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5366                {
 5367                    let mut inlays = Vec::new();
 5368                    for (range, new_text) in &edits {
 5369                        let inlay = Inlay::inline_completion(
 5370                            post_inc(&mut self.next_inlay_id),
 5371                            range.start,
 5372                            new_text.as_str(),
 5373                        );
 5374                        inlay_ids.push(inlay.id);
 5375                        inlays.push(inlay);
 5376                    }
 5377
 5378                    self.splice_inlays(&[], inlays, cx);
 5379                } else {
 5380                    let background_color = cx.theme().status().deleted_background;
 5381                    self.highlight_text::<InlineCompletionHighlight>(
 5382                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5383                        HighlightStyle {
 5384                            background_color: Some(background_color),
 5385                            ..Default::default()
 5386                        },
 5387                        cx,
 5388                    );
 5389                }
 5390            }
 5391
 5392            invalidation_row_range = edit_start_row..edit_end_row;
 5393
 5394            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5395                if provider.show_tab_accept_marker() {
 5396                    EditDisplayMode::TabAccept
 5397                } else {
 5398                    EditDisplayMode::Inline
 5399                }
 5400            } else {
 5401                EditDisplayMode::DiffPopover
 5402            };
 5403
 5404            InlineCompletion::Edit {
 5405                edits,
 5406                edit_preview: inline_completion.edit_preview,
 5407                display_mode,
 5408                snapshot,
 5409            }
 5410        };
 5411
 5412        let invalidation_range = multibuffer
 5413            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5414            ..multibuffer.anchor_after(Point::new(
 5415                invalidation_row_range.end,
 5416                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5417            ));
 5418
 5419        self.stale_inline_completion_in_menu = None;
 5420        self.active_inline_completion = Some(InlineCompletionState {
 5421            inlay_ids,
 5422            completion,
 5423            completion_id: inline_completion.id,
 5424            invalidation_range,
 5425        });
 5426
 5427        cx.notify();
 5428
 5429        Some(())
 5430    }
 5431
 5432    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5433        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5434    }
 5435
 5436    fn render_code_actions_indicator(
 5437        &self,
 5438        _style: &EditorStyle,
 5439        row: DisplayRow,
 5440        is_active: bool,
 5441        cx: &mut Context<Self>,
 5442    ) -> Option<IconButton> {
 5443        if self.available_code_actions.is_some() {
 5444            Some(
 5445                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5446                    .shape(ui::IconButtonShape::Square)
 5447                    .icon_size(IconSize::XSmall)
 5448                    .icon_color(Color::Muted)
 5449                    .toggle_state(is_active)
 5450                    .tooltip({
 5451                        let focus_handle = self.focus_handle.clone();
 5452                        move |window, cx| {
 5453                            Tooltip::for_action_in(
 5454                                "Toggle Code Actions",
 5455                                &ToggleCodeActions {
 5456                                    deployed_from_indicator: None,
 5457                                },
 5458                                &focus_handle,
 5459                                window,
 5460                                cx,
 5461                            )
 5462                        }
 5463                    })
 5464                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5465                        window.focus(&editor.focus_handle(cx));
 5466                        editor.toggle_code_actions(
 5467                            &ToggleCodeActions {
 5468                                deployed_from_indicator: Some(row),
 5469                            },
 5470                            window,
 5471                            cx,
 5472                        );
 5473                    })),
 5474            )
 5475        } else {
 5476            None
 5477        }
 5478    }
 5479
 5480    fn clear_tasks(&mut self) {
 5481        self.tasks.clear()
 5482    }
 5483
 5484    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5485        if self.tasks.insert(key, value).is_some() {
 5486            // This case should hopefully be rare, but just in case...
 5487            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5488        }
 5489    }
 5490
 5491    fn build_tasks_context(
 5492        project: &Entity<Project>,
 5493        buffer: &Entity<Buffer>,
 5494        buffer_row: u32,
 5495        tasks: &Arc<RunnableTasks>,
 5496        cx: &mut Context<Self>,
 5497    ) -> Task<Option<task::TaskContext>> {
 5498        let position = Point::new(buffer_row, tasks.column);
 5499        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5500        let location = Location {
 5501            buffer: buffer.clone(),
 5502            range: range_start..range_start,
 5503        };
 5504        // Fill in the environmental variables from the tree-sitter captures
 5505        let mut captured_task_variables = TaskVariables::default();
 5506        for (capture_name, value) in tasks.extra_variables.clone() {
 5507            captured_task_variables.insert(
 5508                task::VariableName::Custom(capture_name.into()),
 5509                value.clone(),
 5510            );
 5511        }
 5512        project.update(cx, |project, cx| {
 5513            project.task_store().update(cx, |task_store, cx| {
 5514                task_store.task_context_for_location(captured_task_variables, location, cx)
 5515            })
 5516        })
 5517    }
 5518
 5519    pub fn spawn_nearest_task(
 5520        &mut self,
 5521        action: &SpawnNearestTask,
 5522        window: &mut Window,
 5523        cx: &mut Context<Self>,
 5524    ) {
 5525        let Some((workspace, _)) = self.workspace.clone() else {
 5526            return;
 5527        };
 5528        let Some(project) = self.project.clone() else {
 5529            return;
 5530        };
 5531
 5532        // Try to find a closest, enclosing node using tree-sitter that has a
 5533        // task
 5534        let Some((buffer, buffer_row, tasks)) = self
 5535            .find_enclosing_node_task(cx)
 5536            // Or find the task that's closest in row-distance.
 5537            .or_else(|| self.find_closest_task(cx))
 5538        else {
 5539            return;
 5540        };
 5541
 5542        let reveal_strategy = action.reveal;
 5543        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5544        cx.spawn_in(window, |_, mut cx| async move {
 5545            let context = task_context.await?;
 5546            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5547
 5548            let resolved = resolved_task.resolved.as_mut()?;
 5549            resolved.reveal = reveal_strategy;
 5550
 5551            workspace
 5552                .update(&mut cx, |workspace, cx| {
 5553                    workspace::tasks::schedule_resolved_task(
 5554                        workspace,
 5555                        task_source_kind,
 5556                        resolved_task,
 5557                        false,
 5558                        cx,
 5559                    );
 5560                })
 5561                .ok()
 5562        })
 5563        .detach();
 5564    }
 5565
 5566    fn find_closest_task(
 5567        &mut self,
 5568        cx: &mut Context<Self>,
 5569    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5570        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5571
 5572        let ((buffer_id, row), tasks) = self
 5573            .tasks
 5574            .iter()
 5575            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5576
 5577        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5578        let tasks = Arc::new(tasks.to_owned());
 5579        Some((buffer, *row, tasks))
 5580    }
 5581
 5582    fn find_enclosing_node_task(
 5583        &mut self,
 5584        cx: &mut Context<Self>,
 5585    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5586        let snapshot = self.buffer.read(cx).snapshot(cx);
 5587        let offset = self.selections.newest::<usize>(cx).head();
 5588        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5589        let buffer_id = excerpt.buffer().remote_id();
 5590
 5591        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5592        let mut cursor = layer.node().walk();
 5593
 5594        while cursor.goto_first_child_for_byte(offset).is_some() {
 5595            if cursor.node().end_byte() == offset {
 5596                cursor.goto_next_sibling();
 5597            }
 5598        }
 5599
 5600        // Ascend to the smallest ancestor that contains the range and has a task.
 5601        loop {
 5602            let node = cursor.node();
 5603            let node_range = node.byte_range();
 5604            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5605
 5606            // Check if this node contains our offset
 5607            if node_range.start <= offset && node_range.end >= offset {
 5608                // If it contains offset, check for task
 5609                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5610                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5611                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5612                }
 5613            }
 5614
 5615            if !cursor.goto_parent() {
 5616                break;
 5617            }
 5618        }
 5619        None
 5620    }
 5621
 5622    fn render_run_indicator(
 5623        &self,
 5624        _style: &EditorStyle,
 5625        is_active: bool,
 5626        row: DisplayRow,
 5627        cx: &mut Context<Self>,
 5628    ) -> IconButton {
 5629        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5630            .shape(ui::IconButtonShape::Square)
 5631            .icon_size(IconSize::XSmall)
 5632            .icon_color(Color::Muted)
 5633            .toggle_state(is_active)
 5634            .on_click(cx.listener(move |editor, _e, window, cx| {
 5635                window.focus(&editor.focus_handle(cx));
 5636                editor.toggle_code_actions(
 5637                    &ToggleCodeActions {
 5638                        deployed_from_indicator: Some(row),
 5639                    },
 5640                    window,
 5641                    cx,
 5642                );
 5643            }))
 5644    }
 5645
 5646    pub fn context_menu_visible(&self) -> bool {
 5647        !self.edit_prediction_preview_is_active()
 5648            && self
 5649                .context_menu
 5650                .borrow()
 5651                .as_ref()
 5652                .map_or(false, |menu| menu.visible())
 5653    }
 5654
 5655    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5656        self.context_menu
 5657            .borrow()
 5658            .as_ref()
 5659            .map(|menu| menu.origin())
 5660    }
 5661
 5662    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5663        px(30.)
 5664    }
 5665
 5666    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5667        if self.read_only(cx) {
 5668            cx.theme().players().read_only()
 5669        } else {
 5670            self.style.as_ref().unwrap().local_player
 5671        }
 5672    }
 5673
 5674    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5675        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5676        let accept_keystroke = accept_binding.keystroke()?;
 5677
 5678        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5679
 5680        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5681            Color::Accent
 5682        } else {
 5683            Color::Muted
 5684        };
 5685
 5686        h_flex()
 5687            .px_0p5()
 5688            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5689            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5690            .text_size(TextSize::XSmall.rems(cx))
 5691            .child(h_flex().children(ui::render_modifiers(
 5692                &accept_keystroke.modifiers,
 5693                PlatformStyle::platform(),
 5694                Some(modifiers_color),
 5695                Some(IconSize::XSmall.rems().into()),
 5696                true,
 5697            )))
 5698            .when(is_platform_style_mac, |parent| {
 5699                parent.child(accept_keystroke.key.clone())
 5700            })
 5701            .when(!is_platform_style_mac, |parent| {
 5702                parent.child(
 5703                    Key::new(
 5704                        util::capitalize(&accept_keystroke.key),
 5705                        Some(Color::Default),
 5706                    )
 5707                    .size(Some(IconSize::XSmall.rems().into())),
 5708                )
 5709            })
 5710            .into()
 5711    }
 5712
 5713    fn render_edit_prediction_line_popover(
 5714        &self,
 5715        label: impl Into<SharedString>,
 5716        icon: Option<IconName>,
 5717        window: &mut Window,
 5718        cx: &App,
 5719    ) -> Option<Div> {
 5720        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5721
 5722        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5723
 5724        let result = h_flex()
 5725            .gap_1()
 5726            .border_1()
 5727            .rounded_lg()
 5728            .shadow_sm()
 5729            .bg(bg_color)
 5730            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5731            .py_0p5()
 5732            .pl_1()
 5733            .pr(padding_right)
 5734            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5735            .child(Label::new(label).size(LabelSize::Small))
 5736            .when_some(icon, |element, icon| {
 5737                element.child(
 5738                    div()
 5739                        .mt(px(1.5))
 5740                        .child(Icon::new(icon).size(IconSize::Small)),
 5741                )
 5742            });
 5743
 5744        Some(result)
 5745    }
 5746
 5747    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5748        let accent_color = cx.theme().colors().text_accent;
 5749        let editor_bg_color = cx.theme().colors().editor_background;
 5750        editor_bg_color.blend(accent_color.opacity(0.1))
 5751    }
 5752
 5753    #[allow(clippy::too_many_arguments)]
 5754    fn render_edit_prediction_cursor_popover(
 5755        &self,
 5756        min_width: Pixels,
 5757        max_width: Pixels,
 5758        cursor_point: Point,
 5759        style: &EditorStyle,
 5760        accept_keystroke: &gpui::Keystroke,
 5761        _window: &Window,
 5762        cx: &mut Context<Editor>,
 5763    ) -> Option<AnyElement> {
 5764        let provider = self.edit_prediction_provider.as_ref()?;
 5765
 5766        if provider.provider.needs_terms_acceptance(cx) {
 5767            return Some(
 5768                h_flex()
 5769                    .min_w(min_width)
 5770                    .flex_1()
 5771                    .px_2()
 5772                    .py_1()
 5773                    .gap_3()
 5774                    .elevation_2(cx)
 5775                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5776                    .id("accept-terms")
 5777                    .cursor_pointer()
 5778                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5779                    .on_click(cx.listener(|this, _event, window, cx| {
 5780                        cx.stop_propagation();
 5781                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5782                        window.dispatch_action(
 5783                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5784                            cx,
 5785                        );
 5786                    }))
 5787                    .child(
 5788                        h_flex()
 5789                            .flex_1()
 5790                            .gap_2()
 5791                            .child(Icon::new(IconName::ZedPredict))
 5792                            .child(Label::new("Accept Terms of Service"))
 5793                            .child(div().w_full())
 5794                            .child(
 5795                                Icon::new(IconName::ArrowUpRight)
 5796                                    .color(Color::Muted)
 5797                                    .size(IconSize::Small),
 5798                            )
 5799                            .into_any_element(),
 5800                    )
 5801                    .into_any(),
 5802            );
 5803        }
 5804
 5805        let is_refreshing = provider.provider.is_refreshing(cx);
 5806
 5807        fn pending_completion_container() -> Div {
 5808            h_flex()
 5809                .h_full()
 5810                .flex_1()
 5811                .gap_2()
 5812                .child(Icon::new(IconName::ZedPredict))
 5813        }
 5814
 5815        let completion = match &self.active_inline_completion {
 5816            Some(completion) => match &completion.completion {
 5817                InlineCompletion::Move {
 5818                    target, snapshot, ..
 5819                } if !self.has_visible_completions_menu() => {
 5820                    use text::ToPoint as _;
 5821
 5822                    return Some(
 5823                        h_flex()
 5824                            .px_2()
 5825                            .py_1()
 5826                            .elevation_2(cx)
 5827                            .border_color(cx.theme().colors().border)
 5828                            .rounded_tl(px(0.))
 5829                            .gap_2()
 5830                            .child(
 5831                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5832                                    Icon::new(IconName::ZedPredictDown)
 5833                                } else {
 5834                                    Icon::new(IconName::ZedPredictUp)
 5835                                },
 5836                            )
 5837                            .child(Label::new("Hold").size(LabelSize::Small))
 5838                            .child(h_flex().children(ui::render_modifiers(
 5839                                &accept_keystroke.modifiers,
 5840                                PlatformStyle::platform(),
 5841                                Some(Color::Default),
 5842                                Some(IconSize::Small.rems().into()),
 5843                                false,
 5844                            )))
 5845                            .into_any(),
 5846                    );
 5847                }
 5848                _ => self.render_edit_prediction_cursor_popover_preview(
 5849                    completion,
 5850                    cursor_point,
 5851                    style,
 5852                    cx,
 5853                )?,
 5854            },
 5855
 5856            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5857                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5858                    stale_completion,
 5859                    cursor_point,
 5860                    style,
 5861                    cx,
 5862                )?,
 5863
 5864                None => {
 5865                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5866                }
 5867            },
 5868
 5869            None => pending_completion_container().child(Label::new("No Prediction")),
 5870        };
 5871
 5872        let completion = if is_refreshing {
 5873            completion
 5874                .with_animation(
 5875                    "loading-completion",
 5876                    Animation::new(Duration::from_secs(2))
 5877                        .repeat()
 5878                        .with_easing(pulsating_between(0.4, 0.8)),
 5879                    |label, delta| label.opacity(delta),
 5880                )
 5881                .into_any_element()
 5882        } else {
 5883            completion.into_any_element()
 5884        };
 5885
 5886        let has_completion = self.active_inline_completion.is_some();
 5887
 5888        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5889        Some(
 5890            h_flex()
 5891                .min_w(min_width)
 5892                .max_w(max_width)
 5893                .flex_1()
 5894                .elevation_2(cx)
 5895                .border_color(cx.theme().colors().border)
 5896                .child(
 5897                    div()
 5898                        .flex_1()
 5899                        .py_1()
 5900                        .px_2()
 5901                        .overflow_hidden()
 5902                        .child(completion),
 5903                )
 5904                .child(
 5905                    h_flex()
 5906                        .h_full()
 5907                        .border_l_1()
 5908                        .rounded_r_lg()
 5909                        .border_color(cx.theme().colors().border)
 5910                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5911                        .gap_1()
 5912                        .py_1()
 5913                        .px_2()
 5914                        .child(
 5915                            h_flex()
 5916                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5917                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5918                                .child(h_flex().children(ui::render_modifiers(
 5919                                    &accept_keystroke.modifiers,
 5920                                    PlatformStyle::platform(),
 5921                                    Some(if !has_completion {
 5922                                        Color::Muted
 5923                                    } else {
 5924                                        Color::Default
 5925                                    }),
 5926                                    None,
 5927                                    false,
 5928                                ))),
 5929                        )
 5930                        .child(Label::new("Preview").into_any_element())
 5931                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5932                )
 5933                .into_any(),
 5934        )
 5935    }
 5936
 5937    fn render_edit_prediction_cursor_popover_preview(
 5938        &self,
 5939        completion: &InlineCompletionState,
 5940        cursor_point: Point,
 5941        style: &EditorStyle,
 5942        cx: &mut Context<Editor>,
 5943    ) -> Option<Div> {
 5944        use text::ToPoint as _;
 5945
 5946        fn render_relative_row_jump(
 5947            prefix: impl Into<String>,
 5948            current_row: u32,
 5949            target_row: u32,
 5950        ) -> Div {
 5951            let (row_diff, arrow) = if target_row < current_row {
 5952                (current_row - target_row, IconName::ArrowUp)
 5953            } else {
 5954                (target_row - current_row, IconName::ArrowDown)
 5955            };
 5956
 5957            h_flex()
 5958                .child(
 5959                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5960                        .color(Color::Muted)
 5961                        .size(LabelSize::Small),
 5962                )
 5963                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5964        }
 5965
 5966        match &completion.completion {
 5967            InlineCompletion::Move {
 5968                target, snapshot, ..
 5969            } => Some(
 5970                h_flex()
 5971                    .px_2()
 5972                    .gap_2()
 5973                    .flex_1()
 5974                    .child(
 5975                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5976                            Icon::new(IconName::ZedPredictDown)
 5977                        } else {
 5978                            Icon::new(IconName::ZedPredictUp)
 5979                        },
 5980                    )
 5981                    .child(Label::new("Jump to Edit")),
 5982            ),
 5983
 5984            InlineCompletion::Edit {
 5985                edits,
 5986                edit_preview,
 5987                snapshot,
 5988                display_mode: _,
 5989            } => {
 5990                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5991
 5992                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 5993                    &snapshot,
 5994                    &edits,
 5995                    edit_preview.as_ref()?,
 5996                    true,
 5997                    cx,
 5998                )
 5999                .first_line_preview();
 6000
 6001                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6002                    .with_highlights(&style.text, highlighted_edits.highlights);
 6003
 6004                let preview = h_flex()
 6005                    .gap_1()
 6006                    .min_w_16()
 6007                    .child(styled_text)
 6008                    .when(has_more_lines, |parent| parent.child(""));
 6009
 6010                let left = if first_edit_row != cursor_point.row {
 6011                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6012                        .into_any_element()
 6013                } else {
 6014                    Icon::new(IconName::ZedPredict).into_any_element()
 6015                };
 6016
 6017                Some(
 6018                    h_flex()
 6019                        .h_full()
 6020                        .flex_1()
 6021                        .gap_2()
 6022                        .pr_1()
 6023                        .overflow_x_hidden()
 6024                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6025                        .child(left)
 6026                        .child(preview),
 6027                )
 6028            }
 6029        }
 6030    }
 6031
 6032    fn render_context_menu(
 6033        &self,
 6034        style: &EditorStyle,
 6035        max_height_in_lines: u32,
 6036        y_flipped: bool,
 6037        window: &mut Window,
 6038        cx: &mut Context<Editor>,
 6039    ) -> Option<AnyElement> {
 6040        let menu = self.context_menu.borrow();
 6041        let menu = menu.as_ref()?;
 6042        if !menu.visible() {
 6043            return None;
 6044        };
 6045        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6046    }
 6047
 6048    fn render_context_menu_aside(
 6049        &self,
 6050        style: &EditorStyle,
 6051        max_size: Size<Pixels>,
 6052        cx: &mut Context<Editor>,
 6053    ) -> Option<AnyElement> {
 6054        self.context_menu.borrow().as_ref().and_then(|menu| {
 6055            if menu.visible() {
 6056                menu.render_aside(
 6057                    style,
 6058                    max_size,
 6059                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6060                    cx,
 6061                )
 6062            } else {
 6063                None
 6064            }
 6065        })
 6066    }
 6067
 6068    fn hide_context_menu(
 6069        &mut self,
 6070        window: &mut Window,
 6071        cx: &mut Context<Self>,
 6072    ) -> Option<CodeContextMenu> {
 6073        cx.notify();
 6074        self.completion_tasks.clear();
 6075        let context_menu = self.context_menu.borrow_mut().take();
 6076        self.stale_inline_completion_in_menu.take();
 6077        self.update_visible_inline_completion(window, cx);
 6078        context_menu
 6079    }
 6080
 6081    fn show_snippet_choices(
 6082        &mut self,
 6083        choices: &Vec<String>,
 6084        selection: Range<Anchor>,
 6085        cx: &mut Context<Self>,
 6086    ) {
 6087        if selection.start.buffer_id.is_none() {
 6088            return;
 6089        }
 6090        let buffer_id = selection.start.buffer_id.unwrap();
 6091        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6092        let id = post_inc(&mut self.next_completion_id);
 6093
 6094        if let Some(buffer) = buffer {
 6095            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6096                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6097            ));
 6098        }
 6099    }
 6100
 6101    pub fn insert_snippet(
 6102        &mut self,
 6103        insertion_ranges: &[Range<usize>],
 6104        snippet: Snippet,
 6105        window: &mut Window,
 6106        cx: &mut Context<Self>,
 6107    ) -> Result<()> {
 6108        struct Tabstop<T> {
 6109            is_end_tabstop: bool,
 6110            ranges: Vec<Range<T>>,
 6111            choices: Option<Vec<String>>,
 6112        }
 6113
 6114        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6115            let snippet_text: Arc<str> = snippet.text.clone().into();
 6116            buffer.edit(
 6117                insertion_ranges
 6118                    .iter()
 6119                    .cloned()
 6120                    .map(|range| (range, snippet_text.clone())),
 6121                Some(AutoindentMode::EachLine),
 6122                cx,
 6123            );
 6124
 6125            let snapshot = &*buffer.read(cx);
 6126            let snippet = &snippet;
 6127            snippet
 6128                .tabstops
 6129                .iter()
 6130                .map(|tabstop| {
 6131                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6132                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6133                    });
 6134                    let mut tabstop_ranges = tabstop
 6135                        .ranges
 6136                        .iter()
 6137                        .flat_map(|tabstop_range| {
 6138                            let mut delta = 0_isize;
 6139                            insertion_ranges.iter().map(move |insertion_range| {
 6140                                let insertion_start = insertion_range.start as isize + delta;
 6141                                delta +=
 6142                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6143
 6144                                let start = ((insertion_start + tabstop_range.start) as usize)
 6145                                    .min(snapshot.len());
 6146                                let end = ((insertion_start + tabstop_range.end) as usize)
 6147                                    .min(snapshot.len());
 6148                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6149                            })
 6150                        })
 6151                        .collect::<Vec<_>>();
 6152                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6153
 6154                    Tabstop {
 6155                        is_end_tabstop,
 6156                        ranges: tabstop_ranges,
 6157                        choices: tabstop.choices.clone(),
 6158                    }
 6159                })
 6160                .collect::<Vec<_>>()
 6161        });
 6162        if let Some(tabstop) = tabstops.first() {
 6163            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6164                s.select_ranges(tabstop.ranges.iter().cloned());
 6165            });
 6166
 6167            if let Some(choices) = &tabstop.choices {
 6168                if let Some(selection) = tabstop.ranges.first() {
 6169                    self.show_snippet_choices(choices, selection.clone(), cx)
 6170                }
 6171            }
 6172
 6173            // If we're already at the last tabstop and it's at the end of the snippet,
 6174            // we're done, we don't need to keep the state around.
 6175            if !tabstop.is_end_tabstop {
 6176                let choices = tabstops
 6177                    .iter()
 6178                    .map(|tabstop| tabstop.choices.clone())
 6179                    .collect();
 6180
 6181                let ranges = tabstops
 6182                    .into_iter()
 6183                    .map(|tabstop| tabstop.ranges)
 6184                    .collect::<Vec<_>>();
 6185
 6186                self.snippet_stack.push(SnippetState {
 6187                    active_index: 0,
 6188                    ranges,
 6189                    choices,
 6190                });
 6191            }
 6192
 6193            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6194            if self.autoclose_regions.is_empty() {
 6195                let snapshot = self.buffer.read(cx).snapshot(cx);
 6196                for selection in &mut self.selections.all::<Point>(cx) {
 6197                    let selection_head = selection.head();
 6198                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6199                        continue;
 6200                    };
 6201
 6202                    let mut bracket_pair = None;
 6203                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6204                    let prev_chars = snapshot
 6205                        .reversed_chars_at(selection_head)
 6206                        .collect::<String>();
 6207                    for (pair, enabled) in scope.brackets() {
 6208                        if enabled
 6209                            && pair.close
 6210                            && prev_chars.starts_with(pair.start.as_str())
 6211                            && next_chars.starts_with(pair.end.as_str())
 6212                        {
 6213                            bracket_pair = Some(pair.clone());
 6214                            break;
 6215                        }
 6216                    }
 6217                    if let Some(pair) = bracket_pair {
 6218                        let start = snapshot.anchor_after(selection_head);
 6219                        let end = snapshot.anchor_after(selection_head);
 6220                        self.autoclose_regions.push(AutocloseRegion {
 6221                            selection_id: selection.id,
 6222                            range: start..end,
 6223                            pair,
 6224                        });
 6225                    }
 6226                }
 6227            }
 6228        }
 6229        Ok(())
 6230    }
 6231
 6232    pub fn move_to_next_snippet_tabstop(
 6233        &mut self,
 6234        window: &mut Window,
 6235        cx: &mut Context<Self>,
 6236    ) -> bool {
 6237        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6238    }
 6239
 6240    pub fn move_to_prev_snippet_tabstop(
 6241        &mut self,
 6242        window: &mut Window,
 6243        cx: &mut Context<Self>,
 6244    ) -> bool {
 6245        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6246    }
 6247
 6248    pub fn move_to_snippet_tabstop(
 6249        &mut self,
 6250        bias: Bias,
 6251        window: &mut Window,
 6252        cx: &mut Context<Self>,
 6253    ) -> bool {
 6254        if let Some(mut snippet) = self.snippet_stack.pop() {
 6255            match bias {
 6256                Bias::Left => {
 6257                    if snippet.active_index > 0 {
 6258                        snippet.active_index -= 1;
 6259                    } else {
 6260                        self.snippet_stack.push(snippet);
 6261                        return false;
 6262                    }
 6263                }
 6264                Bias::Right => {
 6265                    if snippet.active_index + 1 < snippet.ranges.len() {
 6266                        snippet.active_index += 1;
 6267                    } else {
 6268                        self.snippet_stack.push(snippet);
 6269                        return false;
 6270                    }
 6271                }
 6272            }
 6273            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6274                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6275                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6276                });
 6277
 6278                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6279                    if let Some(selection) = current_ranges.first() {
 6280                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6281                    }
 6282                }
 6283
 6284                // If snippet state is not at the last tabstop, push it back on the stack
 6285                if snippet.active_index + 1 < snippet.ranges.len() {
 6286                    self.snippet_stack.push(snippet);
 6287                }
 6288                return true;
 6289            }
 6290        }
 6291
 6292        false
 6293    }
 6294
 6295    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6296        self.transact(window, cx, |this, window, cx| {
 6297            this.select_all(&SelectAll, window, cx);
 6298            this.insert("", window, cx);
 6299        });
 6300    }
 6301
 6302    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6303        self.transact(window, cx, |this, window, cx| {
 6304            this.select_autoclose_pair(window, cx);
 6305            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6306            if !this.linked_edit_ranges.is_empty() {
 6307                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6308                let snapshot = this.buffer.read(cx).snapshot(cx);
 6309
 6310                for selection in selections.iter() {
 6311                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6312                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6313                    if selection_start.buffer_id != selection_end.buffer_id {
 6314                        continue;
 6315                    }
 6316                    if let Some(ranges) =
 6317                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6318                    {
 6319                        for (buffer, entries) in ranges {
 6320                            linked_ranges.entry(buffer).or_default().extend(entries);
 6321                        }
 6322                    }
 6323                }
 6324            }
 6325
 6326            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6327            if !this.selections.line_mode {
 6328                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6329                for selection in &mut selections {
 6330                    if selection.is_empty() {
 6331                        let old_head = selection.head();
 6332                        let mut new_head =
 6333                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6334                                .to_point(&display_map);
 6335                        if let Some((buffer, line_buffer_range)) = display_map
 6336                            .buffer_snapshot
 6337                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6338                        {
 6339                            let indent_size =
 6340                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6341                            let indent_len = match indent_size.kind {
 6342                                IndentKind::Space => {
 6343                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6344                                }
 6345                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6346                            };
 6347                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6348                                let indent_len = indent_len.get();
 6349                                new_head = cmp::min(
 6350                                    new_head,
 6351                                    MultiBufferPoint::new(
 6352                                        old_head.row,
 6353                                        ((old_head.column - 1) / indent_len) * indent_len,
 6354                                    ),
 6355                                );
 6356                            }
 6357                        }
 6358
 6359                        selection.set_head(new_head, SelectionGoal::None);
 6360                    }
 6361                }
 6362            }
 6363
 6364            this.signature_help_state.set_backspace_pressed(true);
 6365            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6366                s.select(selections)
 6367            });
 6368            this.insert("", window, cx);
 6369            let empty_str: Arc<str> = Arc::from("");
 6370            for (buffer, edits) in linked_ranges {
 6371                let snapshot = buffer.read(cx).snapshot();
 6372                use text::ToPoint as TP;
 6373
 6374                let edits = edits
 6375                    .into_iter()
 6376                    .map(|range| {
 6377                        let end_point = TP::to_point(&range.end, &snapshot);
 6378                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6379
 6380                        if end_point == start_point {
 6381                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6382                                .saturating_sub(1);
 6383                            start_point =
 6384                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6385                        };
 6386
 6387                        (start_point..end_point, empty_str.clone())
 6388                    })
 6389                    .sorted_by_key(|(range, _)| range.start)
 6390                    .collect::<Vec<_>>();
 6391                buffer.update(cx, |this, cx| {
 6392                    this.edit(edits, None, cx);
 6393                })
 6394            }
 6395            this.refresh_inline_completion(true, false, window, cx);
 6396            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6397        });
 6398    }
 6399
 6400    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6401        self.transact(window, cx, |this, window, cx| {
 6402            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6403                let line_mode = s.line_mode;
 6404                s.move_with(|map, selection| {
 6405                    if selection.is_empty() && !line_mode {
 6406                        let cursor = movement::right(map, selection.head());
 6407                        selection.end = cursor;
 6408                        selection.reversed = true;
 6409                        selection.goal = SelectionGoal::None;
 6410                    }
 6411                })
 6412            });
 6413            this.insert("", window, cx);
 6414            this.refresh_inline_completion(true, false, window, cx);
 6415        });
 6416    }
 6417
 6418    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6419        if self.move_to_prev_snippet_tabstop(window, cx) {
 6420            return;
 6421        }
 6422
 6423        self.outdent(&Outdent, window, cx);
 6424    }
 6425
 6426    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6427        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6428            return;
 6429        }
 6430
 6431        let mut selections = self.selections.all_adjusted(cx);
 6432        let buffer = self.buffer.read(cx);
 6433        let snapshot = buffer.snapshot(cx);
 6434        let rows_iter = selections.iter().map(|s| s.head().row);
 6435        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6436
 6437        let mut edits = Vec::new();
 6438        let mut prev_edited_row = 0;
 6439        let mut row_delta = 0;
 6440        for selection in &mut selections {
 6441            if selection.start.row != prev_edited_row {
 6442                row_delta = 0;
 6443            }
 6444            prev_edited_row = selection.end.row;
 6445
 6446            // If the selection is non-empty, then increase the indentation of the selected lines.
 6447            if !selection.is_empty() {
 6448                row_delta =
 6449                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6450                continue;
 6451            }
 6452
 6453            // If the selection is empty and the cursor is in the leading whitespace before the
 6454            // suggested indentation, then auto-indent the line.
 6455            let cursor = selection.head();
 6456            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6457            if let Some(suggested_indent) =
 6458                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6459            {
 6460                if cursor.column < suggested_indent.len
 6461                    && cursor.column <= current_indent.len
 6462                    && current_indent.len <= suggested_indent.len
 6463                {
 6464                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6465                    selection.end = selection.start;
 6466                    if row_delta == 0 {
 6467                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6468                            cursor.row,
 6469                            current_indent,
 6470                            suggested_indent,
 6471                        ));
 6472                        row_delta = suggested_indent.len - current_indent.len;
 6473                    }
 6474                    continue;
 6475                }
 6476            }
 6477
 6478            // Otherwise, insert a hard or soft tab.
 6479            let settings = buffer.settings_at(cursor, cx);
 6480            let tab_size = if settings.hard_tabs {
 6481                IndentSize::tab()
 6482            } else {
 6483                let tab_size = settings.tab_size.get();
 6484                let char_column = snapshot
 6485                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6486                    .flat_map(str::chars)
 6487                    .count()
 6488                    + row_delta as usize;
 6489                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6490                IndentSize::spaces(chars_to_next_tab_stop)
 6491            };
 6492            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6493            selection.end = selection.start;
 6494            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6495            row_delta += tab_size.len;
 6496        }
 6497
 6498        self.transact(window, cx, |this, window, cx| {
 6499            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6500            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6501                s.select(selections)
 6502            });
 6503            this.refresh_inline_completion(true, false, window, cx);
 6504        });
 6505    }
 6506
 6507    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6508        if self.read_only(cx) {
 6509            return;
 6510        }
 6511        let mut selections = self.selections.all::<Point>(cx);
 6512        let mut prev_edited_row = 0;
 6513        let mut row_delta = 0;
 6514        let mut edits = Vec::new();
 6515        let buffer = self.buffer.read(cx);
 6516        let snapshot = buffer.snapshot(cx);
 6517        for selection in &mut selections {
 6518            if selection.start.row != prev_edited_row {
 6519                row_delta = 0;
 6520            }
 6521            prev_edited_row = selection.end.row;
 6522
 6523            row_delta =
 6524                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6525        }
 6526
 6527        self.transact(window, cx, |this, window, cx| {
 6528            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6529            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6530                s.select(selections)
 6531            });
 6532        });
 6533    }
 6534
 6535    fn indent_selection(
 6536        buffer: &MultiBuffer,
 6537        snapshot: &MultiBufferSnapshot,
 6538        selection: &mut Selection<Point>,
 6539        edits: &mut Vec<(Range<Point>, String)>,
 6540        delta_for_start_row: u32,
 6541        cx: &App,
 6542    ) -> u32 {
 6543        let settings = buffer.settings_at(selection.start, cx);
 6544        let tab_size = settings.tab_size.get();
 6545        let indent_kind = if settings.hard_tabs {
 6546            IndentKind::Tab
 6547        } else {
 6548            IndentKind::Space
 6549        };
 6550        let mut start_row = selection.start.row;
 6551        let mut end_row = selection.end.row + 1;
 6552
 6553        // If a selection ends at the beginning of a line, don't indent
 6554        // that last line.
 6555        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6556            end_row -= 1;
 6557        }
 6558
 6559        // Avoid re-indenting a row that has already been indented by a
 6560        // previous selection, but still update this selection's column
 6561        // to reflect that indentation.
 6562        if delta_for_start_row > 0 {
 6563            start_row += 1;
 6564            selection.start.column += delta_for_start_row;
 6565            if selection.end.row == selection.start.row {
 6566                selection.end.column += delta_for_start_row;
 6567            }
 6568        }
 6569
 6570        let mut delta_for_end_row = 0;
 6571        let has_multiple_rows = start_row + 1 != end_row;
 6572        for row in start_row..end_row {
 6573            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6574            let indent_delta = match (current_indent.kind, indent_kind) {
 6575                (IndentKind::Space, IndentKind::Space) => {
 6576                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6577                    IndentSize::spaces(columns_to_next_tab_stop)
 6578                }
 6579                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6580                (_, IndentKind::Tab) => IndentSize::tab(),
 6581            };
 6582
 6583            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6584                0
 6585            } else {
 6586                selection.start.column
 6587            };
 6588            let row_start = Point::new(row, start);
 6589            edits.push((
 6590                row_start..row_start,
 6591                indent_delta.chars().collect::<String>(),
 6592            ));
 6593
 6594            // Update this selection's endpoints to reflect the indentation.
 6595            if row == selection.start.row {
 6596                selection.start.column += indent_delta.len;
 6597            }
 6598            if row == selection.end.row {
 6599                selection.end.column += indent_delta.len;
 6600                delta_for_end_row = indent_delta.len;
 6601            }
 6602        }
 6603
 6604        if selection.start.row == selection.end.row {
 6605            delta_for_start_row + delta_for_end_row
 6606        } else {
 6607            delta_for_end_row
 6608        }
 6609    }
 6610
 6611    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6612        if self.read_only(cx) {
 6613            return;
 6614        }
 6615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6616        let selections = self.selections.all::<Point>(cx);
 6617        let mut deletion_ranges = Vec::new();
 6618        let mut last_outdent = None;
 6619        {
 6620            let buffer = self.buffer.read(cx);
 6621            let snapshot = buffer.snapshot(cx);
 6622            for selection in &selections {
 6623                let settings = buffer.settings_at(selection.start, cx);
 6624                let tab_size = settings.tab_size.get();
 6625                let mut rows = selection.spanned_rows(false, &display_map);
 6626
 6627                // Avoid re-outdenting a row that has already been outdented by a
 6628                // previous selection.
 6629                if let Some(last_row) = last_outdent {
 6630                    if last_row == rows.start {
 6631                        rows.start = rows.start.next_row();
 6632                    }
 6633                }
 6634                let has_multiple_rows = rows.len() > 1;
 6635                for row in rows.iter_rows() {
 6636                    let indent_size = snapshot.indent_size_for_line(row);
 6637                    if indent_size.len > 0 {
 6638                        let deletion_len = match indent_size.kind {
 6639                            IndentKind::Space => {
 6640                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6641                                if columns_to_prev_tab_stop == 0 {
 6642                                    tab_size
 6643                                } else {
 6644                                    columns_to_prev_tab_stop
 6645                                }
 6646                            }
 6647                            IndentKind::Tab => 1,
 6648                        };
 6649                        let start = if has_multiple_rows
 6650                            || deletion_len > selection.start.column
 6651                            || indent_size.len < selection.start.column
 6652                        {
 6653                            0
 6654                        } else {
 6655                            selection.start.column - deletion_len
 6656                        };
 6657                        deletion_ranges.push(
 6658                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6659                        );
 6660                        last_outdent = Some(row);
 6661                    }
 6662                }
 6663            }
 6664        }
 6665
 6666        self.transact(window, cx, |this, window, cx| {
 6667            this.buffer.update(cx, |buffer, cx| {
 6668                let empty_str: Arc<str> = Arc::default();
 6669                buffer.edit(
 6670                    deletion_ranges
 6671                        .into_iter()
 6672                        .map(|range| (range, empty_str.clone())),
 6673                    None,
 6674                    cx,
 6675                );
 6676            });
 6677            let selections = this.selections.all::<usize>(cx);
 6678            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6679                s.select(selections)
 6680            });
 6681        });
 6682    }
 6683
 6684    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6685        if self.read_only(cx) {
 6686            return;
 6687        }
 6688        let selections = self
 6689            .selections
 6690            .all::<usize>(cx)
 6691            .into_iter()
 6692            .map(|s| s.range());
 6693
 6694        self.transact(window, cx, |this, window, cx| {
 6695            this.buffer.update(cx, |buffer, cx| {
 6696                buffer.autoindent_ranges(selections, cx);
 6697            });
 6698            let selections = this.selections.all::<usize>(cx);
 6699            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6700                s.select(selections)
 6701            });
 6702        });
 6703    }
 6704
 6705    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6706        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6707        let selections = self.selections.all::<Point>(cx);
 6708
 6709        let mut new_cursors = Vec::new();
 6710        let mut edit_ranges = Vec::new();
 6711        let mut selections = selections.iter().peekable();
 6712        while let Some(selection) = selections.next() {
 6713            let mut rows = selection.spanned_rows(false, &display_map);
 6714            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6715
 6716            // Accumulate contiguous regions of rows that we want to delete.
 6717            while let Some(next_selection) = selections.peek() {
 6718                let next_rows = next_selection.spanned_rows(false, &display_map);
 6719                if next_rows.start <= rows.end {
 6720                    rows.end = next_rows.end;
 6721                    selections.next().unwrap();
 6722                } else {
 6723                    break;
 6724                }
 6725            }
 6726
 6727            let buffer = &display_map.buffer_snapshot;
 6728            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6729            let edit_end;
 6730            let cursor_buffer_row;
 6731            if buffer.max_point().row >= rows.end.0 {
 6732                // If there's a line after the range, delete the \n from the end of the row range
 6733                // and position the cursor on the next line.
 6734                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6735                cursor_buffer_row = rows.end;
 6736            } else {
 6737                // If there isn't a line after the range, delete the \n from the line before the
 6738                // start of the row range and position the cursor there.
 6739                edit_start = edit_start.saturating_sub(1);
 6740                edit_end = buffer.len();
 6741                cursor_buffer_row = rows.start.previous_row();
 6742            }
 6743
 6744            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6745            *cursor.column_mut() =
 6746                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6747
 6748            new_cursors.push((
 6749                selection.id,
 6750                buffer.anchor_after(cursor.to_point(&display_map)),
 6751            ));
 6752            edit_ranges.push(edit_start..edit_end);
 6753        }
 6754
 6755        self.transact(window, cx, |this, window, cx| {
 6756            let buffer = this.buffer.update(cx, |buffer, cx| {
 6757                let empty_str: Arc<str> = Arc::default();
 6758                buffer.edit(
 6759                    edit_ranges
 6760                        .into_iter()
 6761                        .map(|range| (range, empty_str.clone())),
 6762                    None,
 6763                    cx,
 6764                );
 6765                buffer.snapshot(cx)
 6766            });
 6767            let new_selections = new_cursors
 6768                .into_iter()
 6769                .map(|(id, cursor)| {
 6770                    let cursor = cursor.to_point(&buffer);
 6771                    Selection {
 6772                        id,
 6773                        start: cursor,
 6774                        end: cursor,
 6775                        reversed: false,
 6776                        goal: SelectionGoal::None,
 6777                    }
 6778                })
 6779                .collect();
 6780
 6781            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6782                s.select(new_selections);
 6783            });
 6784        });
 6785    }
 6786
 6787    pub fn join_lines_impl(
 6788        &mut self,
 6789        insert_whitespace: bool,
 6790        window: &mut Window,
 6791        cx: &mut Context<Self>,
 6792    ) {
 6793        if self.read_only(cx) {
 6794            return;
 6795        }
 6796        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6797        for selection in self.selections.all::<Point>(cx) {
 6798            let start = MultiBufferRow(selection.start.row);
 6799            // Treat single line selections as if they include the next line. Otherwise this action
 6800            // would do nothing for single line selections individual cursors.
 6801            let end = if selection.start.row == selection.end.row {
 6802                MultiBufferRow(selection.start.row + 1)
 6803            } else {
 6804                MultiBufferRow(selection.end.row)
 6805            };
 6806
 6807            if let Some(last_row_range) = row_ranges.last_mut() {
 6808                if start <= last_row_range.end {
 6809                    last_row_range.end = end;
 6810                    continue;
 6811                }
 6812            }
 6813            row_ranges.push(start..end);
 6814        }
 6815
 6816        let snapshot = self.buffer.read(cx).snapshot(cx);
 6817        let mut cursor_positions = Vec::new();
 6818        for row_range in &row_ranges {
 6819            let anchor = snapshot.anchor_before(Point::new(
 6820                row_range.end.previous_row().0,
 6821                snapshot.line_len(row_range.end.previous_row()),
 6822            ));
 6823            cursor_positions.push(anchor..anchor);
 6824        }
 6825
 6826        self.transact(window, cx, |this, window, cx| {
 6827            for row_range in row_ranges.into_iter().rev() {
 6828                for row in row_range.iter_rows().rev() {
 6829                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6830                    let next_line_row = row.next_row();
 6831                    let indent = snapshot.indent_size_for_line(next_line_row);
 6832                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6833
 6834                    let replace =
 6835                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6836                            " "
 6837                        } else {
 6838                            ""
 6839                        };
 6840
 6841                    this.buffer.update(cx, |buffer, cx| {
 6842                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6843                    });
 6844                }
 6845            }
 6846
 6847            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6848                s.select_anchor_ranges(cursor_positions)
 6849            });
 6850        });
 6851    }
 6852
 6853    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6854        self.join_lines_impl(true, window, cx);
 6855    }
 6856
 6857    pub fn sort_lines_case_sensitive(
 6858        &mut self,
 6859        _: &SortLinesCaseSensitive,
 6860        window: &mut Window,
 6861        cx: &mut Context<Self>,
 6862    ) {
 6863        self.manipulate_lines(window, cx, |lines| lines.sort())
 6864    }
 6865
 6866    pub fn sort_lines_case_insensitive(
 6867        &mut self,
 6868        _: &SortLinesCaseInsensitive,
 6869        window: &mut Window,
 6870        cx: &mut Context<Self>,
 6871    ) {
 6872        self.manipulate_lines(window, cx, |lines| {
 6873            lines.sort_by_key(|line| line.to_lowercase())
 6874        })
 6875    }
 6876
 6877    pub fn unique_lines_case_insensitive(
 6878        &mut self,
 6879        _: &UniqueLinesCaseInsensitive,
 6880        window: &mut Window,
 6881        cx: &mut Context<Self>,
 6882    ) {
 6883        self.manipulate_lines(window, cx, |lines| {
 6884            let mut seen = HashSet::default();
 6885            lines.retain(|line| seen.insert(line.to_lowercase()));
 6886        })
 6887    }
 6888
 6889    pub fn unique_lines_case_sensitive(
 6890        &mut self,
 6891        _: &UniqueLinesCaseSensitive,
 6892        window: &mut Window,
 6893        cx: &mut Context<Self>,
 6894    ) {
 6895        self.manipulate_lines(window, cx, |lines| {
 6896            let mut seen = HashSet::default();
 6897            lines.retain(|line| seen.insert(*line));
 6898        })
 6899    }
 6900
 6901    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6902        let mut revert_changes = HashMap::default();
 6903        let snapshot = self.snapshot(window, cx);
 6904        for hunk in snapshot
 6905            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6906        {
 6907            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6908        }
 6909        if !revert_changes.is_empty() {
 6910            self.transact(window, cx, |editor, window, cx| {
 6911                editor.revert(revert_changes, window, cx);
 6912            });
 6913        }
 6914    }
 6915
 6916    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6917        let Some(project) = self.project.clone() else {
 6918            return;
 6919        };
 6920        self.reload(project, window, cx)
 6921            .detach_and_notify_err(window, cx);
 6922    }
 6923
 6924    pub fn revert_selected_hunks(
 6925        &mut self,
 6926        _: &RevertSelectedHunks,
 6927        window: &mut Window,
 6928        cx: &mut Context<Self>,
 6929    ) {
 6930        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6931        self.revert_hunks_in_ranges(selections, window, cx);
 6932    }
 6933
 6934    fn revert_hunks_in_ranges(
 6935        &mut self,
 6936        ranges: impl Iterator<Item = Range<Point>>,
 6937        window: &mut Window,
 6938        cx: &mut Context<Editor>,
 6939    ) {
 6940        let mut revert_changes = HashMap::default();
 6941        let snapshot = self.snapshot(window, cx);
 6942        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6943            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6944        }
 6945        if !revert_changes.is_empty() {
 6946            self.transact(window, cx, |editor, window, cx| {
 6947                editor.revert(revert_changes, window, cx);
 6948            });
 6949        }
 6950    }
 6951
 6952    pub fn open_active_item_in_terminal(
 6953        &mut self,
 6954        _: &OpenInTerminal,
 6955        window: &mut Window,
 6956        cx: &mut Context<Self>,
 6957    ) {
 6958        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6959            let project_path = buffer.read(cx).project_path(cx)?;
 6960            let project = self.project.as_ref()?.read(cx);
 6961            let entry = project.entry_for_path(&project_path, cx)?;
 6962            let parent = match &entry.canonical_path {
 6963                Some(canonical_path) => canonical_path.to_path_buf(),
 6964                None => project.absolute_path(&project_path, cx)?,
 6965            }
 6966            .parent()?
 6967            .to_path_buf();
 6968            Some(parent)
 6969        }) {
 6970            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6971        }
 6972    }
 6973
 6974    pub fn prepare_revert_change(
 6975        &self,
 6976        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6977        hunk: &MultiBufferDiffHunk,
 6978        cx: &mut App,
 6979    ) -> Option<()> {
 6980        let buffer = self.buffer.read(cx);
 6981        let diff = buffer.diff_for(hunk.buffer_id)?;
 6982        let buffer = buffer.buffer(hunk.buffer_id)?;
 6983        let buffer = buffer.read(cx);
 6984        let original_text = diff
 6985            .read(cx)
 6986            .base_text()
 6987            .as_ref()?
 6988            .as_rope()
 6989            .slice(hunk.diff_base_byte_range.clone());
 6990        let buffer_snapshot = buffer.snapshot();
 6991        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6992        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6993            probe
 6994                .0
 6995                .start
 6996                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6997                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6998        }) {
 6999            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7000            Some(())
 7001        } else {
 7002            None
 7003        }
 7004    }
 7005
 7006    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7007        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7008    }
 7009
 7010    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7011        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7012    }
 7013
 7014    fn manipulate_lines<Fn>(
 7015        &mut self,
 7016        window: &mut Window,
 7017        cx: &mut Context<Self>,
 7018        mut callback: Fn,
 7019    ) where
 7020        Fn: FnMut(&mut Vec<&str>),
 7021    {
 7022        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7023        let buffer = self.buffer.read(cx).snapshot(cx);
 7024
 7025        let mut edits = Vec::new();
 7026
 7027        let selections = self.selections.all::<Point>(cx);
 7028        let mut selections = selections.iter().peekable();
 7029        let mut contiguous_row_selections = Vec::new();
 7030        let mut new_selections = Vec::new();
 7031        let mut added_lines = 0;
 7032        let mut removed_lines = 0;
 7033
 7034        while let Some(selection) = selections.next() {
 7035            let (start_row, end_row) = consume_contiguous_rows(
 7036                &mut contiguous_row_selections,
 7037                selection,
 7038                &display_map,
 7039                &mut selections,
 7040            );
 7041
 7042            let start_point = Point::new(start_row.0, 0);
 7043            let end_point = Point::new(
 7044                end_row.previous_row().0,
 7045                buffer.line_len(end_row.previous_row()),
 7046            );
 7047            let text = buffer
 7048                .text_for_range(start_point..end_point)
 7049                .collect::<String>();
 7050
 7051            let mut lines = text.split('\n').collect_vec();
 7052
 7053            let lines_before = lines.len();
 7054            callback(&mut lines);
 7055            let lines_after = lines.len();
 7056
 7057            edits.push((start_point..end_point, lines.join("\n")));
 7058
 7059            // Selections must change based on added and removed line count
 7060            let start_row =
 7061                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7062            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7063            new_selections.push(Selection {
 7064                id: selection.id,
 7065                start: start_row,
 7066                end: end_row,
 7067                goal: SelectionGoal::None,
 7068                reversed: selection.reversed,
 7069            });
 7070
 7071            if lines_after > lines_before {
 7072                added_lines += lines_after - lines_before;
 7073            } else if lines_before > lines_after {
 7074                removed_lines += lines_before - lines_after;
 7075            }
 7076        }
 7077
 7078        self.transact(window, cx, |this, window, cx| {
 7079            let buffer = this.buffer.update(cx, |buffer, cx| {
 7080                buffer.edit(edits, None, cx);
 7081                buffer.snapshot(cx)
 7082            });
 7083
 7084            // Recalculate offsets on newly edited buffer
 7085            let new_selections = new_selections
 7086                .iter()
 7087                .map(|s| {
 7088                    let start_point = Point::new(s.start.0, 0);
 7089                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7090                    Selection {
 7091                        id: s.id,
 7092                        start: buffer.point_to_offset(start_point),
 7093                        end: buffer.point_to_offset(end_point),
 7094                        goal: s.goal,
 7095                        reversed: s.reversed,
 7096                    }
 7097                })
 7098                .collect();
 7099
 7100            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7101                s.select(new_selections);
 7102            });
 7103
 7104            this.request_autoscroll(Autoscroll::fit(), cx);
 7105        });
 7106    }
 7107
 7108    pub fn convert_to_upper_case(
 7109        &mut self,
 7110        _: &ConvertToUpperCase,
 7111        window: &mut Window,
 7112        cx: &mut Context<Self>,
 7113    ) {
 7114        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7115    }
 7116
 7117    pub fn convert_to_lower_case(
 7118        &mut self,
 7119        _: &ConvertToLowerCase,
 7120        window: &mut Window,
 7121        cx: &mut Context<Self>,
 7122    ) {
 7123        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7124    }
 7125
 7126    pub fn convert_to_title_case(
 7127        &mut self,
 7128        _: &ConvertToTitleCase,
 7129        window: &mut Window,
 7130        cx: &mut Context<Self>,
 7131    ) {
 7132        self.manipulate_text(window, cx, |text| {
 7133            text.split('\n')
 7134                .map(|line| line.to_case(Case::Title))
 7135                .join("\n")
 7136        })
 7137    }
 7138
 7139    pub fn convert_to_snake_case(
 7140        &mut self,
 7141        _: &ConvertToSnakeCase,
 7142        window: &mut Window,
 7143        cx: &mut Context<Self>,
 7144    ) {
 7145        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7146    }
 7147
 7148    pub fn convert_to_kebab_case(
 7149        &mut self,
 7150        _: &ConvertToKebabCase,
 7151        window: &mut Window,
 7152        cx: &mut Context<Self>,
 7153    ) {
 7154        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7155    }
 7156
 7157    pub fn convert_to_upper_camel_case(
 7158        &mut self,
 7159        _: &ConvertToUpperCamelCase,
 7160        window: &mut Window,
 7161        cx: &mut Context<Self>,
 7162    ) {
 7163        self.manipulate_text(window, cx, |text| {
 7164            text.split('\n')
 7165                .map(|line| line.to_case(Case::UpperCamel))
 7166                .join("\n")
 7167        })
 7168    }
 7169
 7170    pub fn convert_to_lower_camel_case(
 7171        &mut self,
 7172        _: &ConvertToLowerCamelCase,
 7173        window: &mut Window,
 7174        cx: &mut Context<Self>,
 7175    ) {
 7176        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7177    }
 7178
 7179    pub fn convert_to_opposite_case(
 7180        &mut self,
 7181        _: &ConvertToOppositeCase,
 7182        window: &mut Window,
 7183        cx: &mut Context<Self>,
 7184    ) {
 7185        self.manipulate_text(window, cx, |text| {
 7186            text.chars()
 7187                .fold(String::with_capacity(text.len()), |mut t, c| {
 7188                    if c.is_uppercase() {
 7189                        t.extend(c.to_lowercase());
 7190                    } else {
 7191                        t.extend(c.to_uppercase());
 7192                    }
 7193                    t
 7194                })
 7195        })
 7196    }
 7197
 7198    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7199    where
 7200        Fn: FnMut(&str) -> String,
 7201    {
 7202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7203        let buffer = self.buffer.read(cx).snapshot(cx);
 7204
 7205        let mut new_selections = Vec::new();
 7206        let mut edits = Vec::new();
 7207        let mut selection_adjustment = 0i32;
 7208
 7209        for selection in self.selections.all::<usize>(cx) {
 7210            let selection_is_empty = selection.is_empty();
 7211
 7212            let (start, end) = if selection_is_empty {
 7213                let word_range = movement::surrounding_word(
 7214                    &display_map,
 7215                    selection.start.to_display_point(&display_map),
 7216                );
 7217                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7218                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7219                (start, end)
 7220            } else {
 7221                (selection.start, selection.end)
 7222            };
 7223
 7224            let text = buffer.text_for_range(start..end).collect::<String>();
 7225            let old_length = text.len() as i32;
 7226            let text = callback(&text);
 7227
 7228            new_selections.push(Selection {
 7229                start: (start as i32 - selection_adjustment) as usize,
 7230                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7231                goal: SelectionGoal::None,
 7232                ..selection
 7233            });
 7234
 7235            selection_adjustment += old_length - text.len() as i32;
 7236
 7237            edits.push((start..end, text));
 7238        }
 7239
 7240        self.transact(window, cx, |this, window, cx| {
 7241            this.buffer.update(cx, |buffer, cx| {
 7242                buffer.edit(edits, None, cx);
 7243            });
 7244
 7245            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7246                s.select(new_selections);
 7247            });
 7248
 7249            this.request_autoscroll(Autoscroll::fit(), cx);
 7250        });
 7251    }
 7252
 7253    pub fn duplicate(
 7254        &mut self,
 7255        upwards: bool,
 7256        whole_lines: bool,
 7257        window: &mut Window,
 7258        cx: &mut Context<Self>,
 7259    ) {
 7260        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7261        let buffer = &display_map.buffer_snapshot;
 7262        let selections = self.selections.all::<Point>(cx);
 7263
 7264        let mut edits = Vec::new();
 7265        let mut selections_iter = selections.iter().peekable();
 7266        while let Some(selection) = selections_iter.next() {
 7267            let mut rows = selection.spanned_rows(false, &display_map);
 7268            // duplicate line-wise
 7269            if whole_lines || selection.start == selection.end {
 7270                // Avoid duplicating the same lines twice.
 7271                while let Some(next_selection) = selections_iter.peek() {
 7272                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7273                    if next_rows.start < rows.end {
 7274                        rows.end = next_rows.end;
 7275                        selections_iter.next().unwrap();
 7276                    } else {
 7277                        break;
 7278                    }
 7279                }
 7280
 7281                // Copy the text from the selected row region and splice it either at the start
 7282                // or end of the region.
 7283                let start = Point::new(rows.start.0, 0);
 7284                let end = Point::new(
 7285                    rows.end.previous_row().0,
 7286                    buffer.line_len(rows.end.previous_row()),
 7287                );
 7288                let text = buffer
 7289                    .text_for_range(start..end)
 7290                    .chain(Some("\n"))
 7291                    .collect::<String>();
 7292                let insert_location = if upwards {
 7293                    Point::new(rows.end.0, 0)
 7294                } else {
 7295                    start
 7296                };
 7297                edits.push((insert_location..insert_location, text));
 7298            } else {
 7299                // duplicate character-wise
 7300                let start = selection.start;
 7301                let end = selection.end;
 7302                let text = buffer.text_for_range(start..end).collect::<String>();
 7303                edits.push((selection.end..selection.end, text));
 7304            }
 7305        }
 7306
 7307        self.transact(window, cx, |this, _, cx| {
 7308            this.buffer.update(cx, |buffer, cx| {
 7309                buffer.edit(edits, None, cx);
 7310            });
 7311
 7312            this.request_autoscroll(Autoscroll::fit(), cx);
 7313        });
 7314    }
 7315
 7316    pub fn duplicate_line_up(
 7317        &mut self,
 7318        _: &DuplicateLineUp,
 7319        window: &mut Window,
 7320        cx: &mut Context<Self>,
 7321    ) {
 7322        self.duplicate(true, true, window, cx);
 7323    }
 7324
 7325    pub fn duplicate_line_down(
 7326        &mut self,
 7327        _: &DuplicateLineDown,
 7328        window: &mut Window,
 7329        cx: &mut Context<Self>,
 7330    ) {
 7331        self.duplicate(false, true, window, cx);
 7332    }
 7333
 7334    pub fn duplicate_selection(
 7335        &mut self,
 7336        _: &DuplicateSelection,
 7337        window: &mut Window,
 7338        cx: &mut Context<Self>,
 7339    ) {
 7340        self.duplicate(false, false, window, cx);
 7341    }
 7342
 7343    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7344        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7345        let buffer = self.buffer.read(cx).snapshot(cx);
 7346
 7347        let mut edits = Vec::new();
 7348        let mut unfold_ranges = Vec::new();
 7349        let mut refold_creases = Vec::new();
 7350
 7351        let selections = self.selections.all::<Point>(cx);
 7352        let mut selections = selections.iter().peekable();
 7353        let mut contiguous_row_selections = Vec::new();
 7354        let mut new_selections = Vec::new();
 7355
 7356        while let Some(selection) = selections.next() {
 7357            // Find all the selections that span a contiguous row range
 7358            let (start_row, end_row) = consume_contiguous_rows(
 7359                &mut contiguous_row_selections,
 7360                selection,
 7361                &display_map,
 7362                &mut selections,
 7363            );
 7364
 7365            // Move the text spanned by the row range to be before the line preceding the row range
 7366            if start_row.0 > 0 {
 7367                let range_to_move = Point::new(
 7368                    start_row.previous_row().0,
 7369                    buffer.line_len(start_row.previous_row()),
 7370                )
 7371                    ..Point::new(
 7372                        end_row.previous_row().0,
 7373                        buffer.line_len(end_row.previous_row()),
 7374                    );
 7375                let insertion_point = display_map
 7376                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7377                    .0;
 7378
 7379                // Don't move lines across excerpts
 7380                if buffer
 7381                    .excerpt_containing(insertion_point..range_to_move.end)
 7382                    .is_some()
 7383                {
 7384                    let text = buffer
 7385                        .text_for_range(range_to_move.clone())
 7386                        .flat_map(|s| s.chars())
 7387                        .skip(1)
 7388                        .chain(['\n'])
 7389                        .collect::<String>();
 7390
 7391                    edits.push((
 7392                        buffer.anchor_after(range_to_move.start)
 7393                            ..buffer.anchor_before(range_to_move.end),
 7394                        String::new(),
 7395                    ));
 7396                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7397                    edits.push((insertion_anchor..insertion_anchor, text));
 7398
 7399                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7400
 7401                    // Move selections up
 7402                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7403                        |mut selection| {
 7404                            selection.start.row -= row_delta;
 7405                            selection.end.row -= row_delta;
 7406                            selection
 7407                        },
 7408                    ));
 7409
 7410                    // Move folds up
 7411                    unfold_ranges.push(range_to_move.clone());
 7412                    for fold in display_map.folds_in_range(
 7413                        buffer.anchor_before(range_to_move.start)
 7414                            ..buffer.anchor_after(range_to_move.end),
 7415                    ) {
 7416                        let mut start = fold.range.start.to_point(&buffer);
 7417                        let mut end = fold.range.end.to_point(&buffer);
 7418                        start.row -= row_delta;
 7419                        end.row -= row_delta;
 7420                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7421                    }
 7422                }
 7423            }
 7424
 7425            // If we didn't move line(s), preserve the existing selections
 7426            new_selections.append(&mut contiguous_row_selections);
 7427        }
 7428
 7429        self.transact(window, cx, |this, window, cx| {
 7430            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7431            this.buffer.update(cx, |buffer, cx| {
 7432                for (range, text) in edits {
 7433                    buffer.edit([(range, text)], None, cx);
 7434                }
 7435            });
 7436            this.fold_creases(refold_creases, true, window, cx);
 7437            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7438                s.select(new_selections);
 7439            })
 7440        });
 7441    }
 7442
 7443    pub fn move_line_down(
 7444        &mut self,
 7445        _: &MoveLineDown,
 7446        window: &mut Window,
 7447        cx: &mut Context<Self>,
 7448    ) {
 7449        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7450        let buffer = self.buffer.read(cx).snapshot(cx);
 7451
 7452        let mut edits = Vec::new();
 7453        let mut unfold_ranges = Vec::new();
 7454        let mut refold_creases = Vec::new();
 7455
 7456        let selections = self.selections.all::<Point>(cx);
 7457        let mut selections = selections.iter().peekable();
 7458        let mut contiguous_row_selections = Vec::new();
 7459        let mut new_selections = Vec::new();
 7460
 7461        while let Some(selection) = selections.next() {
 7462            // Find all the selections that span a contiguous row range
 7463            let (start_row, end_row) = consume_contiguous_rows(
 7464                &mut contiguous_row_selections,
 7465                selection,
 7466                &display_map,
 7467                &mut selections,
 7468            );
 7469
 7470            // Move the text spanned by the row range to be after the last line of the row range
 7471            if end_row.0 <= buffer.max_point().row {
 7472                let range_to_move =
 7473                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7474                let insertion_point = display_map
 7475                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7476                    .0;
 7477
 7478                // Don't move lines across excerpt boundaries
 7479                if buffer
 7480                    .excerpt_containing(range_to_move.start..insertion_point)
 7481                    .is_some()
 7482                {
 7483                    let mut text = String::from("\n");
 7484                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7485                    text.pop(); // Drop trailing newline
 7486                    edits.push((
 7487                        buffer.anchor_after(range_to_move.start)
 7488                            ..buffer.anchor_before(range_to_move.end),
 7489                        String::new(),
 7490                    ));
 7491                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7492                    edits.push((insertion_anchor..insertion_anchor, text));
 7493
 7494                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7495
 7496                    // Move selections down
 7497                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7498                        |mut selection| {
 7499                            selection.start.row += row_delta;
 7500                            selection.end.row += row_delta;
 7501                            selection
 7502                        },
 7503                    ));
 7504
 7505                    // Move folds down
 7506                    unfold_ranges.push(range_to_move.clone());
 7507                    for fold in display_map.folds_in_range(
 7508                        buffer.anchor_before(range_to_move.start)
 7509                            ..buffer.anchor_after(range_to_move.end),
 7510                    ) {
 7511                        let mut start = fold.range.start.to_point(&buffer);
 7512                        let mut end = fold.range.end.to_point(&buffer);
 7513                        start.row += row_delta;
 7514                        end.row += row_delta;
 7515                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7516                    }
 7517                }
 7518            }
 7519
 7520            // If we didn't move line(s), preserve the existing selections
 7521            new_selections.append(&mut contiguous_row_selections);
 7522        }
 7523
 7524        self.transact(window, cx, |this, window, cx| {
 7525            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7526            this.buffer.update(cx, |buffer, cx| {
 7527                for (range, text) in edits {
 7528                    buffer.edit([(range, text)], None, cx);
 7529                }
 7530            });
 7531            this.fold_creases(refold_creases, true, window, cx);
 7532            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7533                s.select(new_selections)
 7534            });
 7535        });
 7536    }
 7537
 7538    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7539        let text_layout_details = &self.text_layout_details(window);
 7540        self.transact(window, cx, |this, window, cx| {
 7541            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7542                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7543                let line_mode = s.line_mode;
 7544                s.move_with(|display_map, selection| {
 7545                    if !selection.is_empty() || line_mode {
 7546                        return;
 7547                    }
 7548
 7549                    let mut head = selection.head();
 7550                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7551                    if head.column() == display_map.line_len(head.row()) {
 7552                        transpose_offset = display_map
 7553                            .buffer_snapshot
 7554                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7555                    }
 7556
 7557                    if transpose_offset == 0 {
 7558                        return;
 7559                    }
 7560
 7561                    *head.column_mut() += 1;
 7562                    head = display_map.clip_point(head, Bias::Right);
 7563                    let goal = SelectionGoal::HorizontalPosition(
 7564                        display_map
 7565                            .x_for_display_point(head, text_layout_details)
 7566                            .into(),
 7567                    );
 7568                    selection.collapse_to(head, goal);
 7569
 7570                    let transpose_start = display_map
 7571                        .buffer_snapshot
 7572                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7573                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7574                        let transpose_end = display_map
 7575                            .buffer_snapshot
 7576                            .clip_offset(transpose_offset + 1, Bias::Right);
 7577                        if let Some(ch) =
 7578                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7579                        {
 7580                            edits.push((transpose_start..transpose_offset, String::new()));
 7581                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7582                        }
 7583                    }
 7584                });
 7585                edits
 7586            });
 7587            this.buffer
 7588                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7589            let selections = this.selections.all::<usize>(cx);
 7590            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7591                s.select(selections);
 7592            });
 7593        });
 7594    }
 7595
 7596    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7597        self.rewrap_impl(IsVimMode::No, cx)
 7598    }
 7599
 7600    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7601        let buffer = self.buffer.read(cx).snapshot(cx);
 7602        let selections = self.selections.all::<Point>(cx);
 7603        let mut selections = selections.iter().peekable();
 7604
 7605        let mut edits = Vec::new();
 7606        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7607
 7608        while let Some(selection) = selections.next() {
 7609            let mut start_row = selection.start.row;
 7610            let mut end_row = selection.end.row;
 7611
 7612            // Skip selections that overlap with a range that has already been rewrapped.
 7613            let selection_range = start_row..end_row;
 7614            if rewrapped_row_ranges
 7615                .iter()
 7616                .any(|range| range.overlaps(&selection_range))
 7617            {
 7618                continue;
 7619            }
 7620
 7621            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7622
 7623            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7624                match language_scope.language_name().as_ref() {
 7625                    "Markdown" | "Plain Text" => {
 7626                        should_rewrap = true;
 7627                    }
 7628                    _ => {}
 7629                }
 7630            }
 7631
 7632            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7633
 7634            // Since not all lines in the selection may be at the same indent
 7635            // level, choose the indent size that is the most common between all
 7636            // of the lines.
 7637            //
 7638            // If there is a tie, we use the deepest indent.
 7639            let (indent_size, indent_end) = {
 7640                let mut indent_size_occurrences = HashMap::default();
 7641                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7642
 7643                for row in start_row..=end_row {
 7644                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7645                    rows_by_indent_size.entry(indent).or_default().push(row);
 7646                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7647                }
 7648
 7649                let indent_size = indent_size_occurrences
 7650                    .into_iter()
 7651                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7652                    .map(|(indent, _)| indent)
 7653                    .unwrap_or_default();
 7654                let row = rows_by_indent_size[&indent_size][0];
 7655                let indent_end = Point::new(row, indent_size.len);
 7656
 7657                (indent_size, indent_end)
 7658            };
 7659
 7660            let mut line_prefix = indent_size.chars().collect::<String>();
 7661
 7662            if let Some(comment_prefix) =
 7663                buffer
 7664                    .language_scope_at(selection.head())
 7665                    .and_then(|language| {
 7666                        language
 7667                            .line_comment_prefixes()
 7668                            .iter()
 7669                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7670                            .cloned()
 7671                    })
 7672            {
 7673                line_prefix.push_str(&comment_prefix);
 7674                should_rewrap = true;
 7675            }
 7676
 7677            if !should_rewrap {
 7678                continue;
 7679            }
 7680
 7681            if selection.is_empty() {
 7682                'expand_upwards: while start_row > 0 {
 7683                    let prev_row = start_row - 1;
 7684                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7685                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7686                    {
 7687                        start_row = prev_row;
 7688                    } else {
 7689                        break 'expand_upwards;
 7690                    }
 7691                }
 7692
 7693                'expand_downwards: while end_row < buffer.max_point().row {
 7694                    let next_row = end_row + 1;
 7695                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7696                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7697                    {
 7698                        end_row = next_row;
 7699                    } else {
 7700                        break 'expand_downwards;
 7701                    }
 7702                }
 7703            }
 7704
 7705            let start = Point::new(start_row, 0);
 7706            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7707            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7708            let Some(lines_without_prefixes) = selection_text
 7709                .lines()
 7710                .map(|line| {
 7711                    line.strip_prefix(&line_prefix)
 7712                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7713                        .ok_or_else(|| {
 7714                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7715                        })
 7716                })
 7717                .collect::<Result<Vec<_>, _>>()
 7718                .log_err()
 7719            else {
 7720                continue;
 7721            };
 7722
 7723            let wrap_column = buffer
 7724                .settings_at(Point::new(start_row, 0), cx)
 7725                .preferred_line_length as usize;
 7726            let wrapped_text = wrap_with_prefix(
 7727                line_prefix,
 7728                lines_without_prefixes.join(" "),
 7729                wrap_column,
 7730                tab_size,
 7731            );
 7732
 7733            // TODO: should always use char-based diff while still supporting cursor behavior that
 7734            // matches vim.
 7735            let diff = match is_vim_mode {
 7736                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7737                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7738            };
 7739            let mut offset = start.to_offset(&buffer);
 7740            let mut moved_since_edit = true;
 7741
 7742            for change in diff.iter_all_changes() {
 7743                let value = change.value();
 7744                match change.tag() {
 7745                    ChangeTag::Equal => {
 7746                        offset += value.len();
 7747                        moved_since_edit = true;
 7748                    }
 7749                    ChangeTag::Delete => {
 7750                        let start = buffer.anchor_after(offset);
 7751                        let end = buffer.anchor_before(offset + value.len());
 7752
 7753                        if moved_since_edit {
 7754                            edits.push((start..end, String::new()));
 7755                        } else {
 7756                            edits.last_mut().unwrap().0.end = end;
 7757                        }
 7758
 7759                        offset += value.len();
 7760                        moved_since_edit = false;
 7761                    }
 7762                    ChangeTag::Insert => {
 7763                        if moved_since_edit {
 7764                            let anchor = buffer.anchor_after(offset);
 7765                            edits.push((anchor..anchor, value.to_string()));
 7766                        } else {
 7767                            edits.last_mut().unwrap().1.push_str(value);
 7768                        }
 7769
 7770                        moved_since_edit = false;
 7771                    }
 7772                }
 7773            }
 7774
 7775            rewrapped_row_ranges.push(start_row..=end_row);
 7776        }
 7777
 7778        self.buffer
 7779            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7780    }
 7781
 7782    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7783        let mut text = String::new();
 7784        let buffer = self.buffer.read(cx).snapshot(cx);
 7785        let mut selections = self.selections.all::<Point>(cx);
 7786        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7787        {
 7788            let max_point = buffer.max_point();
 7789            let mut is_first = true;
 7790            for selection in &mut selections {
 7791                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7792                if is_entire_line {
 7793                    selection.start = Point::new(selection.start.row, 0);
 7794                    if !selection.is_empty() && selection.end.column == 0 {
 7795                        selection.end = cmp::min(max_point, selection.end);
 7796                    } else {
 7797                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7798                    }
 7799                    selection.goal = SelectionGoal::None;
 7800                }
 7801                if is_first {
 7802                    is_first = false;
 7803                } else {
 7804                    text += "\n";
 7805                }
 7806                let mut len = 0;
 7807                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7808                    text.push_str(chunk);
 7809                    len += chunk.len();
 7810                }
 7811                clipboard_selections.push(ClipboardSelection {
 7812                    len,
 7813                    is_entire_line,
 7814                    first_line_indent: buffer
 7815                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7816                        .len,
 7817                });
 7818            }
 7819        }
 7820
 7821        self.transact(window, cx, |this, window, cx| {
 7822            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7823                s.select(selections);
 7824            });
 7825            this.insert("", window, cx);
 7826        });
 7827        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7828    }
 7829
 7830    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7831        let item = self.cut_common(window, cx);
 7832        cx.write_to_clipboard(item);
 7833    }
 7834
 7835    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7836        self.change_selections(None, window, cx, |s| {
 7837            s.move_with(|snapshot, sel| {
 7838                if sel.is_empty() {
 7839                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7840                }
 7841            });
 7842        });
 7843        let item = self.cut_common(window, cx);
 7844        cx.set_global(KillRing(item))
 7845    }
 7846
 7847    pub fn kill_ring_yank(
 7848        &mut self,
 7849        _: &KillRingYank,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7854            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7855                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7856            } else {
 7857                return;
 7858            }
 7859        } else {
 7860            return;
 7861        };
 7862        self.do_paste(&text, metadata, false, window, cx);
 7863    }
 7864
 7865    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7866        let selections = self.selections.all::<Point>(cx);
 7867        let buffer = self.buffer.read(cx).read(cx);
 7868        let mut text = String::new();
 7869
 7870        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7871        {
 7872            let max_point = buffer.max_point();
 7873            let mut is_first = true;
 7874            for selection in selections.iter() {
 7875                let mut start = selection.start;
 7876                let mut end = selection.end;
 7877                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7878                if is_entire_line {
 7879                    start = Point::new(start.row, 0);
 7880                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7881                }
 7882                if is_first {
 7883                    is_first = false;
 7884                } else {
 7885                    text += "\n";
 7886                }
 7887                let mut len = 0;
 7888                for chunk in buffer.text_for_range(start..end) {
 7889                    text.push_str(chunk);
 7890                    len += chunk.len();
 7891                }
 7892                clipboard_selections.push(ClipboardSelection {
 7893                    len,
 7894                    is_entire_line,
 7895                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7896                });
 7897            }
 7898        }
 7899
 7900        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7901            text,
 7902            clipboard_selections,
 7903        ));
 7904    }
 7905
 7906    pub fn do_paste(
 7907        &mut self,
 7908        text: &String,
 7909        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7910        handle_entire_lines: bool,
 7911        window: &mut Window,
 7912        cx: &mut Context<Self>,
 7913    ) {
 7914        if self.read_only(cx) {
 7915            return;
 7916        }
 7917
 7918        let clipboard_text = Cow::Borrowed(text);
 7919
 7920        self.transact(window, cx, |this, window, cx| {
 7921            if let Some(mut clipboard_selections) = clipboard_selections {
 7922                let old_selections = this.selections.all::<usize>(cx);
 7923                let all_selections_were_entire_line =
 7924                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7925                let first_selection_indent_column =
 7926                    clipboard_selections.first().map(|s| s.first_line_indent);
 7927                if clipboard_selections.len() != old_selections.len() {
 7928                    clipboard_selections.drain(..);
 7929                }
 7930                let cursor_offset = this.selections.last::<usize>(cx).head();
 7931                let mut auto_indent_on_paste = true;
 7932
 7933                this.buffer.update(cx, |buffer, cx| {
 7934                    let snapshot = buffer.read(cx);
 7935                    auto_indent_on_paste =
 7936                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7937
 7938                    let mut start_offset = 0;
 7939                    let mut edits = Vec::new();
 7940                    let mut original_indent_columns = Vec::new();
 7941                    for (ix, selection) in old_selections.iter().enumerate() {
 7942                        let to_insert;
 7943                        let entire_line;
 7944                        let original_indent_column;
 7945                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7946                            let end_offset = start_offset + clipboard_selection.len;
 7947                            to_insert = &clipboard_text[start_offset..end_offset];
 7948                            entire_line = clipboard_selection.is_entire_line;
 7949                            start_offset = end_offset + 1;
 7950                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7951                        } else {
 7952                            to_insert = clipboard_text.as_str();
 7953                            entire_line = all_selections_were_entire_line;
 7954                            original_indent_column = first_selection_indent_column
 7955                        }
 7956
 7957                        // If the corresponding selection was empty when this slice of the
 7958                        // clipboard text was written, then the entire line containing the
 7959                        // selection was copied. If this selection is also currently empty,
 7960                        // then paste the line before the current line of the buffer.
 7961                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7962                            let column = selection.start.to_point(&snapshot).column as usize;
 7963                            let line_start = selection.start - column;
 7964                            line_start..line_start
 7965                        } else {
 7966                            selection.range()
 7967                        };
 7968
 7969                        edits.push((range, to_insert));
 7970                        original_indent_columns.extend(original_indent_column);
 7971                    }
 7972                    drop(snapshot);
 7973
 7974                    buffer.edit(
 7975                        edits,
 7976                        if auto_indent_on_paste {
 7977                            Some(AutoindentMode::Block {
 7978                                original_indent_columns,
 7979                            })
 7980                        } else {
 7981                            None
 7982                        },
 7983                        cx,
 7984                    );
 7985                });
 7986
 7987                let selections = this.selections.all::<usize>(cx);
 7988                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7989                    s.select(selections)
 7990                });
 7991            } else {
 7992                this.insert(&clipboard_text, window, cx);
 7993            }
 7994        });
 7995    }
 7996
 7997    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7998        if let Some(item) = cx.read_from_clipboard() {
 7999            let entries = item.entries();
 8000
 8001            match entries.first() {
 8002                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8003                // of all the pasted entries.
 8004                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8005                    .do_paste(
 8006                        clipboard_string.text(),
 8007                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8008                        true,
 8009                        window,
 8010                        cx,
 8011                    ),
 8012                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8013            }
 8014        }
 8015    }
 8016
 8017    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8018        if self.read_only(cx) {
 8019            return;
 8020        }
 8021
 8022        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8023            if let Some((selections, _)) =
 8024                self.selection_history.transaction(transaction_id).cloned()
 8025            {
 8026                self.change_selections(None, window, cx, |s| {
 8027                    s.select_anchors(selections.to_vec());
 8028                });
 8029            }
 8030            self.request_autoscroll(Autoscroll::fit(), cx);
 8031            self.unmark_text(window, cx);
 8032            self.refresh_inline_completion(true, false, window, cx);
 8033            cx.emit(EditorEvent::Edited { transaction_id });
 8034            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8035        }
 8036    }
 8037
 8038    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8039        if self.read_only(cx) {
 8040            return;
 8041        }
 8042
 8043        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8044            if let Some((_, Some(selections))) =
 8045                self.selection_history.transaction(transaction_id).cloned()
 8046            {
 8047                self.change_selections(None, window, cx, |s| {
 8048                    s.select_anchors(selections.to_vec());
 8049                });
 8050            }
 8051            self.request_autoscroll(Autoscroll::fit(), cx);
 8052            self.unmark_text(window, cx);
 8053            self.refresh_inline_completion(true, false, window, cx);
 8054            cx.emit(EditorEvent::Edited { transaction_id });
 8055        }
 8056    }
 8057
 8058    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8059        self.buffer
 8060            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8061    }
 8062
 8063    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8064        self.buffer
 8065            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8066    }
 8067
 8068    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8069        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8070            let line_mode = s.line_mode;
 8071            s.move_with(|map, selection| {
 8072                let cursor = if selection.is_empty() && !line_mode {
 8073                    movement::left(map, selection.start)
 8074                } else {
 8075                    selection.start
 8076                };
 8077                selection.collapse_to(cursor, SelectionGoal::None);
 8078            });
 8079        })
 8080    }
 8081
 8082    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8083        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8084            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8085        })
 8086    }
 8087
 8088    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8090            let line_mode = s.line_mode;
 8091            s.move_with(|map, selection| {
 8092                let cursor = if selection.is_empty() && !line_mode {
 8093                    movement::right(map, selection.end)
 8094                } else {
 8095                    selection.end
 8096                };
 8097                selection.collapse_to(cursor, SelectionGoal::None)
 8098            });
 8099        })
 8100    }
 8101
 8102    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8103        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8104            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8105        })
 8106    }
 8107
 8108    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8109        if self.take_rename(true, window, cx).is_some() {
 8110            return;
 8111        }
 8112
 8113        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8114            cx.propagate();
 8115            return;
 8116        }
 8117
 8118        let text_layout_details = &self.text_layout_details(window);
 8119        let selection_count = self.selections.count();
 8120        let first_selection = self.selections.first_anchor();
 8121
 8122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8123            let line_mode = s.line_mode;
 8124            s.move_with(|map, selection| {
 8125                if !selection.is_empty() && !line_mode {
 8126                    selection.goal = SelectionGoal::None;
 8127                }
 8128                let (cursor, goal) = movement::up(
 8129                    map,
 8130                    selection.start,
 8131                    selection.goal,
 8132                    false,
 8133                    text_layout_details,
 8134                );
 8135                selection.collapse_to(cursor, goal);
 8136            });
 8137        });
 8138
 8139        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8140        {
 8141            cx.propagate();
 8142        }
 8143    }
 8144
 8145    pub fn move_up_by_lines(
 8146        &mut self,
 8147        action: &MoveUpByLines,
 8148        window: &mut Window,
 8149        cx: &mut Context<Self>,
 8150    ) {
 8151        if self.take_rename(true, window, cx).is_some() {
 8152            return;
 8153        }
 8154
 8155        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8156            cx.propagate();
 8157            return;
 8158        }
 8159
 8160        let text_layout_details = &self.text_layout_details(window);
 8161
 8162        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8163            let line_mode = s.line_mode;
 8164            s.move_with(|map, selection| {
 8165                if !selection.is_empty() && !line_mode {
 8166                    selection.goal = SelectionGoal::None;
 8167                }
 8168                let (cursor, goal) = movement::up_by_rows(
 8169                    map,
 8170                    selection.start,
 8171                    action.lines,
 8172                    selection.goal,
 8173                    false,
 8174                    text_layout_details,
 8175                );
 8176                selection.collapse_to(cursor, goal);
 8177            });
 8178        })
 8179    }
 8180
 8181    pub fn move_down_by_lines(
 8182        &mut self,
 8183        action: &MoveDownByLines,
 8184        window: &mut Window,
 8185        cx: &mut Context<Self>,
 8186    ) {
 8187        if self.take_rename(true, window, cx).is_some() {
 8188            return;
 8189        }
 8190
 8191        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8192            cx.propagate();
 8193            return;
 8194        }
 8195
 8196        let text_layout_details = &self.text_layout_details(window);
 8197
 8198        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8199            let line_mode = s.line_mode;
 8200            s.move_with(|map, selection| {
 8201                if !selection.is_empty() && !line_mode {
 8202                    selection.goal = SelectionGoal::None;
 8203                }
 8204                let (cursor, goal) = movement::down_by_rows(
 8205                    map,
 8206                    selection.start,
 8207                    action.lines,
 8208                    selection.goal,
 8209                    false,
 8210                    text_layout_details,
 8211                );
 8212                selection.collapse_to(cursor, goal);
 8213            });
 8214        })
 8215    }
 8216
 8217    pub fn select_down_by_lines(
 8218        &mut self,
 8219        action: &SelectDownByLines,
 8220        window: &mut Window,
 8221        cx: &mut Context<Self>,
 8222    ) {
 8223        let text_layout_details = &self.text_layout_details(window);
 8224        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8225            s.move_heads_with(|map, head, goal| {
 8226                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8227            })
 8228        })
 8229    }
 8230
 8231    pub fn select_up_by_lines(
 8232        &mut self,
 8233        action: &SelectUpByLines,
 8234        window: &mut Window,
 8235        cx: &mut Context<Self>,
 8236    ) {
 8237        let text_layout_details = &self.text_layout_details(window);
 8238        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8239            s.move_heads_with(|map, head, goal| {
 8240                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8241            })
 8242        })
 8243    }
 8244
 8245    pub fn select_page_up(
 8246        &mut self,
 8247        _: &SelectPageUp,
 8248        window: &mut Window,
 8249        cx: &mut Context<Self>,
 8250    ) {
 8251        let Some(row_count) = self.visible_row_count() else {
 8252            return;
 8253        };
 8254
 8255        let text_layout_details = &self.text_layout_details(window);
 8256
 8257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8258            s.move_heads_with(|map, head, goal| {
 8259                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8260            })
 8261        })
 8262    }
 8263
 8264    pub fn move_page_up(
 8265        &mut self,
 8266        action: &MovePageUp,
 8267        window: &mut Window,
 8268        cx: &mut Context<Self>,
 8269    ) {
 8270        if self.take_rename(true, window, cx).is_some() {
 8271            return;
 8272        }
 8273
 8274        if self
 8275            .context_menu
 8276            .borrow_mut()
 8277            .as_mut()
 8278            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8279            .unwrap_or(false)
 8280        {
 8281            return;
 8282        }
 8283
 8284        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8285            cx.propagate();
 8286            return;
 8287        }
 8288
 8289        let Some(row_count) = self.visible_row_count() else {
 8290            return;
 8291        };
 8292
 8293        let autoscroll = if action.center_cursor {
 8294            Autoscroll::center()
 8295        } else {
 8296            Autoscroll::fit()
 8297        };
 8298
 8299        let text_layout_details = &self.text_layout_details(window);
 8300
 8301        self.change_selections(Some(autoscroll), window, cx, |s| {
 8302            let line_mode = s.line_mode;
 8303            s.move_with(|map, selection| {
 8304                if !selection.is_empty() && !line_mode {
 8305                    selection.goal = SelectionGoal::None;
 8306                }
 8307                let (cursor, goal) = movement::up_by_rows(
 8308                    map,
 8309                    selection.end,
 8310                    row_count,
 8311                    selection.goal,
 8312                    false,
 8313                    text_layout_details,
 8314                );
 8315                selection.collapse_to(cursor, goal);
 8316            });
 8317        });
 8318    }
 8319
 8320    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8321        let text_layout_details = &self.text_layout_details(window);
 8322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323            s.move_heads_with(|map, head, goal| {
 8324                movement::up(map, head, goal, false, text_layout_details)
 8325            })
 8326        })
 8327    }
 8328
 8329    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8330        self.take_rename(true, window, cx);
 8331
 8332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8333            cx.propagate();
 8334            return;
 8335        }
 8336
 8337        let text_layout_details = &self.text_layout_details(window);
 8338        let selection_count = self.selections.count();
 8339        let first_selection = self.selections.first_anchor();
 8340
 8341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8342            let line_mode = s.line_mode;
 8343            s.move_with(|map, selection| {
 8344                if !selection.is_empty() && !line_mode {
 8345                    selection.goal = SelectionGoal::None;
 8346                }
 8347                let (cursor, goal) = movement::down(
 8348                    map,
 8349                    selection.end,
 8350                    selection.goal,
 8351                    false,
 8352                    text_layout_details,
 8353                );
 8354                selection.collapse_to(cursor, goal);
 8355            });
 8356        });
 8357
 8358        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8359        {
 8360            cx.propagate();
 8361        }
 8362    }
 8363
 8364    pub fn select_page_down(
 8365        &mut self,
 8366        _: &SelectPageDown,
 8367        window: &mut Window,
 8368        cx: &mut Context<Self>,
 8369    ) {
 8370        let Some(row_count) = self.visible_row_count() else {
 8371            return;
 8372        };
 8373
 8374        let text_layout_details = &self.text_layout_details(window);
 8375
 8376        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8377            s.move_heads_with(|map, head, goal| {
 8378                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8379            })
 8380        })
 8381    }
 8382
 8383    pub fn move_page_down(
 8384        &mut self,
 8385        action: &MovePageDown,
 8386        window: &mut Window,
 8387        cx: &mut Context<Self>,
 8388    ) {
 8389        if self.take_rename(true, window, cx).is_some() {
 8390            return;
 8391        }
 8392
 8393        if self
 8394            .context_menu
 8395            .borrow_mut()
 8396            .as_mut()
 8397            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8398            .unwrap_or(false)
 8399        {
 8400            return;
 8401        }
 8402
 8403        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8404            cx.propagate();
 8405            return;
 8406        }
 8407
 8408        let Some(row_count) = self.visible_row_count() else {
 8409            return;
 8410        };
 8411
 8412        let autoscroll = if action.center_cursor {
 8413            Autoscroll::center()
 8414        } else {
 8415            Autoscroll::fit()
 8416        };
 8417
 8418        let text_layout_details = &self.text_layout_details(window);
 8419        self.change_selections(Some(autoscroll), window, cx, |s| {
 8420            let line_mode = s.line_mode;
 8421            s.move_with(|map, selection| {
 8422                if !selection.is_empty() && !line_mode {
 8423                    selection.goal = SelectionGoal::None;
 8424                }
 8425                let (cursor, goal) = movement::down_by_rows(
 8426                    map,
 8427                    selection.end,
 8428                    row_count,
 8429                    selection.goal,
 8430                    false,
 8431                    text_layout_details,
 8432                );
 8433                selection.collapse_to(cursor, goal);
 8434            });
 8435        });
 8436    }
 8437
 8438    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8439        let text_layout_details = &self.text_layout_details(window);
 8440        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8441            s.move_heads_with(|map, head, goal| {
 8442                movement::down(map, head, goal, false, text_layout_details)
 8443            })
 8444        });
 8445    }
 8446
 8447    pub fn context_menu_first(
 8448        &mut self,
 8449        _: &ContextMenuFirst,
 8450        _window: &mut Window,
 8451        cx: &mut Context<Self>,
 8452    ) {
 8453        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8454            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8455        }
 8456    }
 8457
 8458    pub fn context_menu_prev(
 8459        &mut self,
 8460        _: &ContextMenuPrev,
 8461        _window: &mut Window,
 8462        cx: &mut Context<Self>,
 8463    ) {
 8464        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8465            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8466        }
 8467    }
 8468
 8469    pub fn context_menu_next(
 8470        &mut self,
 8471        _: &ContextMenuNext,
 8472        _window: &mut Window,
 8473        cx: &mut Context<Self>,
 8474    ) {
 8475        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8476            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8477        }
 8478    }
 8479
 8480    pub fn context_menu_last(
 8481        &mut self,
 8482        _: &ContextMenuLast,
 8483        _window: &mut Window,
 8484        cx: &mut Context<Self>,
 8485    ) {
 8486        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8487            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8488        }
 8489    }
 8490
 8491    pub fn move_to_previous_word_start(
 8492        &mut self,
 8493        _: &MoveToPreviousWordStart,
 8494        window: &mut Window,
 8495        cx: &mut Context<Self>,
 8496    ) {
 8497        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8498            s.move_cursors_with(|map, head, _| {
 8499                (
 8500                    movement::previous_word_start(map, head),
 8501                    SelectionGoal::None,
 8502                )
 8503            });
 8504        })
 8505    }
 8506
 8507    pub fn move_to_previous_subword_start(
 8508        &mut self,
 8509        _: &MoveToPreviousSubwordStart,
 8510        window: &mut Window,
 8511        cx: &mut Context<Self>,
 8512    ) {
 8513        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8514            s.move_cursors_with(|map, head, _| {
 8515                (
 8516                    movement::previous_subword_start(map, head),
 8517                    SelectionGoal::None,
 8518                )
 8519            });
 8520        })
 8521    }
 8522
 8523    pub fn select_to_previous_word_start(
 8524        &mut self,
 8525        _: &SelectToPreviousWordStart,
 8526        window: &mut Window,
 8527        cx: &mut Context<Self>,
 8528    ) {
 8529        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8530            s.move_heads_with(|map, head, _| {
 8531                (
 8532                    movement::previous_word_start(map, head),
 8533                    SelectionGoal::None,
 8534                )
 8535            });
 8536        })
 8537    }
 8538
 8539    pub fn select_to_previous_subword_start(
 8540        &mut self,
 8541        _: &SelectToPreviousSubwordStart,
 8542        window: &mut Window,
 8543        cx: &mut Context<Self>,
 8544    ) {
 8545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8546            s.move_heads_with(|map, head, _| {
 8547                (
 8548                    movement::previous_subword_start(map, head),
 8549                    SelectionGoal::None,
 8550                )
 8551            });
 8552        })
 8553    }
 8554
 8555    pub fn delete_to_previous_word_start(
 8556        &mut self,
 8557        action: &DeleteToPreviousWordStart,
 8558        window: &mut Window,
 8559        cx: &mut Context<Self>,
 8560    ) {
 8561        self.transact(window, cx, |this, window, cx| {
 8562            this.select_autoclose_pair(window, cx);
 8563            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8564                let line_mode = s.line_mode;
 8565                s.move_with(|map, selection| {
 8566                    if selection.is_empty() && !line_mode {
 8567                        let cursor = if action.ignore_newlines {
 8568                            movement::previous_word_start(map, selection.head())
 8569                        } else {
 8570                            movement::previous_word_start_or_newline(map, selection.head())
 8571                        };
 8572                        selection.set_head(cursor, SelectionGoal::None);
 8573                    }
 8574                });
 8575            });
 8576            this.insert("", window, cx);
 8577        });
 8578    }
 8579
 8580    pub fn delete_to_previous_subword_start(
 8581        &mut self,
 8582        _: &DeleteToPreviousSubwordStart,
 8583        window: &mut Window,
 8584        cx: &mut Context<Self>,
 8585    ) {
 8586        self.transact(window, cx, |this, window, cx| {
 8587            this.select_autoclose_pair(window, cx);
 8588            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8589                let line_mode = s.line_mode;
 8590                s.move_with(|map, selection| {
 8591                    if selection.is_empty() && !line_mode {
 8592                        let cursor = movement::previous_subword_start(map, selection.head());
 8593                        selection.set_head(cursor, SelectionGoal::None);
 8594                    }
 8595                });
 8596            });
 8597            this.insert("", window, cx);
 8598        });
 8599    }
 8600
 8601    pub fn move_to_next_word_end(
 8602        &mut self,
 8603        _: &MoveToNextWordEnd,
 8604        window: &mut Window,
 8605        cx: &mut Context<Self>,
 8606    ) {
 8607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608            s.move_cursors_with(|map, head, _| {
 8609                (movement::next_word_end(map, head), SelectionGoal::None)
 8610            });
 8611        })
 8612    }
 8613
 8614    pub fn move_to_next_subword_end(
 8615        &mut self,
 8616        _: &MoveToNextSubwordEnd,
 8617        window: &mut Window,
 8618        cx: &mut Context<Self>,
 8619    ) {
 8620        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8621            s.move_cursors_with(|map, head, _| {
 8622                (movement::next_subword_end(map, head), SelectionGoal::None)
 8623            });
 8624        })
 8625    }
 8626
 8627    pub fn select_to_next_word_end(
 8628        &mut self,
 8629        _: &SelectToNextWordEnd,
 8630        window: &mut Window,
 8631        cx: &mut Context<Self>,
 8632    ) {
 8633        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8634            s.move_heads_with(|map, head, _| {
 8635                (movement::next_word_end(map, head), SelectionGoal::None)
 8636            });
 8637        })
 8638    }
 8639
 8640    pub fn select_to_next_subword_end(
 8641        &mut self,
 8642        _: &SelectToNextSubwordEnd,
 8643        window: &mut Window,
 8644        cx: &mut Context<Self>,
 8645    ) {
 8646        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8647            s.move_heads_with(|map, head, _| {
 8648                (movement::next_subword_end(map, head), SelectionGoal::None)
 8649            });
 8650        })
 8651    }
 8652
 8653    pub fn delete_to_next_word_end(
 8654        &mut self,
 8655        action: &DeleteToNextWordEnd,
 8656        window: &mut Window,
 8657        cx: &mut Context<Self>,
 8658    ) {
 8659        self.transact(window, cx, |this, window, cx| {
 8660            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8661                let line_mode = s.line_mode;
 8662                s.move_with(|map, selection| {
 8663                    if selection.is_empty() && !line_mode {
 8664                        let cursor = if action.ignore_newlines {
 8665                            movement::next_word_end(map, selection.head())
 8666                        } else {
 8667                            movement::next_word_end_or_newline(map, selection.head())
 8668                        };
 8669                        selection.set_head(cursor, SelectionGoal::None);
 8670                    }
 8671                });
 8672            });
 8673            this.insert("", window, cx);
 8674        });
 8675    }
 8676
 8677    pub fn delete_to_next_subword_end(
 8678        &mut self,
 8679        _: &DeleteToNextSubwordEnd,
 8680        window: &mut Window,
 8681        cx: &mut Context<Self>,
 8682    ) {
 8683        self.transact(window, cx, |this, window, cx| {
 8684            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8685                s.move_with(|map, selection| {
 8686                    if selection.is_empty() {
 8687                        let cursor = movement::next_subword_end(map, selection.head());
 8688                        selection.set_head(cursor, SelectionGoal::None);
 8689                    }
 8690                });
 8691            });
 8692            this.insert("", window, cx);
 8693        });
 8694    }
 8695
 8696    pub fn move_to_beginning_of_line(
 8697        &mut self,
 8698        action: &MoveToBeginningOfLine,
 8699        window: &mut Window,
 8700        cx: &mut Context<Self>,
 8701    ) {
 8702        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8703            s.move_cursors_with(|map, head, _| {
 8704                (
 8705                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8706                    SelectionGoal::None,
 8707                )
 8708            });
 8709        })
 8710    }
 8711
 8712    pub fn select_to_beginning_of_line(
 8713        &mut self,
 8714        action: &SelectToBeginningOfLine,
 8715        window: &mut Window,
 8716        cx: &mut Context<Self>,
 8717    ) {
 8718        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8719            s.move_heads_with(|map, head, _| {
 8720                (
 8721                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8722                    SelectionGoal::None,
 8723                )
 8724            });
 8725        });
 8726    }
 8727
 8728    pub fn delete_to_beginning_of_line(
 8729        &mut self,
 8730        _: &DeleteToBeginningOfLine,
 8731        window: &mut Window,
 8732        cx: &mut Context<Self>,
 8733    ) {
 8734        self.transact(window, cx, |this, window, cx| {
 8735            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8736                s.move_with(|_, selection| {
 8737                    selection.reversed = true;
 8738                });
 8739            });
 8740
 8741            this.select_to_beginning_of_line(
 8742                &SelectToBeginningOfLine {
 8743                    stop_at_soft_wraps: false,
 8744                },
 8745                window,
 8746                cx,
 8747            );
 8748            this.backspace(&Backspace, window, cx);
 8749        });
 8750    }
 8751
 8752    pub fn move_to_end_of_line(
 8753        &mut self,
 8754        action: &MoveToEndOfLine,
 8755        window: &mut Window,
 8756        cx: &mut Context<Self>,
 8757    ) {
 8758        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8759            s.move_cursors_with(|map, head, _| {
 8760                (
 8761                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8762                    SelectionGoal::None,
 8763                )
 8764            });
 8765        })
 8766    }
 8767
 8768    pub fn select_to_end_of_line(
 8769        &mut self,
 8770        action: &SelectToEndOfLine,
 8771        window: &mut Window,
 8772        cx: &mut Context<Self>,
 8773    ) {
 8774        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8775            s.move_heads_with(|map, head, _| {
 8776                (
 8777                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8778                    SelectionGoal::None,
 8779                )
 8780            });
 8781        })
 8782    }
 8783
 8784    pub fn delete_to_end_of_line(
 8785        &mut self,
 8786        _: &DeleteToEndOfLine,
 8787        window: &mut Window,
 8788        cx: &mut Context<Self>,
 8789    ) {
 8790        self.transact(window, cx, |this, window, cx| {
 8791            this.select_to_end_of_line(
 8792                &SelectToEndOfLine {
 8793                    stop_at_soft_wraps: false,
 8794                },
 8795                window,
 8796                cx,
 8797            );
 8798            this.delete(&Delete, window, cx);
 8799        });
 8800    }
 8801
 8802    pub fn cut_to_end_of_line(
 8803        &mut self,
 8804        _: &CutToEndOfLine,
 8805        window: &mut Window,
 8806        cx: &mut Context<Self>,
 8807    ) {
 8808        self.transact(window, cx, |this, window, cx| {
 8809            this.select_to_end_of_line(
 8810                &SelectToEndOfLine {
 8811                    stop_at_soft_wraps: false,
 8812                },
 8813                window,
 8814                cx,
 8815            );
 8816            this.cut(&Cut, window, cx);
 8817        });
 8818    }
 8819
 8820    pub fn move_to_start_of_paragraph(
 8821        &mut self,
 8822        _: &MoveToStartOfParagraph,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8827            cx.propagate();
 8828            return;
 8829        }
 8830
 8831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832            s.move_with(|map, selection| {
 8833                selection.collapse_to(
 8834                    movement::start_of_paragraph(map, selection.head(), 1),
 8835                    SelectionGoal::None,
 8836                )
 8837            });
 8838        })
 8839    }
 8840
 8841    pub fn move_to_end_of_paragraph(
 8842        &mut self,
 8843        _: &MoveToEndOfParagraph,
 8844        window: &mut Window,
 8845        cx: &mut Context<Self>,
 8846    ) {
 8847        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8848            cx.propagate();
 8849            return;
 8850        }
 8851
 8852        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8853            s.move_with(|map, selection| {
 8854                selection.collapse_to(
 8855                    movement::end_of_paragraph(map, selection.head(), 1),
 8856                    SelectionGoal::None,
 8857                )
 8858            });
 8859        })
 8860    }
 8861
 8862    pub fn select_to_start_of_paragraph(
 8863        &mut self,
 8864        _: &SelectToStartOfParagraph,
 8865        window: &mut Window,
 8866        cx: &mut Context<Self>,
 8867    ) {
 8868        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8869            cx.propagate();
 8870            return;
 8871        }
 8872
 8873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8874            s.move_heads_with(|map, head, _| {
 8875                (
 8876                    movement::start_of_paragraph(map, head, 1),
 8877                    SelectionGoal::None,
 8878                )
 8879            });
 8880        })
 8881    }
 8882
 8883    pub fn select_to_end_of_paragraph(
 8884        &mut self,
 8885        _: &SelectToEndOfParagraph,
 8886        window: &mut Window,
 8887        cx: &mut Context<Self>,
 8888    ) {
 8889        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8890            cx.propagate();
 8891            return;
 8892        }
 8893
 8894        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8895            s.move_heads_with(|map, head, _| {
 8896                (
 8897                    movement::end_of_paragraph(map, head, 1),
 8898                    SelectionGoal::None,
 8899                )
 8900            });
 8901        })
 8902    }
 8903
 8904    pub fn move_to_beginning(
 8905        &mut self,
 8906        _: &MoveToBeginning,
 8907        window: &mut Window,
 8908        cx: &mut Context<Self>,
 8909    ) {
 8910        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8911            cx.propagate();
 8912            return;
 8913        }
 8914
 8915        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8916            s.select_ranges(vec![0..0]);
 8917        });
 8918    }
 8919
 8920    pub fn select_to_beginning(
 8921        &mut self,
 8922        _: &SelectToBeginning,
 8923        window: &mut Window,
 8924        cx: &mut Context<Self>,
 8925    ) {
 8926        let mut selection = self.selections.last::<Point>(cx);
 8927        selection.set_head(Point::zero(), SelectionGoal::None);
 8928
 8929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8930            s.select(vec![selection]);
 8931        });
 8932    }
 8933
 8934    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8936            cx.propagate();
 8937            return;
 8938        }
 8939
 8940        let cursor = self.buffer.read(cx).read(cx).len();
 8941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8942            s.select_ranges(vec![cursor..cursor])
 8943        });
 8944    }
 8945
 8946    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8947        self.nav_history = nav_history;
 8948    }
 8949
 8950    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8951        self.nav_history.as_ref()
 8952    }
 8953
 8954    fn push_to_nav_history(
 8955        &mut self,
 8956        cursor_anchor: Anchor,
 8957        new_position: Option<Point>,
 8958        cx: &mut Context<Self>,
 8959    ) {
 8960        if let Some(nav_history) = self.nav_history.as_mut() {
 8961            let buffer = self.buffer.read(cx).read(cx);
 8962            let cursor_position = cursor_anchor.to_point(&buffer);
 8963            let scroll_state = self.scroll_manager.anchor();
 8964            let scroll_top_row = scroll_state.top_row(&buffer);
 8965            drop(buffer);
 8966
 8967            if let Some(new_position) = new_position {
 8968                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8969                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8970                    return;
 8971                }
 8972            }
 8973
 8974            nav_history.push(
 8975                Some(NavigationData {
 8976                    cursor_anchor,
 8977                    cursor_position,
 8978                    scroll_anchor: scroll_state,
 8979                    scroll_top_row,
 8980                }),
 8981                cx,
 8982            );
 8983        }
 8984    }
 8985
 8986    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8987        let buffer = self.buffer.read(cx).snapshot(cx);
 8988        let mut selection = self.selections.first::<usize>(cx);
 8989        selection.set_head(buffer.len(), SelectionGoal::None);
 8990        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8991            s.select(vec![selection]);
 8992        });
 8993    }
 8994
 8995    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8996        let end = self.buffer.read(cx).read(cx).len();
 8997        self.change_selections(None, window, cx, |s| {
 8998            s.select_ranges(vec![0..end]);
 8999        });
 9000    }
 9001
 9002    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9003        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9004        let mut selections = self.selections.all::<Point>(cx);
 9005        let max_point = display_map.buffer_snapshot.max_point();
 9006        for selection in &mut selections {
 9007            let rows = selection.spanned_rows(true, &display_map);
 9008            selection.start = Point::new(rows.start.0, 0);
 9009            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9010            selection.reversed = false;
 9011        }
 9012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9013            s.select(selections);
 9014        });
 9015    }
 9016
 9017    pub fn split_selection_into_lines(
 9018        &mut self,
 9019        _: &SplitSelectionIntoLines,
 9020        window: &mut Window,
 9021        cx: &mut Context<Self>,
 9022    ) {
 9023        let mut to_unfold = Vec::new();
 9024        let mut new_selection_ranges = Vec::new();
 9025        {
 9026            let selections = self.selections.all::<Point>(cx);
 9027            let buffer = self.buffer.read(cx).read(cx);
 9028            for selection in selections {
 9029                for row in selection.start.row..selection.end.row {
 9030                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9031                    new_selection_ranges.push(cursor..cursor);
 9032                }
 9033                new_selection_ranges.push(selection.end..selection.end);
 9034                to_unfold.push(selection.start..selection.end);
 9035            }
 9036        }
 9037        self.unfold_ranges(&to_unfold, true, true, cx);
 9038        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9039            s.select_ranges(new_selection_ranges);
 9040        });
 9041    }
 9042
 9043    pub fn add_selection_above(
 9044        &mut self,
 9045        _: &AddSelectionAbove,
 9046        window: &mut Window,
 9047        cx: &mut Context<Self>,
 9048    ) {
 9049        self.add_selection(true, window, cx);
 9050    }
 9051
 9052    pub fn add_selection_below(
 9053        &mut self,
 9054        _: &AddSelectionBelow,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        self.add_selection(false, window, cx);
 9059    }
 9060
 9061    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9062        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9063        let mut selections = self.selections.all::<Point>(cx);
 9064        let text_layout_details = self.text_layout_details(window);
 9065        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9066            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9067            let range = oldest_selection.display_range(&display_map).sorted();
 9068
 9069            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9070            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9071            let positions = start_x.min(end_x)..start_x.max(end_x);
 9072
 9073            selections.clear();
 9074            let mut stack = Vec::new();
 9075            for row in range.start.row().0..=range.end.row().0 {
 9076                if let Some(selection) = self.selections.build_columnar_selection(
 9077                    &display_map,
 9078                    DisplayRow(row),
 9079                    &positions,
 9080                    oldest_selection.reversed,
 9081                    &text_layout_details,
 9082                ) {
 9083                    stack.push(selection.id);
 9084                    selections.push(selection);
 9085                }
 9086            }
 9087
 9088            if above {
 9089                stack.reverse();
 9090            }
 9091
 9092            AddSelectionsState { above, stack }
 9093        });
 9094
 9095        let last_added_selection = *state.stack.last().unwrap();
 9096        let mut new_selections = Vec::new();
 9097        if above == state.above {
 9098            let end_row = if above {
 9099                DisplayRow(0)
 9100            } else {
 9101                display_map.max_point().row()
 9102            };
 9103
 9104            'outer: for selection in selections {
 9105                if selection.id == last_added_selection {
 9106                    let range = selection.display_range(&display_map).sorted();
 9107                    debug_assert_eq!(range.start.row(), range.end.row());
 9108                    let mut row = range.start.row();
 9109                    let positions =
 9110                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9111                            px(start)..px(end)
 9112                        } else {
 9113                            let start_x =
 9114                                display_map.x_for_display_point(range.start, &text_layout_details);
 9115                            let end_x =
 9116                                display_map.x_for_display_point(range.end, &text_layout_details);
 9117                            start_x.min(end_x)..start_x.max(end_x)
 9118                        };
 9119
 9120                    while row != end_row {
 9121                        if above {
 9122                            row.0 -= 1;
 9123                        } else {
 9124                            row.0 += 1;
 9125                        }
 9126
 9127                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9128                            &display_map,
 9129                            row,
 9130                            &positions,
 9131                            selection.reversed,
 9132                            &text_layout_details,
 9133                        ) {
 9134                            state.stack.push(new_selection.id);
 9135                            if above {
 9136                                new_selections.push(new_selection);
 9137                                new_selections.push(selection);
 9138                            } else {
 9139                                new_selections.push(selection);
 9140                                new_selections.push(new_selection);
 9141                            }
 9142
 9143                            continue 'outer;
 9144                        }
 9145                    }
 9146                }
 9147
 9148                new_selections.push(selection);
 9149            }
 9150        } else {
 9151            new_selections = selections;
 9152            new_selections.retain(|s| s.id != last_added_selection);
 9153            state.stack.pop();
 9154        }
 9155
 9156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9157            s.select(new_selections);
 9158        });
 9159        if state.stack.len() > 1 {
 9160            self.add_selections_state = Some(state);
 9161        }
 9162    }
 9163
 9164    pub fn select_next_match_internal(
 9165        &mut self,
 9166        display_map: &DisplaySnapshot,
 9167        replace_newest: bool,
 9168        autoscroll: Option<Autoscroll>,
 9169        window: &mut Window,
 9170        cx: &mut Context<Self>,
 9171    ) -> Result<()> {
 9172        fn select_next_match_ranges(
 9173            this: &mut Editor,
 9174            range: Range<usize>,
 9175            replace_newest: bool,
 9176            auto_scroll: Option<Autoscroll>,
 9177            window: &mut Window,
 9178            cx: &mut Context<Editor>,
 9179        ) {
 9180            this.unfold_ranges(&[range.clone()], false, true, cx);
 9181            this.change_selections(auto_scroll, window, cx, |s| {
 9182                if replace_newest {
 9183                    s.delete(s.newest_anchor().id);
 9184                }
 9185                s.insert_range(range.clone());
 9186            });
 9187        }
 9188
 9189        let buffer = &display_map.buffer_snapshot;
 9190        let mut selections = self.selections.all::<usize>(cx);
 9191        if let Some(mut select_next_state) = self.select_next_state.take() {
 9192            let query = &select_next_state.query;
 9193            if !select_next_state.done {
 9194                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9195                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9196                let mut next_selected_range = None;
 9197
 9198                let bytes_after_last_selection =
 9199                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9200                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9201                let query_matches = query
 9202                    .stream_find_iter(bytes_after_last_selection)
 9203                    .map(|result| (last_selection.end, result))
 9204                    .chain(
 9205                        query
 9206                            .stream_find_iter(bytes_before_first_selection)
 9207                            .map(|result| (0, result)),
 9208                    );
 9209
 9210                for (start_offset, query_match) in query_matches {
 9211                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9212                    let offset_range =
 9213                        start_offset + query_match.start()..start_offset + query_match.end();
 9214                    let display_range = offset_range.start.to_display_point(display_map)
 9215                        ..offset_range.end.to_display_point(display_map);
 9216
 9217                    if !select_next_state.wordwise
 9218                        || (!movement::is_inside_word(display_map, display_range.start)
 9219                            && !movement::is_inside_word(display_map, display_range.end))
 9220                    {
 9221                        // TODO: This is n^2, because we might check all the selections
 9222                        if !selections
 9223                            .iter()
 9224                            .any(|selection| selection.range().overlaps(&offset_range))
 9225                        {
 9226                            next_selected_range = Some(offset_range);
 9227                            break;
 9228                        }
 9229                    }
 9230                }
 9231
 9232                if let Some(next_selected_range) = next_selected_range {
 9233                    select_next_match_ranges(
 9234                        self,
 9235                        next_selected_range,
 9236                        replace_newest,
 9237                        autoscroll,
 9238                        window,
 9239                        cx,
 9240                    );
 9241                } else {
 9242                    select_next_state.done = true;
 9243                }
 9244            }
 9245
 9246            self.select_next_state = Some(select_next_state);
 9247        } else {
 9248            let mut only_carets = true;
 9249            let mut same_text_selected = true;
 9250            let mut selected_text = None;
 9251
 9252            let mut selections_iter = selections.iter().peekable();
 9253            while let Some(selection) = selections_iter.next() {
 9254                if selection.start != selection.end {
 9255                    only_carets = false;
 9256                }
 9257
 9258                if same_text_selected {
 9259                    if selected_text.is_none() {
 9260                        selected_text =
 9261                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9262                    }
 9263
 9264                    if let Some(next_selection) = selections_iter.peek() {
 9265                        if next_selection.range().len() == selection.range().len() {
 9266                            let next_selected_text = buffer
 9267                                .text_for_range(next_selection.range())
 9268                                .collect::<String>();
 9269                            if Some(next_selected_text) != selected_text {
 9270                                same_text_selected = false;
 9271                                selected_text = None;
 9272                            }
 9273                        } else {
 9274                            same_text_selected = false;
 9275                            selected_text = None;
 9276                        }
 9277                    }
 9278                }
 9279            }
 9280
 9281            if only_carets {
 9282                for selection in &mut selections {
 9283                    let word_range = movement::surrounding_word(
 9284                        display_map,
 9285                        selection.start.to_display_point(display_map),
 9286                    );
 9287                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9288                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9289                    selection.goal = SelectionGoal::None;
 9290                    selection.reversed = false;
 9291                    select_next_match_ranges(
 9292                        self,
 9293                        selection.start..selection.end,
 9294                        replace_newest,
 9295                        autoscroll,
 9296                        window,
 9297                        cx,
 9298                    );
 9299                }
 9300
 9301                if selections.len() == 1 {
 9302                    let selection = selections
 9303                        .last()
 9304                        .expect("ensured that there's only one selection");
 9305                    let query = buffer
 9306                        .text_for_range(selection.start..selection.end)
 9307                        .collect::<String>();
 9308                    let is_empty = query.is_empty();
 9309                    let select_state = SelectNextState {
 9310                        query: AhoCorasick::new(&[query])?,
 9311                        wordwise: true,
 9312                        done: is_empty,
 9313                    };
 9314                    self.select_next_state = Some(select_state);
 9315                } else {
 9316                    self.select_next_state = None;
 9317                }
 9318            } else if let Some(selected_text) = selected_text {
 9319                self.select_next_state = Some(SelectNextState {
 9320                    query: AhoCorasick::new(&[selected_text])?,
 9321                    wordwise: false,
 9322                    done: false,
 9323                });
 9324                self.select_next_match_internal(
 9325                    display_map,
 9326                    replace_newest,
 9327                    autoscroll,
 9328                    window,
 9329                    cx,
 9330                )?;
 9331            }
 9332        }
 9333        Ok(())
 9334    }
 9335
 9336    pub fn select_all_matches(
 9337        &mut self,
 9338        _action: &SelectAllMatches,
 9339        window: &mut Window,
 9340        cx: &mut Context<Self>,
 9341    ) -> Result<()> {
 9342        self.push_to_selection_history();
 9343        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9344
 9345        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9346        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9347            return Ok(());
 9348        };
 9349        if select_next_state.done {
 9350            return Ok(());
 9351        }
 9352
 9353        let mut new_selections = self.selections.all::<usize>(cx);
 9354
 9355        let buffer = &display_map.buffer_snapshot;
 9356        let query_matches = select_next_state
 9357            .query
 9358            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9359
 9360        for query_match in query_matches {
 9361            let query_match = query_match.unwrap(); // can only fail due to I/O
 9362            let offset_range = query_match.start()..query_match.end();
 9363            let display_range = offset_range.start.to_display_point(&display_map)
 9364                ..offset_range.end.to_display_point(&display_map);
 9365
 9366            if !select_next_state.wordwise
 9367                || (!movement::is_inside_word(&display_map, display_range.start)
 9368                    && !movement::is_inside_word(&display_map, display_range.end))
 9369            {
 9370                self.selections.change_with(cx, |selections| {
 9371                    new_selections.push(Selection {
 9372                        id: selections.new_selection_id(),
 9373                        start: offset_range.start,
 9374                        end: offset_range.end,
 9375                        reversed: false,
 9376                        goal: SelectionGoal::None,
 9377                    });
 9378                });
 9379            }
 9380        }
 9381
 9382        new_selections.sort_by_key(|selection| selection.start);
 9383        let mut ix = 0;
 9384        while ix + 1 < new_selections.len() {
 9385            let current_selection = &new_selections[ix];
 9386            let next_selection = &new_selections[ix + 1];
 9387            if current_selection.range().overlaps(&next_selection.range()) {
 9388                if current_selection.id < next_selection.id {
 9389                    new_selections.remove(ix + 1);
 9390                } else {
 9391                    new_selections.remove(ix);
 9392                }
 9393            } else {
 9394                ix += 1;
 9395            }
 9396        }
 9397
 9398        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9399
 9400        for selection in new_selections.iter_mut() {
 9401            selection.reversed = reversed;
 9402        }
 9403
 9404        select_next_state.done = true;
 9405        self.unfold_ranges(
 9406            &new_selections
 9407                .iter()
 9408                .map(|selection| selection.range())
 9409                .collect::<Vec<_>>(),
 9410            false,
 9411            false,
 9412            cx,
 9413        );
 9414        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9415            selections.select(new_selections)
 9416        });
 9417
 9418        Ok(())
 9419    }
 9420
 9421    pub fn select_next(
 9422        &mut self,
 9423        action: &SelectNext,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) -> Result<()> {
 9427        self.push_to_selection_history();
 9428        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9429        self.select_next_match_internal(
 9430            &display_map,
 9431            action.replace_newest,
 9432            Some(Autoscroll::newest()),
 9433            window,
 9434            cx,
 9435        )?;
 9436        Ok(())
 9437    }
 9438
 9439    pub fn select_previous(
 9440        &mut self,
 9441        action: &SelectPrevious,
 9442        window: &mut Window,
 9443        cx: &mut Context<Self>,
 9444    ) -> Result<()> {
 9445        self.push_to_selection_history();
 9446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9447        let buffer = &display_map.buffer_snapshot;
 9448        let mut selections = self.selections.all::<usize>(cx);
 9449        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9450            let query = &select_prev_state.query;
 9451            if !select_prev_state.done {
 9452                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9453                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9454                let mut next_selected_range = None;
 9455                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9456                let bytes_before_last_selection =
 9457                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9458                let bytes_after_first_selection =
 9459                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9460                let query_matches = query
 9461                    .stream_find_iter(bytes_before_last_selection)
 9462                    .map(|result| (last_selection.start, result))
 9463                    .chain(
 9464                        query
 9465                            .stream_find_iter(bytes_after_first_selection)
 9466                            .map(|result| (buffer.len(), result)),
 9467                    );
 9468                for (end_offset, query_match) in query_matches {
 9469                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9470                    let offset_range =
 9471                        end_offset - query_match.end()..end_offset - query_match.start();
 9472                    let display_range = offset_range.start.to_display_point(&display_map)
 9473                        ..offset_range.end.to_display_point(&display_map);
 9474
 9475                    if !select_prev_state.wordwise
 9476                        || (!movement::is_inside_word(&display_map, display_range.start)
 9477                            && !movement::is_inside_word(&display_map, display_range.end))
 9478                    {
 9479                        next_selected_range = Some(offset_range);
 9480                        break;
 9481                    }
 9482                }
 9483
 9484                if let Some(next_selected_range) = next_selected_range {
 9485                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9486                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9487                        if action.replace_newest {
 9488                            s.delete(s.newest_anchor().id);
 9489                        }
 9490                        s.insert_range(next_selected_range);
 9491                    });
 9492                } else {
 9493                    select_prev_state.done = true;
 9494                }
 9495            }
 9496
 9497            self.select_prev_state = Some(select_prev_state);
 9498        } else {
 9499            let mut only_carets = true;
 9500            let mut same_text_selected = true;
 9501            let mut selected_text = None;
 9502
 9503            let mut selections_iter = selections.iter().peekable();
 9504            while let Some(selection) = selections_iter.next() {
 9505                if selection.start != selection.end {
 9506                    only_carets = false;
 9507                }
 9508
 9509                if same_text_selected {
 9510                    if selected_text.is_none() {
 9511                        selected_text =
 9512                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9513                    }
 9514
 9515                    if let Some(next_selection) = selections_iter.peek() {
 9516                        if next_selection.range().len() == selection.range().len() {
 9517                            let next_selected_text = buffer
 9518                                .text_for_range(next_selection.range())
 9519                                .collect::<String>();
 9520                            if Some(next_selected_text) != selected_text {
 9521                                same_text_selected = false;
 9522                                selected_text = None;
 9523                            }
 9524                        } else {
 9525                            same_text_selected = false;
 9526                            selected_text = None;
 9527                        }
 9528                    }
 9529                }
 9530            }
 9531
 9532            if only_carets {
 9533                for selection in &mut selections {
 9534                    let word_range = movement::surrounding_word(
 9535                        &display_map,
 9536                        selection.start.to_display_point(&display_map),
 9537                    );
 9538                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9539                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9540                    selection.goal = SelectionGoal::None;
 9541                    selection.reversed = false;
 9542                }
 9543                if selections.len() == 1 {
 9544                    let selection = selections
 9545                        .last()
 9546                        .expect("ensured that there's only one selection");
 9547                    let query = buffer
 9548                        .text_for_range(selection.start..selection.end)
 9549                        .collect::<String>();
 9550                    let is_empty = query.is_empty();
 9551                    let select_state = SelectNextState {
 9552                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9553                        wordwise: true,
 9554                        done: is_empty,
 9555                    };
 9556                    self.select_prev_state = Some(select_state);
 9557                } else {
 9558                    self.select_prev_state = None;
 9559                }
 9560
 9561                self.unfold_ranges(
 9562                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9563                    false,
 9564                    true,
 9565                    cx,
 9566                );
 9567                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9568                    s.select(selections);
 9569                });
 9570            } else if let Some(selected_text) = selected_text {
 9571                self.select_prev_state = Some(SelectNextState {
 9572                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9573                    wordwise: false,
 9574                    done: false,
 9575                });
 9576                self.select_previous(action, window, cx)?;
 9577            }
 9578        }
 9579        Ok(())
 9580    }
 9581
 9582    pub fn toggle_comments(
 9583        &mut self,
 9584        action: &ToggleComments,
 9585        window: &mut Window,
 9586        cx: &mut Context<Self>,
 9587    ) {
 9588        if self.read_only(cx) {
 9589            return;
 9590        }
 9591        let text_layout_details = &self.text_layout_details(window);
 9592        self.transact(window, cx, |this, window, cx| {
 9593            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9594            let mut edits = Vec::new();
 9595            let mut selection_edit_ranges = Vec::new();
 9596            let mut last_toggled_row = None;
 9597            let snapshot = this.buffer.read(cx).read(cx);
 9598            let empty_str: Arc<str> = Arc::default();
 9599            let mut suffixes_inserted = Vec::new();
 9600            let ignore_indent = action.ignore_indent;
 9601
 9602            fn comment_prefix_range(
 9603                snapshot: &MultiBufferSnapshot,
 9604                row: MultiBufferRow,
 9605                comment_prefix: &str,
 9606                comment_prefix_whitespace: &str,
 9607                ignore_indent: bool,
 9608            ) -> Range<Point> {
 9609                let indent_size = if ignore_indent {
 9610                    0
 9611                } else {
 9612                    snapshot.indent_size_for_line(row).len
 9613                };
 9614
 9615                let start = Point::new(row.0, indent_size);
 9616
 9617                let mut line_bytes = snapshot
 9618                    .bytes_in_range(start..snapshot.max_point())
 9619                    .flatten()
 9620                    .copied();
 9621
 9622                // If this line currently begins with the line comment prefix, then record
 9623                // the range containing the prefix.
 9624                if line_bytes
 9625                    .by_ref()
 9626                    .take(comment_prefix.len())
 9627                    .eq(comment_prefix.bytes())
 9628                {
 9629                    // Include any whitespace that matches the comment prefix.
 9630                    let matching_whitespace_len = line_bytes
 9631                        .zip(comment_prefix_whitespace.bytes())
 9632                        .take_while(|(a, b)| a == b)
 9633                        .count() as u32;
 9634                    let end = Point::new(
 9635                        start.row,
 9636                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9637                    );
 9638                    start..end
 9639                } else {
 9640                    start..start
 9641                }
 9642            }
 9643
 9644            fn comment_suffix_range(
 9645                snapshot: &MultiBufferSnapshot,
 9646                row: MultiBufferRow,
 9647                comment_suffix: &str,
 9648                comment_suffix_has_leading_space: bool,
 9649            ) -> Range<Point> {
 9650                let end = Point::new(row.0, snapshot.line_len(row));
 9651                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9652
 9653                let mut line_end_bytes = snapshot
 9654                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9655                    .flatten()
 9656                    .copied();
 9657
 9658                let leading_space_len = if suffix_start_column > 0
 9659                    && line_end_bytes.next() == Some(b' ')
 9660                    && comment_suffix_has_leading_space
 9661                {
 9662                    1
 9663                } else {
 9664                    0
 9665                };
 9666
 9667                // If this line currently begins with the line comment prefix, then record
 9668                // the range containing the prefix.
 9669                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9670                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9671                    start..end
 9672                } else {
 9673                    end..end
 9674                }
 9675            }
 9676
 9677            // TODO: Handle selections that cross excerpts
 9678            for selection in &mut selections {
 9679                let start_column = snapshot
 9680                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9681                    .len;
 9682                let language = if let Some(language) =
 9683                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9684                {
 9685                    language
 9686                } else {
 9687                    continue;
 9688                };
 9689
 9690                selection_edit_ranges.clear();
 9691
 9692                // If multiple selections contain a given row, avoid processing that
 9693                // row more than once.
 9694                let mut start_row = MultiBufferRow(selection.start.row);
 9695                if last_toggled_row == Some(start_row) {
 9696                    start_row = start_row.next_row();
 9697                }
 9698                let end_row =
 9699                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9700                        MultiBufferRow(selection.end.row - 1)
 9701                    } else {
 9702                        MultiBufferRow(selection.end.row)
 9703                    };
 9704                last_toggled_row = Some(end_row);
 9705
 9706                if start_row > end_row {
 9707                    continue;
 9708                }
 9709
 9710                // If the language has line comments, toggle those.
 9711                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9712
 9713                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9714                if ignore_indent {
 9715                    full_comment_prefixes = full_comment_prefixes
 9716                        .into_iter()
 9717                        .map(|s| Arc::from(s.trim_end()))
 9718                        .collect();
 9719                }
 9720
 9721                if !full_comment_prefixes.is_empty() {
 9722                    let first_prefix = full_comment_prefixes
 9723                        .first()
 9724                        .expect("prefixes is non-empty");
 9725                    let prefix_trimmed_lengths = full_comment_prefixes
 9726                        .iter()
 9727                        .map(|p| p.trim_end_matches(' ').len())
 9728                        .collect::<SmallVec<[usize; 4]>>();
 9729
 9730                    let mut all_selection_lines_are_comments = true;
 9731
 9732                    for row in start_row.0..=end_row.0 {
 9733                        let row = MultiBufferRow(row);
 9734                        if start_row < end_row && snapshot.is_line_blank(row) {
 9735                            continue;
 9736                        }
 9737
 9738                        let prefix_range = full_comment_prefixes
 9739                            .iter()
 9740                            .zip(prefix_trimmed_lengths.iter().copied())
 9741                            .map(|(prefix, trimmed_prefix_len)| {
 9742                                comment_prefix_range(
 9743                                    snapshot.deref(),
 9744                                    row,
 9745                                    &prefix[..trimmed_prefix_len],
 9746                                    &prefix[trimmed_prefix_len..],
 9747                                    ignore_indent,
 9748                                )
 9749                            })
 9750                            .max_by_key(|range| range.end.column - range.start.column)
 9751                            .expect("prefixes is non-empty");
 9752
 9753                        if prefix_range.is_empty() {
 9754                            all_selection_lines_are_comments = false;
 9755                        }
 9756
 9757                        selection_edit_ranges.push(prefix_range);
 9758                    }
 9759
 9760                    if all_selection_lines_are_comments {
 9761                        edits.extend(
 9762                            selection_edit_ranges
 9763                                .iter()
 9764                                .cloned()
 9765                                .map(|range| (range, empty_str.clone())),
 9766                        );
 9767                    } else {
 9768                        let min_column = selection_edit_ranges
 9769                            .iter()
 9770                            .map(|range| range.start.column)
 9771                            .min()
 9772                            .unwrap_or(0);
 9773                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9774                            let position = Point::new(range.start.row, min_column);
 9775                            (position..position, first_prefix.clone())
 9776                        }));
 9777                    }
 9778                } else if let Some((full_comment_prefix, comment_suffix)) =
 9779                    language.block_comment_delimiters()
 9780                {
 9781                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9782                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9783                    let prefix_range = comment_prefix_range(
 9784                        snapshot.deref(),
 9785                        start_row,
 9786                        comment_prefix,
 9787                        comment_prefix_whitespace,
 9788                        ignore_indent,
 9789                    );
 9790                    let suffix_range = comment_suffix_range(
 9791                        snapshot.deref(),
 9792                        end_row,
 9793                        comment_suffix.trim_start_matches(' '),
 9794                        comment_suffix.starts_with(' '),
 9795                    );
 9796
 9797                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9798                        edits.push((
 9799                            prefix_range.start..prefix_range.start,
 9800                            full_comment_prefix.clone(),
 9801                        ));
 9802                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9803                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9804                    } else {
 9805                        edits.push((prefix_range, empty_str.clone()));
 9806                        edits.push((suffix_range, empty_str.clone()));
 9807                    }
 9808                } else {
 9809                    continue;
 9810                }
 9811            }
 9812
 9813            drop(snapshot);
 9814            this.buffer.update(cx, |buffer, cx| {
 9815                buffer.edit(edits, None, cx);
 9816            });
 9817
 9818            // Adjust selections so that they end before any comment suffixes that
 9819            // were inserted.
 9820            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9821            let mut selections = this.selections.all::<Point>(cx);
 9822            let snapshot = this.buffer.read(cx).read(cx);
 9823            for selection in &mut selections {
 9824                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9825                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9826                        Ordering::Less => {
 9827                            suffixes_inserted.next();
 9828                            continue;
 9829                        }
 9830                        Ordering::Greater => break,
 9831                        Ordering::Equal => {
 9832                            if selection.end.column == snapshot.line_len(row) {
 9833                                if selection.is_empty() {
 9834                                    selection.start.column -= suffix_len as u32;
 9835                                }
 9836                                selection.end.column -= suffix_len as u32;
 9837                            }
 9838                            break;
 9839                        }
 9840                    }
 9841                }
 9842            }
 9843
 9844            drop(snapshot);
 9845            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9846                s.select(selections)
 9847            });
 9848
 9849            let selections = this.selections.all::<Point>(cx);
 9850            let selections_on_single_row = selections.windows(2).all(|selections| {
 9851                selections[0].start.row == selections[1].start.row
 9852                    && selections[0].end.row == selections[1].end.row
 9853                    && selections[0].start.row == selections[0].end.row
 9854            });
 9855            let selections_selecting = selections
 9856                .iter()
 9857                .any(|selection| selection.start != selection.end);
 9858            let advance_downwards = action.advance_downwards
 9859                && selections_on_single_row
 9860                && !selections_selecting
 9861                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9862
 9863            if advance_downwards {
 9864                let snapshot = this.buffer.read(cx).snapshot(cx);
 9865
 9866                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9867                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9868                        let mut point = display_point.to_point(display_snapshot);
 9869                        point.row += 1;
 9870                        point = snapshot.clip_point(point, Bias::Left);
 9871                        let display_point = point.to_display_point(display_snapshot);
 9872                        let goal = SelectionGoal::HorizontalPosition(
 9873                            display_snapshot
 9874                                .x_for_display_point(display_point, text_layout_details)
 9875                                .into(),
 9876                        );
 9877                        (display_point, goal)
 9878                    })
 9879                });
 9880            }
 9881        });
 9882    }
 9883
 9884    pub fn select_enclosing_symbol(
 9885        &mut self,
 9886        _: &SelectEnclosingSymbol,
 9887        window: &mut Window,
 9888        cx: &mut Context<Self>,
 9889    ) {
 9890        let buffer = self.buffer.read(cx).snapshot(cx);
 9891        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9892
 9893        fn update_selection(
 9894            selection: &Selection<usize>,
 9895            buffer_snap: &MultiBufferSnapshot,
 9896        ) -> Option<Selection<usize>> {
 9897            let cursor = selection.head();
 9898            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9899            for symbol in symbols.iter().rev() {
 9900                let start = symbol.range.start.to_offset(buffer_snap);
 9901                let end = symbol.range.end.to_offset(buffer_snap);
 9902                let new_range = start..end;
 9903                if start < selection.start || end > selection.end {
 9904                    return Some(Selection {
 9905                        id: selection.id,
 9906                        start: new_range.start,
 9907                        end: new_range.end,
 9908                        goal: SelectionGoal::None,
 9909                        reversed: selection.reversed,
 9910                    });
 9911                }
 9912            }
 9913            None
 9914        }
 9915
 9916        let mut selected_larger_symbol = false;
 9917        let new_selections = old_selections
 9918            .iter()
 9919            .map(|selection| match update_selection(selection, &buffer) {
 9920                Some(new_selection) => {
 9921                    if new_selection.range() != selection.range() {
 9922                        selected_larger_symbol = true;
 9923                    }
 9924                    new_selection
 9925                }
 9926                None => selection.clone(),
 9927            })
 9928            .collect::<Vec<_>>();
 9929
 9930        if selected_larger_symbol {
 9931            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9932                s.select(new_selections);
 9933            });
 9934        }
 9935    }
 9936
 9937    pub fn select_larger_syntax_node(
 9938        &mut self,
 9939        _: &SelectLargerSyntaxNode,
 9940        window: &mut Window,
 9941        cx: &mut Context<Self>,
 9942    ) {
 9943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9944        let buffer = self.buffer.read(cx).snapshot(cx);
 9945        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9946
 9947        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9948        let mut selected_larger_node = false;
 9949        let new_selections = old_selections
 9950            .iter()
 9951            .map(|selection| {
 9952                let old_range = selection.start..selection.end;
 9953                let mut new_range = old_range.clone();
 9954                let mut new_node = None;
 9955                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9956                {
 9957                    new_node = Some(node);
 9958                    new_range = containing_range;
 9959                    if !display_map.intersects_fold(new_range.start)
 9960                        && !display_map.intersects_fold(new_range.end)
 9961                    {
 9962                        break;
 9963                    }
 9964                }
 9965
 9966                if let Some(node) = new_node {
 9967                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9968                    // nodes. Parent and grandparent are also logged because this operation will not
 9969                    // visit nodes that have the same range as their parent.
 9970                    log::info!("Node: {node:?}");
 9971                    let parent = node.parent();
 9972                    log::info!("Parent: {parent:?}");
 9973                    let grandparent = parent.and_then(|x| x.parent());
 9974                    log::info!("Grandparent: {grandparent:?}");
 9975                }
 9976
 9977                selected_larger_node |= new_range != old_range;
 9978                Selection {
 9979                    id: selection.id,
 9980                    start: new_range.start,
 9981                    end: new_range.end,
 9982                    goal: SelectionGoal::None,
 9983                    reversed: selection.reversed,
 9984                }
 9985            })
 9986            .collect::<Vec<_>>();
 9987
 9988        if selected_larger_node {
 9989            stack.push(old_selections);
 9990            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9991                s.select(new_selections);
 9992            });
 9993        }
 9994        self.select_larger_syntax_node_stack = stack;
 9995    }
 9996
 9997    pub fn select_smaller_syntax_node(
 9998        &mut self,
 9999        _: &SelectSmallerSyntaxNode,
10000        window: &mut Window,
10001        cx: &mut Context<Self>,
10002    ) {
10003        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10004        if let Some(selections) = stack.pop() {
10005            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10006                s.select(selections.to_vec());
10007            });
10008        }
10009        self.select_larger_syntax_node_stack = stack;
10010    }
10011
10012    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10013        if !EditorSettings::get_global(cx).gutter.runnables {
10014            self.clear_tasks();
10015            return Task::ready(());
10016        }
10017        let project = self.project.as_ref().map(Entity::downgrade);
10018        cx.spawn_in(window, |this, mut cx| async move {
10019            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10020            let Some(project) = project.and_then(|p| p.upgrade()) else {
10021                return;
10022            };
10023            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10024                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10025            }) else {
10026                return;
10027            };
10028
10029            let hide_runnables = project
10030                .update(&mut cx, |project, cx| {
10031                    // Do not display any test indicators in non-dev server remote projects.
10032                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10033                })
10034                .unwrap_or(true);
10035            if hide_runnables {
10036                return;
10037            }
10038            let new_rows =
10039                cx.background_executor()
10040                    .spawn({
10041                        let snapshot = display_snapshot.clone();
10042                        async move {
10043                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10044                        }
10045                    })
10046                    .await;
10047
10048            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10049            this.update(&mut cx, |this, _| {
10050                this.clear_tasks();
10051                for (key, value) in rows {
10052                    this.insert_tasks(key, value);
10053                }
10054            })
10055            .ok();
10056        })
10057    }
10058    fn fetch_runnable_ranges(
10059        snapshot: &DisplaySnapshot,
10060        range: Range<Anchor>,
10061    ) -> Vec<language::RunnableRange> {
10062        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10063    }
10064
10065    fn runnable_rows(
10066        project: Entity<Project>,
10067        snapshot: DisplaySnapshot,
10068        runnable_ranges: Vec<RunnableRange>,
10069        mut cx: AsyncWindowContext,
10070    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10071        runnable_ranges
10072            .into_iter()
10073            .filter_map(|mut runnable| {
10074                let tasks = cx
10075                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10076                    .ok()?;
10077                if tasks.is_empty() {
10078                    return None;
10079                }
10080
10081                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10082
10083                let row = snapshot
10084                    .buffer_snapshot
10085                    .buffer_line_for_row(MultiBufferRow(point.row))?
10086                    .1
10087                    .start
10088                    .row;
10089
10090                let context_range =
10091                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10092                Some((
10093                    (runnable.buffer_id, row),
10094                    RunnableTasks {
10095                        templates: tasks,
10096                        offset: MultiBufferOffset(runnable.run_range.start),
10097                        context_range,
10098                        column: point.column,
10099                        extra_variables: runnable.extra_captures,
10100                    },
10101                ))
10102            })
10103            .collect()
10104    }
10105
10106    fn templates_with_tags(
10107        project: &Entity<Project>,
10108        runnable: &mut Runnable,
10109        cx: &mut App,
10110    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10111        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10112            let (worktree_id, file) = project
10113                .buffer_for_id(runnable.buffer, cx)
10114                .and_then(|buffer| buffer.read(cx).file())
10115                .map(|file| (file.worktree_id(cx), file.clone()))
10116                .unzip();
10117
10118            (
10119                project.task_store().read(cx).task_inventory().cloned(),
10120                worktree_id,
10121                file,
10122            )
10123        });
10124
10125        let tags = mem::take(&mut runnable.tags);
10126        let mut tags: Vec<_> = tags
10127            .into_iter()
10128            .flat_map(|tag| {
10129                let tag = tag.0.clone();
10130                inventory
10131                    .as_ref()
10132                    .into_iter()
10133                    .flat_map(|inventory| {
10134                        inventory.read(cx).list_tasks(
10135                            file.clone(),
10136                            Some(runnable.language.clone()),
10137                            worktree_id,
10138                            cx,
10139                        )
10140                    })
10141                    .filter(move |(_, template)| {
10142                        template.tags.iter().any(|source_tag| source_tag == &tag)
10143                    })
10144            })
10145            .sorted_by_key(|(kind, _)| kind.to_owned())
10146            .collect();
10147        if let Some((leading_tag_source, _)) = tags.first() {
10148            // Strongest source wins; if we have worktree tag binding, prefer that to
10149            // global and language bindings;
10150            // if we have a global binding, prefer that to language binding.
10151            let first_mismatch = tags
10152                .iter()
10153                .position(|(tag_source, _)| tag_source != leading_tag_source);
10154            if let Some(index) = first_mismatch {
10155                tags.truncate(index);
10156            }
10157        }
10158
10159        tags
10160    }
10161
10162    pub fn move_to_enclosing_bracket(
10163        &mut self,
10164        _: &MoveToEnclosingBracket,
10165        window: &mut Window,
10166        cx: &mut Context<Self>,
10167    ) {
10168        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10169            s.move_offsets_with(|snapshot, selection| {
10170                let Some(enclosing_bracket_ranges) =
10171                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10172                else {
10173                    return;
10174                };
10175
10176                let mut best_length = usize::MAX;
10177                let mut best_inside = false;
10178                let mut best_in_bracket_range = false;
10179                let mut best_destination = None;
10180                for (open, close) in enclosing_bracket_ranges {
10181                    let close = close.to_inclusive();
10182                    let length = close.end() - open.start;
10183                    let inside = selection.start >= open.end && selection.end <= *close.start();
10184                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10185                        || close.contains(&selection.head());
10186
10187                    // If best is next to a bracket and current isn't, skip
10188                    if !in_bracket_range && best_in_bracket_range {
10189                        continue;
10190                    }
10191
10192                    // Prefer smaller lengths unless best is inside and current isn't
10193                    if length > best_length && (best_inside || !inside) {
10194                        continue;
10195                    }
10196
10197                    best_length = length;
10198                    best_inside = inside;
10199                    best_in_bracket_range = in_bracket_range;
10200                    best_destination = Some(
10201                        if close.contains(&selection.start) && close.contains(&selection.end) {
10202                            if inside {
10203                                open.end
10204                            } else {
10205                                open.start
10206                            }
10207                        } else if inside {
10208                            *close.start()
10209                        } else {
10210                            *close.end()
10211                        },
10212                    );
10213                }
10214
10215                if let Some(destination) = best_destination {
10216                    selection.collapse_to(destination, SelectionGoal::None);
10217                }
10218            })
10219        });
10220    }
10221
10222    pub fn undo_selection(
10223        &mut self,
10224        _: &UndoSelection,
10225        window: &mut Window,
10226        cx: &mut Context<Self>,
10227    ) {
10228        self.end_selection(window, cx);
10229        self.selection_history.mode = SelectionHistoryMode::Undoing;
10230        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10231            self.change_selections(None, window, cx, |s| {
10232                s.select_anchors(entry.selections.to_vec())
10233            });
10234            self.select_next_state = entry.select_next_state;
10235            self.select_prev_state = entry.select_prev_state;
10236            self.add_selections_state = entry.add_selections_state;
10237            self.request_autoscroll(Autoscroll::newest(), cx);
10238        }
10239        self.selection_history.mode = SelectionHistoryMode::Normal;
10240    }
10241
10242    pub fn redo_selection(
10243        &mut self,
10244        _: &RedoSelection,
10245        window: &mut Window,
10246        cx: &mut Context<Self>,
10247    ) {
10248        self.end_selection(window, cx);
10249        self.selection_history.mode = SelectionHistoryMode::Redoing;
10250        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10251            self.change_selections(None, window, cx, |s| {
10252                s.select_anchors(entry.selections.to_vec())
10253            });
10254            self.select_next_state = entry.select_next_state;
10255            self.select_prev_state = entry.select_prev_state;
10256            self.add_selections_state = entry.add_selections_state;
10257            self.request_autoscroll(Autoscroll::newest(), cx);
10258        }
10259        self.selection_history.mode = SelectionHistoryMode::Normal;
10260    }
10261
10262    pub fn expand_excerpts(
10263        &mut self,
10264        action: &ExpandExcerpts,
10265        _: &mut Window,
10266        cx: &mut Context<Self>,
10267    ) {
10268        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10269    }
10270
10271    pub fn expand_excerpts_down(
10272        &mut self,
10273        action: &ExpandExcerptsDown,
10274        _: &mut Window,
10275        cx: &mut Context<Self>,
10276    ) {
10277        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10278    }
10279
10280    pub fn expand_excerpts_up(
10281        &mut self,
10282        action: &ExpandExcerptsUp,
10283        _: &mut Window,
10284        cx: &mut Context<Self>,
10285    ) {
10286        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10287    }
10288
10289    pub fn expand_excerpts_for_direction(
10290        &mut self,
10291        lines: u32,
10292        direction: ExpandExcerptDirection,
10293
10294        cx: &mut Context<Self>,
10295    ) {
10296        let selections = self.selections.disjoint_anchors();
10297
10298        let lines = if lines == 0 {
10299            EditorSettings::get_global(cx).expand_excerpt_lines
10300        } else {
10301            lines
10302        };
10303
10304        self.buffer.update(cx, |buffer, cx| {
10305            let snapshot = buffer.snapshot(cx);
10306            let mut excerpt_ids = selections
10307                .iter()
10308                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10309                .collect::<Vec<_>>();
10310            excerpt_ids.sort();
10311            excerpt_ids.dedup();
10312            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10313        })
10314    }
10315
10316    pub fn expand_excerpt(
10317        &mut self,
10318        excerpt: ExcerptId,
10319        direction: ExpandExcerptDirection,
10320        cx: &mut Context<Self>,
10321    ) {
10322        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10323        self.buffer.update(cx, |buffer, cx| {
10324            buffer.expand_excerpts([excerpt], lines, direction, cx)
10325        })
10326    }
10327
10328    pub fn go_to_singleton_buffer_point(
10329        &mut self,
10330        point: Point,
10331        window: &mut Window,
10332        cx: &mut Context<Self>,
10333    ) {
10334        self.go_to_singleton_buffer_range(point..point, window, cx);
10335    }
10336
10337    pub fn go_to_singleton_buffer_range(
10338        &mut self,
10339        range: Range<Point>,
10340        window: &mut Window,
10341        cx: &mut Context<Self>,
10342    ) {
10343        let multibuffer = self.buffer().read(cx);
10344        let Some(buffer) = multibuffer.as_singleton() else {
10345            return;
10346        };
10347        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10348            return;
10349        };
10350        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10351            return;
10352        };
10353        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10354            s.select_anchor_ranges([start..end])
10355        });
10356    }
10357
10358    fn go_to_diagnostic(
10359        &mut self,
10360        _: &GoToDiagnostic,
10361        window: &mut Window,
10362        cx: &mut Context<Self>,
10363    ) {
10364        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10365    }
10366
10367    fn go_to_prev_diagnostic(
10368        &mut self,
10369        _: &GoToPrevDiagnostic,
10370        window: &mut Window,
10371        cx: &mut Context<Self>,
10372    ) {
10373        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10374    }
10375
10376    pub fn go_to_diagnostic_impl(
10377        &mut self,
10378        direction: Direction,
10379        window: &mut Window,
10380        cx: &mut Context<Self>,
10381    ) {
10382        let buffer = self.buffer.read(cx).snapshot(cx);
10383        let selection = self.selections.newest::<usize>(cx);
10384
10385        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10386        if direction == Direction::Next {
10387            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10388                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10389                    return;
10390                };
10391                self.activate_diagnostics(
10392                    buffer_id,
10393                    popover.local_diagnostic.diagnostic.group_id,
10394                    window,
10395                    cx,
10396                );
10397                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10398                    let primary_range_start = active_diagnostics.primary_range.start;
10399                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10400                        let mut new_selection = s.newest_anchor().clone();
10401                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10402                        s.select_anchors(vec![new_selection.clone()]);
10403                    });
10404                    self.refresh_inline_completion(false, true, window, cx);
10405                }
10406                return;
10407            }
10408        }
10409
10410        let active_group_id = self
10411            .active_diagnostics
10412            .as_ref()
10413            .map(|active_group| active_group.group_id);
10414        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10415            active_diagnostics
10416                .primary_range
10417                .to_offset(&buffer)
10418                .to_inclusive()
10419        });
10420        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10421            if active_primary_range.contains(&selection.head()) {
10422                *active_primary_range.start()
10423            } else {
10424                selection.head()
10425            }
10426        } else {
10427            selection.head()
10428        };
10429
10430        let snapshot = self.snapshot(window, cx);
10431        let primary_diagnostics_before = buffer
10432            .diagnostics_in_range::<usize>(0..search_start)
10433            .filter(|entry| entry.diagnostic.is_primary)
10434            .filter(|entry| entry.range.start != entry.range.end)
10435            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10436            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10437            .collect::<Vec<_>>();
10438        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10439            primary_diagnostics_before
10440                .iter()
10441                .position(|entry| entry.diagnostic.group_id == active_group_id)
10442        });
10443
10444        let primary_diagnostics_after = buffer
10445            .diagnostics_in_range::<usize>(search_start..buffer.len())
10446            .filter(|entry| entry.diagnostic.is_primary)
10447            .filter(|entry| entry.range.start != entry.range.end)
10448            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10449            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10450            .collect::<Vec<_>>();
10451        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10452            primary_diagnostics_after
10453                .iter()
10454                .enumerate()
10455                .rev()
10456                .find_map(|(i, entry)| {
10457                    if entry.diagnostic.group_id == active_group_id {
10458                        Some(i)
10459                    } else {
10460                        None
10461                    }
10462                })
10463        });
10464
10465        let next_primary_diagnostic = match direction {
10466            Direction::Prev => primary_diagnostics_before
10467                .iter()
10468                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10469                .rev()
10470                .next(),
10471            Direction::Next => primary_diagnostics_after
10472                .iter()
10473                .skip(
10474                    last_same_group_diagnostic_after
10475                        .map(|index| index + 1)
10476                        .unwrap_or(0),
10477                )
10478                .next(),
10479        };
10480
10481        // Cycle around to the start of the buffer, potentially moving back to the start of
10482        // the currently active diagnostic.
10483        let cycle_around = || match direction {
10484            Direction::Prev => primary_diagnostics_after
10485                .iter()
10486                .rev()
10487                .chain(primary_diagnostics_before.iter().rev())
10488                .next(),
10489            Direction::Next => primary_diagnostics_before
10490                .iter()
10491                .chain(primary_diagnostics_after.iter())
10492                .next(),
10493        };
10494
10495        if let Some((primary_range, group_id)) = next_primary_diagnostic
10496            .or_else(cycle_around)
10497            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10498        {
10499            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10500                return;
10501            };
10502            self.activate_diagnostics(buffer_id, group_id, window, cx);
10503            if self.active_diagnostics.is_some() {
10504                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10505                    s.select(vec![Selection {
10506                        id: selection.id,
10507                        start: primary_range.start,
10508                        end: primary_range.start,
10509                        reversed: false,
10510                        goal: SelectionGoal::None,
10511                    }]);
10512                });
10513                self.refresh_inline_completion(false, true, window, cx);
10514            }
10515        }
10516    }
10517
10518    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10519        let snapshot = self.snapshot(window, cx);
10520        let selection = self.selections.newest::<Point>(cx);
10521        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10522    }
10523
10524    fn go_to_hunk_after_position(
10525        &mut self,
10526        snapshot: &EditorSnapshot,
10527        position: Point,
10528        window: &mut Window,
10529        cx: &mut Context<Editor>,
10530    ) -> Option<MultiBufferDiffHunk> {
10531        let mut hunk = snapshot
10532            .buffer_snapshot
10533            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10534            .find(|hunk| hunk.row_range.start.0 > position.row);
10535        if hunk.is_none() {
10536            hunk = snapshot
10537                .buffer_snapshot
10538                .diff_hunks_in_range(Point::zero()..position)
10539                .find(|hunk| hunk.row_range.end.0 < position.row)
10540        }
10541        if let Some(hunk) = &hunk {
10542            let destination = Point::new(hunk.row_range.start.0, 0);
10543            self.unfold_ranges(&[destination..destination], false, false, cx);
10544            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10545                s.select_ranges(vec![destination..destination]);
10546            });
10547        }
10548
10549        hunk
10550    }
10551
10552    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10553        let snapshot = self.snapshot(window, cx);
10554        let selection = self.selections.newest::<Point>(cx);
10555        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10556    }
10557
10558    fn go_to_hunk_before_position(
10559        &mut self,
10560        snapshot: &EditorSnapshot,
10561        position: Point,
10562        window: &mut Window,
10563        cx: &mut Context<Editor>,
10564    ) -> Option<MultiBufferDiffHunk> {
10565        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10566        if hunk.is_none() {
10567            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10568        }
10569        if let Some(hunk) = &hunk {
10570            let destination = Point::new(hunk.row_range.start.0, 0);
10571            self.unfold_ranges(&[destination..destination], false, false, cx);
10572            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10573                s.select_ranges(vec![destination..destination]);
10574            });
10575        }
10576
10577        hunk
10578    }
10579
10580    pub fn go_to_definition(
10581        &mut self,
10582        _: &GoToDefinition,
10583        window: &mut Window,
10584        cx: &mut Context<Self>,
10585    ) -> Task<Result<Navigated>> {
10586        let definition =
10587            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10588        cx.spawn_in(window, |editor, mut cx| async move {
10589            if definition.await? == Navigated::Yes {
10590                return Ok(Navigated::Yes);
10591            }
10592            match editor.update_in(&mut cx, |editor, window, cx| {
10593                editor.find_all_references(&FindAllReferences, window, cx)
10594            })? {
10595                Some(references) => references.await,
10596                None => Ok(Navigated::No),
10597            }
10598        })
10599    }
10600
10601    pub fn go_to_declaration(
10602        &mut self,
10603        _: &GoToDeclaration,
10604        window: &mut Window,
10605        cx: &mut Context<Self>,
10606    ) -> Task<Result<Navigated>> {
10607        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10608    }
10609
10610    pub fn go_to_declaration_split(
10611        &mut self,
10612        _: &GoToDeclaration,
10613        window: &mut Window,
10614        cx: &mut Context<Self>,
10615    ) -> Task<Result<Navigated>> {
10616        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10617    }
10618
10619    pub fn go_to_implementation(
10620        &mut self,
10621        _: &GoToImplementation,
10622        window: &mut Window,
10623        cx: &mut Context<Self>,
10624    ) -> Task<Result<Navigated>> {
10625        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10626    }
10627
10628    pub fn go_to_implementation_split(
10629        &mut self,
10630        _: &GoToImplementationSplit,
10631        window: &mut Window,
10632        cx: &mut Context<Self>,
10633    ) -> Task<Result<Navigated>> {
10634        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10635    }
10636
10637    pub fn go_to_type_definition(
10638        &mut self,
10639        _: &GoToTypeDefinition,
10640        window: &mut Window,
10641        cx: &mut Context<Self>,
10642    ) -> Task<Result<Navigated>> {
10643        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10644    }
10645
10646    pub fn go_to_definition_split(
10647        &mut self,
10648        _: &GoToDefinitionSplit,
10649        window: &mut Window,
10650        cx: &mut Context<Self>,
10651    ) -> Task<Result<Navigated>> {
10652        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10653    }
10654
10655    pub fn go_to_type_definition_split(
10656        &mut self,
10657        _: &GoToTypeDefinitionSplit,
10658        window: &mut Window,
10659        cx: &mut Context<Self>,
10660    ) -> Task<Result<Navigated>> {
10661        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10662    }
10663
10664    fn go_to_definition_of_kind(
10665        &mut self,
10666        kind: GotoDefinitionKind,
10667        split: bool,
10668        window: &mut Window,
10669        cx: &mut Context<Self>,
10670    ) -> Task<Result<Navigated>> {
10671        let Some(provider) = self.semantics_provider.clone() else {
10672            return Task::ready(Ok(Navigated::No));
10673        };
10674        let head = self.selections.newest::<usize>(cx).head();
10675        let buffer = self.buffer.read(cx);
10676        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10677            text_anchor
10678        } else {
10679            return Task::ready(Ok(Navigated::No));
10680        };
10681
10682        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10683            return Task::ready(Ok(Navigated::No));
10684        };
10685
10686        cx.spawn_in(window, |editor, mut cx| async move {
10687            let definitions = definitions.await?;
10688            let navigated = editor
10689                .update_in(&mut cx, |editor, window, cx| {
10690                    editor.navigate_to_hover_links(
10691                        Some(kind),
10692                        definitions
10693                            .into_iter()
10694                            .filter(|location| {
10695                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10696                            })
10697                            .map(HoverLink::Text)
10698                            .collect::<Vec<_>>(),
10699                        split,
10700                        window,
10701                        cx,
10702                    )
10703                })?
10704                .await?;
10705            anyhow::Ok(navigated)
10706        })
10707    }
10708
10709    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10710        let selection = self.selections.newest_anchor();
10711        let head = selection.head();
10712        let tail = selection.tail();
10713
10714        let Some((buffer, start_position)) =
10715            self.buffer.read(cx).text_anchor_for_position(head, cx)
10716        else {
10717            return;
10718        };
10719
10720        let end_position = if head != tail {
10721            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10722                return;
10723            };
10724            Some(pos)
10725        } else {
10726            None
10727        };
10728
10729        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10730            let url = if let Some(end_pos) = end_position {
10731                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10732            } else {
10733                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10734            };
10735
10736            if let Some(url) = url {
10737                editor.update(&mut cx, |_, cx| {
10738                    cx.open_url(&url);
10739                })
10740            } else {
10741                Ok(())
10742            }
10743        });
10744
10745        url_finder.detach();
10746    }
10747
10748    pub fn open_selected_filename(
10749        &mut self,
10750        _: &OpenSelectedFilename,
10751        window: &mut Window,
10752        cx: &mut Context<Self>,
10753    ) {
10754        let Some(workspace) = self.workspace() else {
10755            return;
10756        };
10757
10758        let position = self.selections.newest_anchor().head();
10759
10760        let Some((buffer, buffer_position)) =
10761            self.buffer.read(cx).text_anchor_for_position(position, cx)
10762        else {
10763            return;
10764        };
10765
10766        let project = self.project.clone();
10767
10768        cx.spawn_in(window, |_, mut cx| async move {
10769            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10770
10771            if let Some((_, path)) = result {
10772                workspace
10773                    .update_in(&mut cx, |workspace, window, cx| {
10774                        workspace.open_resolved_path(path, window, cx)
10775                    })?
10776                    .await?;
10777            }
10778            anyhow::Ok(())
10779        })
10780        .detach();
10781    }
10782
10783    pub(crate) fn navigate_to_hover_links(
10784        &mut self,
10785        kind: Option<GotoDefinitionKind>,
10786        mut definitions: Vec<HoverLink>,
10787        split: bool,
10788        window: &mut Window,
10789        cx: &mut Context<Editor>,
10790    ) -> Task<Result<Navigated>> {
10791        // If there is one definition, just open it directly
10792        if definitions.len() == 1 {
10793            let definition = definitions.pop().unwrap();
10794
10795            enum TargetTaskResult {
10796                Location(Option<Location>),
10797                AlreadyNavigated,
10798            }
10799
10800            let target_task = match definition {
10801                HoverLink::Text(link) => {
10802                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10803                }
10804                HoverLink::InlayHint(lsp_location, server_id) => {
10805                    let computation =
10806                        self.compute_target_location(lsp_location, server_id, window, cx);
10807                    cx.background_executor().spawn(async move {
10808                        let location = computation.await?;
10809                        Ok(TargetTaskResult::Location(location))
10810                    })
10811                }
10812                HoverLink::Url(url) => {
10813                    cx.open_url(&url);
10814                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10815                }
10816                HoverLink::File(path) => {
10817                    if let Some(workspace) = self.workspace() {
10818                        cx.spawn_in(window, |_, mut cx| async move {
10819                            workspace
10820                                .update_in(&mut cx, |workspace, window, cx| {
10821                                    workspace.open_resolved_path(path, window, cx)
10822                                })?
10823                                .await
10824                                .map(|_| TargetTaskResult::AlreadyNavigated)
10825                        })
10826                    } else {
10827                        Task::ready(Ok(TargetTaskResult::Location(None)))
10828                    }
10829                }
10830            };
10831            cx.spawn_in(window, |editor, mut cx| async move {
10832                let target = match target_task.await.context("target resolution task")? {
10833                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10834                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10835                    TargetTaskResult::Location(Some(target)) => target,
10836                };
10837
10838                editor.update_in(&mut cx, |editor, window, cx| {
10839                    let Some(workspace) = editor.workspace() else {
10840                        return Navigated::No;
10841                    };
10842                    let pane = workspace.read(cx).active_pane().clone();
10843
10844                    let range = target.range.to_point(target.buffer.read(cx));
10845                    let range = editor.range_for_match(&range);
10846                    let range = collapse_multiline_range(range);
10847
10848                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10849                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10850                    } else {
10851                        window.defer(cx, move |window, cx| {
10852                            let target_editor: Entity<Self> =
10853                                workspace.update(cx, |workspace, cx| {
10854                                    let pane = if split {
10855                                        workspace.adjacent_pane(window, cx)
10856                                    } else {
10857                                        workspace.active_pane().clone()
10858                                    };
10859
10860                                    workspace.open_project_item(
10861                                        pane,
10862                                        target.buffer.clone(),
10863                                        true,
10864                                        true,
10865                                        window,
10866                                        cx,
10867                                    )
10868                                });
10869                            target_editor.update(cx, |target_editor, cx| {
10870                                // When selecting a definition in a different buffer, disable the nav history
10871                                // to avoid creating a history entry at the previous cursor location.
10872                                pane.update(cx, |pane, _| pane.disable_history());
10873                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10874                                pane.update(cx, |pane, _| pane.enable_history());
10875                            });
10876                        });
10877                    }
10878                    Navigated::Yes
10879                })
10880            })
10881        } else if !definitions.is_empty() {
10882            cx.spawn_in(window, |editor, mut cx| async move {
10883                let (title, location_tasks, workspace) = editor
10884                    .update_in(&mut cx, |editor, window, cx| {
10885                        let tab_kind = match kind {
10886                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10887                            _ => "Definitions",
10888                        };
10889                        let title = definitions
10890                            .iter()
10891                            .find_map(|definition| match definition {
10892                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10893                                    let buffer = origin.buffer.read(cx);
10894                                    format!(
10895                                        "{} for {}",
10896                                        tab_kind,
10897                                        buffer
10898                                            .text_for_range(origin.range.clone())
10899                                            .collect::<String>()
10900                                    )
10901                                }),
10902                                HoverLink::InlayHint(_, _) => None,
10903                                HoverLink::Url(_) => None,
10904                                HoverLink::File(_) => None,
10905                            })
10906                            .unwrap_or(tab_kind.to_string());
10907                        let location_tasks = definitions
10908                            .into_iter()
10909                            .map(|definition| match definition {
10910                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10911                                HoverLink::InlayHint(lsp_location, server_id) => editor
10912                                    .compute_target_location(lsp_location, server_id, window, cx),
10913                                HoverLink::Url(_) => Task::ready(Ok(None)),
10914                                HoverLink::File(_) => Task::ready(Ok(None)),
10915                            })
10916                            .collect::<Vec<_>>();
10917                        (title, location_tasks, editor.workspace().clone())
10918                    })
10919                    .context("location tasks preparation")?;
10920
10921                let locations = future::join_all(location_tasks)
10922                    .await
10923                    .into_iter()
10924                    .filter_map(|location| location.transpose())
10925                    .collect::<Result<_>>()
10926                    .context("location tasks")?;
10927
10928                let Some(workspace) = workspace else {
10929                    return Ok(Navigated::No);
10930                };
10931                let opened = workspace
10932                    .update_in(&mut cx, |workspace, window, cx| {
10933                        Self::open_locations_in_multibuffer(
10934                            workspace,
10935                            locations,
10936                            title,
10937                            split,
10938                            MultibufferSelectionMode::First,
10939                            window,
10940                            cx,
10941                        )
10942                    })
10943                    .ok();
10944
10945                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10946            })
10947        } else {
10948            Task::ready(Ok(Navigated::No))
10949        }
10950    }
10951
10952    fn compute_target_location(
10953        &self,
10954        lsp_location: lsp::Location,
10955        server_id: LanguageServerId,
10956        window: &mut Window,
10957        cx: &mut Context<Self>,
10958    ) -> Task<anyhow::Result<Option<Location>>> {
10959        let Some(project) = self.project.clone() else {
10960            return Task::ready(Ok(None));
10961        };
10962
10963        cx.spawn_in(window, move |editor, mut cx| async move {
10964            let location_task = editor.update(&mut cx, |_, cx| {
10965                project.update(cx, |project, cx| {
10966                    let language_server_name = project
10967                        .language_server_statuses(cx)
10968                        .find(|(id, _)| server_id == *id)
10969                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10970                    language_server_name.map(|language_server_name| {
10971                        project.open_local_buffer_via_lsp(
10972                            lsp_location.uri.clone(),
10973                            server_id,
10974                            language_server_name,
10975                            cx,
10976                        )
10977                    })
10978                })
10979            })?;
10980            let location = match location_task {
10981                Some(task) => Some({
10982                    let target_buffer_handle = task.await.context("open local buffer")?;
10983                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10984                        let target_start = target_buffer
10985                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10986                        let target_end = target_buffer
10987                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10988                        target_buffer.anchor_after(target_start)
10989                            ..target_buffer.anchor_before(target_end)
10990                    })?;
10991                    Location {
10992                        buffer: target_buffer_handle,
10993                        range,
10994                    }
10995                }),
10996                None => None,
10997            };
10998            Ok(location)
10999        })
11000    }
11001
11002    pub fn find_all_references(
11003        &mut self,
11004        _: &FindAllReferences,
11005        window: &mut Window,
11006        cx: &mut Context<Self>,
11007    ) -> Option<Task<Result<Navigated>>> {
11008        let selection = self.selections.newest::<usize>(cx);
11009        let multi_buffer = self.buffer.read(cx);
11010        let head = selection.head();
11011
11012        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11013        let head_anchor = multi_buffer_snapshot.anchor_at(
11014            head,
11015            if head < selection.tail() {
11016                Bias::Right
11017            } else {
11018                Bias::Left
11019            },
11020        );
11021
11022        match self
11023            .find_all_references_task_sources
11024            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11025        {
11026            Ok(_) => {
11027                log::info!(
11028                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11029                );
11030                return None;
11031            }
11032            Err(i) => {
11033                self.find_all_references_task_sources.insert(i, head_anchor);
11034            }
11035        }
11036
11037        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11038        let workspace = self.workspace()?;
11039        let project = workspace.read(cx).project().clone();
11040        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11041        Some(cx.spawn_in(window, |editor, mut cx| async move {
11042            let _cleanup = defer({
11043                let mut cx = cx.clone();
11044                move || {
11045                    let _ = editor.update(&mut cx, |editor, _| {
11046                        if let Ok(i) =
11047                            editor
11048                                .find_all_references_task_sources
11049                                .binary_search_by(|anchor| {
11050                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11051                                })
11052                        {
11053                            editor.find_all_references_task_sources.remove(i);
11054                        }
11055                    });
11056                }
11057            });
11058
11059            let locations = references.await?;
11060            if locations.is_empty() {
11061                return anyhow::Ok(Navigated::No);
11062            }
11063
11064            workspace.update_in(&mut cx, |workspace, window, cx| {
11065                let title = locations
11066                    .first()
11067                    .as_ref()
11068                    .map(|location| {
11069                        let buffer = location.buffer.read(cx);
11070                        format!(
11071                            "References to `{}`",
11072                            buffer
11073                                .text_for_range(location.range.clone())
11074                                .collect::<String>()
11075                        )
11076                    })
11077                    .unwrap();
11078                Self::open_locations_in_multibuffer(
11079                    workspace,
11080                    locations,
11081                    title,
11082                    false,
11083                    MultibufferSelectionMode::First,
11084                    window,
11085                    cx,
11086                );
11087                Navigated::Yes
11088            })
11089        }))
11090    }
11091
11092    /// Opens a multibuffer with the given project locations in it
11093    pub fn open_locations_in_multibuffer(
11094        workspace: &mut Workspace,
11095        mut locations: Vec<Location>,
11096        title: String,
11097        split: bool,
11098        multibuffer_selection_mode: MultibufferSelectionMode,
11099        window: &mut Window,
11100        cx: &mut Context<Workspace>,
11101    ) {
11102        // If there are multiple definitions, open them in a multibuffer
11103        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11104        let mut locations = locations.into_iter().peekable();
11105        let mut ranges = Vec::new();
11106        let capability = workspace.project().read(cx).capability();
11107
11108        let excerpt_buffer = cx.new(|cx| {
11109            let mut multibuffer = MultiBuffer::new(capability);
11110            while let Some(location) = locations.next() {
11111                let buffer = location.buffer.read(cx);
11112                let mut ranges_for_buffer = Vec::new();
11113                let range = location.range.to_offset(buffer);
11114                ranges_for_buffer.push(range.clone());
11115
11116                while let Some(next_location) = locations.peek() {
11117                    if next_location.buffer == location.buffer {
11118                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11119                        locations.next();
11120                    } else {
11121                        break;
11122                    }
11123                }
11124
11125                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11126                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11127                    location.buffer.clone(),
11128                    ranges_for_buffer,
11129                    DEFAULT_MULTIBUFFER_CONTEXT,
11130                    cx,
11131                ))
11132            }
11133
11134            multibuffer.with_title(title)
11135        });
11136
11137        let editor = cx.new(|cx| {
11138            Editor::for_multibuffer(
11139                excerpt_buffer,
11140                Some(workspace.project().clone()),
11141                true,
11142                window,
11143                cx,
11144            )
11145        });
11146        editor.update(cx, |editor, cx| {
11147            match multibuffer_selection_mode {
11148                MultibufferSelectionMode::First => {
11149                    if let Some(first_range) = ranges.first() {
11150                        editor.change_selections(None, window, cx, |selections| {
11151                            selections.clear_disjoint();
11152                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11153                        });
11154                    }
11155                    editor.highlight_background::<Self>(
11156                        &ranges,
11157                        |theme| theme.editor_highlighted_line_background,
11158                        cx,
11159                    );
11160                }
11161                MultibufferSelectionMode::All => {
11162                    editor.change_selections(None, window, cx, |selections| {
11163                        selections.clear_disjoint();
11164                        selections.select_anchor_ranges(ranges);
11165                    });
11166                }
11167            }
11168            editor.register_buffers_with_language_servers(cx);
11169        });
11170
11171        let item = Box::new(editor);
11172        let item_id = item.item_id();
11173
11174        if split {
11175            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11176        } else {
11177            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11178                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11179                    pane.close_current_preview_item(window, cx)
11180                } else {
11181                    None
11182                }
11183            });
11184            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11185        }
11186        workspace.active_pane().update(cx, |pane, cx| {
11187            pane.set_preview_item_id(Some(item_id), cx);
11188        });
11189    }
11190
11191    pub fn rename(
11192        &mut self,
11193        _: &Rename,
11194        window: &mut Window,
11195        cx: &mut Context<Self>,
11196    ) -> Option<Task<Result<()>>> {
11197        use language::ToOffset as _;
11198
11199        let provider = self.semantics_provider.clone()?;
11200        let selection = self.selections.newest_anchor().clone();
11201        let (cursor_buffer, cursor_buffer_position) = self
11202            .buffer
11203            .read(cx)
11204            .text_anchor_for_position(selection.head(), cx)?;
11205        let (tail_buffer, cursor_buffer_position_end) = self
11206            .buffer
11207            .read(cx)
11208            .text_anchor_for_position(selection.tail(), cx)?;
11209        if tail_buffer != cursor_buffer {
11210            return None;
11211        }
11212
11213        let snapshot = cursor_buffer.read(cx).snapshot();
11214        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11215        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11216        let prepare_rename = provider
11217            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11218            .unwrap_or_else(|| Task::ready(Ok(None)));
11219        drop(snapshot);
11220
11221        Some(cx.spawn_in(window, |this, mut cx| async move {
11222            let rename_range = if let Some(range) = prepare_rename.await? {
11223                Some(range)
11224            } else {
11225                this.update(&mut cx, |this, cx| {
11226                    let buffer = this.buffer.read(cx).snapshot(cx);
11227                    let mut buffer_highlights = this
11228                        .document_highlights_for_position(selection.head(), &buffer)
11229                        .filter(|highlight| {
11230                            highlight.start.excerpt_id == selection.head().excerpt_id
11231                                && highlight.end.excerpt_id == selection.head().excerpt_id
11232                        });
11233                    buffer_highlights
11234                        .next()
11235                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11236                })?
11237            };
11238            if let Some(rename_range) = rename_range {
11239                this.update_in(&mut cx, |this, window, cx| {
11240                    let snapshot = cursor_buffer.read(cx).snapshot();
11241                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11242                    let cursor_offset_in_rename_range =
11243                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11244                    let cursor_offset_in_rename_range_end =
11245                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11246
11247                    this.take_rename(false, window, cx);
11248                    let buffer = this.buffer.read(cx).read(cx);
11249                    let cursor_offset = selection.head().to_offset(&buffer);
11250                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11251                    let rename_end = rename_start + rename_buffer_range.len();
11252                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11253                    let mut old_highlight_id = None;
11254                    let old_name: Arc<str> = buffer
11255                        .chunks(rename_start..rename_end, true)
11256                        .map(|chunk| {
11257                            if old_highlight_id.is_none() {
11258                                old_highlight_id = chunk.syntax_highlight_id;
11259                            }
11260                            chunk.text
11261                        })
11262                        .collect::<String>()
11263                        .into();
11264
11265                    drop(buffer);
11266
11267                    // Position the selection in the rename editor so that it matches the current selection.
11268                    this.show_local_selections = false;
11269                    let rename_editor = cx.new(|cx| {
11270                        let mut editor = Editor::single_line(window, cx);
11271                        editor.buffer.update(cx, |buffer, cx| {
11272                            buffer.edit([(0..0, old_name.clone())], None, cx)
11273                        });
11274                        let rename_selection_range = match cursor_offset_in_rename_range
11275                            .cmp(&cursor_offset_in_rename_range_end)
11276                        {
11277                            Ordering::Equal => {
11278                                editor.select_all(&SelectAll, window, cx);
11279                                return editor;
11280                            }
11281                            Ordering::Less => {
11282                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11283                            }
11284                            Ordering::Greater => {
11285                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11286                            }
11287                        };
11288                        if rename_selection_range.end > old_name.len() {
11289                            editor.select_all(&SelectAll, window, cx);
11290                        } else {
11291                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11292                                s.select_ranges([rename_selection_range]);
11293                            });
11294                        }
11295                        editor
11296                    });
11297                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11298                        if e == &EditorEvent::Focused {
11299                            cx.emit(EditorEvent::FocusedIn)
11300                        }
11301                    })
11302                    .detach();
11303
11304                    let write_highlights =
11305                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11306                    let read_highlights =
11307                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11308                    let ranges = write_highlights
11309                        .iter()
11310                        .flat_map(|(_, ranges)| ranges.iter())
11311                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11312                        .cloned()
11313                        .collect();
11314
11315                    this.highlight_text::<Rename>(
11316                        ranges,
11317                        HighlightStyle {
11318                            fade_out: Some(0.6),
11319                            ..Default::default()
11320                        },
11321                        cx,
11322                    );
11323                    let rename_focus_handle = rename_editor.focus_handle(cx);
11324                    window.focus(&rename_focus_handle);
11325                    let block_id = this.insert_blocks(
11326                        [BlockProperties {
11327                            style: BlockStyle::Flex,
11328                            placement: BlockPlacement::Below(range.start),
11329                            height: 1,
11330                            render: Arc::new({
11331                                let rename_editor = rename_editor.clone();
11332                                move |cx: &mut BlockContext| {
11333                                    let mut text_style = cx.editor_style.text.clone();
11334                                    if let Some(highlight_style) = old_highlight_id
11335                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11336                                    {
11337                                        text_style = text_style.highlight(highlight_style);
11338                                    }
11339                                    div()
11340                                        .block_mouse_down()
11341                                        .pl(cx.anchor_x)
11342                                        .child(EditorElement::new(
11343                                            &rename_editor,
11344                                            EditorStyle {
11345                                                background: cx.theme().system().transparent,
11346                                                local_player: cx.editor_style.local_player,
11347                                                text: text_style,
11348                                                scrollbar_width: cx.editor_style.scrollbar_width,
11349                                                syntax: cx.editor_style.syntax.clone(),
11350                                                status: cx.editor_style.status.clone(),
11351                                                inlay_hints_style: HighlightStyle {
11352                                                    font_weight: Some(FontWeight::BOLD),
11353                                                    ..make_inlay_hints_style(cx.app)
11354                                                },
11355                                                inline_completion_styles: make_suggestion_styles(
11356                                                    cx.app,
11357                                                ),
11358                                                ..EditorStyle::default()
11359                                            },
11360                                        ))
11361                                        .into_any_element()
11362                                }
11363                            }),
11364                            priority: 0,
11365                        }],
11366                        Some(Autoscroll::fit()),
11367                        cx,
11368                    )[0];
11369                    this.pending_rename = Some(RenameState {
11370                        range,
11371                        old_name,
11372                        editor: rename_editor,
11373                        block_id,
11374                    });
11375                })?;
11376            }
11377
11378            Ok(())
11379        }))
11380    }
11381
11382    pub fn confirm_rename(
11383        &mut self,
11384        _: &ConfirmRename,
11385        window: &mut Window,
11386        cx: &mut Context<Self>,
11387    ) -> Option<Task<Result<()>>> {
11388        let rename = self.take_rename(false, window, cx)?;
11389        let workspace = self.workspace()?.downgrade();
11390        let (buffer, start) = self
11391            .buffer
11392            .read(cx)
11393            .text_anchor_for_position(rename.range.start, cx)?;
11394        let (end_buffer, _) = self
11395            .buffer
11396            .read(cx)
11397            .text_anchor_for_position(rename.range.end, cx)?;
11398        if buffer != end_buffer {
11399            return None;
11400        }
11401
11402        let old_name = rename.old_name;
11403        let new_name = rename.editor.read(cx).text(cx);
11404
11405        let rename = self.semantics_provider.as_ref()?.perform_rename(
11406            &buffer,
11407            start,
11408            new_name.clone(),
11409            cx,
11410        )?;
11411
11412        Some(cx.spawn_in(window, |editor, mut cx| async move {
11413            let project_transaction = rename.await?;
11414            Self::open_project_transaction(
11415                &editor,
11416                workspace,
11417                project_transaction,
11418                format!("Rename: {}{}", old_name, new_name),
11419                cx.clone(),
11420            )
11421            .await?;
11422
11423            editor.update(&mut cx, |editor, cx| {
11424                editor.refresh_document_highlights(cx);
11425            })?;
11426            Ok(())
11427        }))
11428    }
11429
11430    fn take_rename(
11431        &mut self,
11432        moving_cursor: bool,
11433        window: &mut Window,
11434        cx: &mut Context<Self>,
11435    ) -> Option<RenameState> {
11436        let rename = self.pending_rename.take()?;
11437        if rename.editor.focus_handle(cx).is_focused(window) {
11438            window.focus(&self.focus_handle);
11439        }
11440
11441        self.remove_blocks(
11442            [rename.block_id].into_iter().collect(),
11443            Some(Autoscroll::fit()),
11444            cx,
11445        );
11446        self.clear_highlights::<Rename>(cx);
11447        self.show_local_selections = true;
11448
11449        if moving_cursor {
11450            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11451                editor.selections.newest::<usize>(cx).head()
11452            });
11453
11454            // Update the selection to match the position of the selection inside
11455            // the rename editor.
11456            let snapshot = self.buffer.read(cx).read(cx);
11457            let rename_range = rename.range.to_offset(&snapshot);
11458            let cursor_in_editor = snapshot
11459                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11460                .min(rename_range.end);
11461            drop(snapshot);
11462
11463            self.change_selections(None, window, cx, |s| {
11464                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11465            });
11466        } else {
11467            self.refresh_document_highlights(cx);
11468        }
11469
11470        Some(rename)
11471    }
11472
11473    pub fn pending_rename(&self) -> Option<&RenameState> {
11474        self.pending_rename.as_ref()
11475    }
11476
11477    fn format(
11478        &mut self,
11479        _: &Format,
11480        window: &mut Window,
11481        cx: &mut Context<Self>,
11482    ) -> Option<Task<Result<()>>> {
11483        let project = match &self.project {
11484            Some(project) => project.clone(),
11485            None => return None,
11486        };
11487
11488        Some(self.perform_format(
11489            project,
11490            FormatTrigger::Manual,
11491            FormatTarget::Buffers,
11492            window,
11493            cx,
11494        ))
11495    }
11496
11497    fn format_selections(
11498        &mut self,
11499        _: &FormatSelections,
11500        window: &mut Window,
11501        cx: &mut Context<Self>,
11502    ) -> Option<Task<Result<()>>> {
11503        let project = match &self.project {
11504            Some(project) => project.clone(),
11505            None => return None,
11506        };
11507
11508        let ranges = self
11509            .selections
11510            .all_adjusted(cx)
11511            .into_iter()
11512            .map(|selection| selection.range())
11513            .collect_vec();
11514
11515        Some(self.perform_format(
11516            project,
11517            FormatTrigger::Manual,
11518            FormatTarget::Ranges(ranges),
11519            window,
11520            cx,
11521        ))
11522    }
11523
11524    fn perform_format(
11525        &mut self,
11526        project: Entity<Project>,
11527        trigger: FormatTrigger,
11528        target: FormatTarget,
11529        window: &mut Window,
11530        cx: &mut Context<Self>,
11531    ) -> Task<Result<()>> {
11532        let buffer = self.buffer.clone();
11533        let (buffers, target) = match target {
11534            FormatTarget::Buffers => {
11535                let mut buffers = buffer.read(cx).all_buffers();
11536                if trigger == FormatTrigger::Save {
11537                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11538                }
11539                (buffers, LspFormatTarget::Buffers)
11540            }
11541            FormatTarget::Ranges(selection_ranges) => {
11542                let multi_buffer = buffer.read(cx);
11543                let snapshot = multi_buffer.read(cx);
11544                let mut buffers = HashSet::default();
11545                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11546                    BTreeMap::new();
11547                for selection_range in selection_ranges {
11548                    for (buffer, buffer_range, _) in
11549                        snapshot.range_to_buffer_ranges(selection_range)
11550                    {
11551                        let buffer_id = buffer.remote_id();
11552                        let start = buffer.anchor_before(buffer_range.start);
11553                        let end = buffer.anchor_after(buffer_range.end);
11554                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11555                        buffer_id_to_ranges
11556                            .entry(buffer_id)
11557                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11558                            .or_insert_with(|| vec![start..end]);
11559                    }
11560                }
11561                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11562            }
11563        };
11564
11565        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11566        let format = project.update(cx, |project, cx| {
11567            project.format(buffers, target, true, trigger, cx)
11568        });
11569
11570        cx.spawn_in(window, |_, mut cx| async move {
11571            let transaction = futures::select_biased! {
11572                () = timeout => {
11573                    log::warn!("timed out waiting for formatting");
11574                    None
11575                }
11576                transaction = format.log_err().fuse() => transaction,
11577            };
11578
11579            buffer
11580                .update(&mut cx, |buffer, cx| {
11581                    if let Some(transaction) = transaction {
11582                        if !buffer.is_singleton() {
11583                            buffer.push_transaction(&transaction.0, cx);
11584                        }
11585                    }
11586
11587                    cx.notify();
11588                })
11589                .ok();
11590
11591            Ok(())
11592        })
11593    }
11594
11595    fn restart_language_server(
11596        &mut self,
11597        _: &RestartLanguageServer,
11598        _: &mut Window,
11599        cx: &mut Context<Self>,
11600    ) {
11601        if let Some(project) = self.project.clone() {
11602            self.buffer.update(cx, |multi_buffer, cx| {
11603                project.update(cx, |project, cx| {
11604                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11605                });
11606            })
11607        }
11608    }
11609
11610    fn cancel_language_server_work(
11611        workspace: &mut Workspace,
11612        _: &actions::CancelLanguageServerWork,
11613        _: &mut Window,
11614        cx: &mut Context<Workspace>,
11615    ) {
11616        let project = workspace.project();
11617        let buffers = workspace
11618            .active_item(cx)
11619            .and_then(|item| item.act_as::<Editor>(cx))
11620            .map_or(HashSet::default(), |editor| {
11621                editor.read(cx).buffer.read(cx).all_buffers()
11622            });
11623        project.update(cx, |project, cx| {
11624            project.cancel_language_server_work_for_buffers(buffers, cx);
11625        });
11626    }
11627
11628    fn show_character_palette(
11629        &mut self,
11630        _: &ShowCharacterPalette,
11631        window: &mut Window,
11632        _: &mut Context<Self>,
11633    ) {
11634        window.show_character_palette();
11635    }
11636
11637    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11638        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11639            let buffer = self.buffer.read(cx).snapshot(cx);
11640            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11641            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11642            let is_valid = buffer
11643                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11644                .any(|entry| {
11645                    entry.diagnostic.is_primary
11646                        && !entry.range.is_empty()
11647                        && entry.range.start == primary_range_start
11648                        && entry.diagnostic.message == active_diagnostics.primary_message
11649                });
11650
11651            if is_valid != active_diagnostics.is_valid {
11652                active_diagnostics.is_valid = is_valid;
11653                let mut new_styles = HashMap::default();
11654                for (block_id, diagnostic) in &active_diagnostics.blocks {
11655                    new_styles.insert(
11656                        *block_id,
11657                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11658                    );
11659                }
11660                self.display_map.update(cx, |display_map, _cx| {
11661                    display_map.replace_blocks(new_styles)
11662                });
11663            }
11664        }
11665    }
11666
11667    fn activate_diagnostics(
11668        &mut self,
11669        buffer_id: BufferId,
11670        group_id: usize,
11671        window: &mut Window,
11672        cx: &mut Context<Self>,
11673    ) {
11674        self.dismiss_diagnostics(cx);
11675        let snapshot = self.snapshot(window, cx);
11676        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11677            let buffer = self.buffer.read(cx).snapshot(cx);
11678
11679            let mut primary_range = None;
11680            let mut primary_message = None;
11681            let diagnostic_group = buffer
11682                .diagnostic_group(buffer_id, group_id)
11683                .filter_map(|entry| {
11684                    let start = entry.range.start;
11685                    let end = entry.range.end;
11686                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11687                        && (start.row == end.row
11688                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11689                    {
11690                        return None;
11691                    }
11692                    if entry.diagnostic.is_primary {
11693                        primary_range = Some(entry.range.clone());
11694                        primary_message = Some(entry.diagnostic.message.clone());
11695                    }
11696                    Some(entry)
11697                })
11698                .collect::<Vec<_>>();
11699            let primary_range = primary_range?;
11700            let primary_message = primary_message?;
11701
11702            let blocks = display_map
11703                .insert_blocks(
11704                    diagnostic_group.iter().map(|entry| {
11705                        let diagnostic = entry.diagnostic.clone();
11706                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11707                        BlockProperties {
11708                            style: BlockStyle::Fixed,
11709                            placement: BlockPlacement::Below(
11710                                buffer.anchor_after(entry.range.start),
11711                            ),
11712                            height: message_height,
11713                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11714                            priority: 0,
11715                        }
11716                    }),
11717                    cx,
11718                )
11719                .into_iter()
11720                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11721                .collect();
11722
11723            Some(ActiveDiagnosticGroup {
11724                primary_range: buffer.anchor_before(primary_range.start)
11725                    ..buffer.anchor_after(primary_range.end),
11726                primary_message,
11727                group_id,
11728                blocks,
11729                is_valid: true,
11730            })
11731        });
11732    }
11733
11734    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11735        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11736            self.display_map.update(cx, |display_map, cx| {
11737                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11738            });
11739            cx.notify();
11740        }
11741    }
11742
11743    pub fn set_selections_from_remote(
11744        &mut self,
11745        selections: Vec<Selection<Anchor>>,
11746        pending_selection: Option<Selection<Anchor>>,
11747        window: &mut Window,
11748        cx: &mut Context<Self>,
11749    ) {
11750        let old_cursor_position = self.selections.newest_anchor().head();
11751        self.selections.change_with(cx, |s| {
11752            s.select_anchors(selections);
11753            if let Some(pending_selection) = pending_selection {
11754                s.set_pending(pending_selection, SelectMode::Character);
11755            } else {
11756                s.clear_pending();
11757            }
11758        });
11759        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11760    }
11761
11762    fn push_to_selection_history(&mut self) {
11763        self.selection_history.push(SelectionHistoryEntry {
11764            selections: self.selections.disjoint_anchors(),
11765            select_next_state: self.select_next_state.clone(),
11766            select_prev_state: self.select_prev_state.clone(),
11767            add_selections_state: self.add_selections_state.clone(),
11768        });
11769    }
11770
11771    pub fn transact(
11772        &mut self,
11773        window: &mut Window,
11774        cx: &mut Context<Self>,
11775        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11776    ) -> Option<TransactionId> {
11777        self.start_transaction_at(Instant::now(), window, cx);
11778        update(self, window, cx);
11779        self.end_transaction_at(Instant::now(), cx)
11780    }
11781
11782    pub fn start_transaction_at(
11783        &mut self,
11784        now: Instant,
11785        window: &mut Window,
11786        cx: &mut Context<Self>,
11787    ) {
11788        self.end_selection(window, cx);
11789        if let Some(tx_id) = self
11790            .buffer
11791            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11792        {
11793            self.selection_history
11794                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11795            cx.emit(EditorEvent::TransactionBegun {
11796                transaction_id: tx_id,
11797            })
11798        }
11799    }
11800
11801    pub fn end_transaction_at(
11802        &mut self,
11803        now: Instant,
11804        cx: &mut Context<Self>,
11805    ) -> Option<TransactionId> {
11806        if let Some(transaction_id) = self
11807            .buffer
11808            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11809        {
11810            if let Some((_, end_selections)) =
11811                self.selection_history.transaction_mut(transaction_id)
11812            {
11813                *end_selections = Some(self.selections.disjoint_anchors());
11814            } else {
11815                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11816            }
11817
11818            cx.emit(EditorEvent::Edited { transaction_id });
11819            Some(transaction_id)
11820        } else {
11821            None
11822        }
11823    }
11824
11825    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11826        if self.selection_mark_mode {
11827            self.change_selections(None, window, cx, |s| {
11828                s.move_with(|_, sel| {
11829                    sel.collapse_to(sel.head(), SelectionGoal::None);
11830                });
11831            })
11832        }
11833        self.selection_mark_mode = true;
11834        cx.notify();
11835    }
11836
11837    pub fn swap_selection_ends(
11838        &mut self,
11839        _: &actions::SwapSelectionEnds,
11840        window: &mut Window,
11841        cx: &mut Context<Self>,
11842    ) {
11843        self.change_selections(None, window, cx, |s| {
11844            s.move_with(|_, sel| {
11845                if sel.start != sel.end {
11846                    sel.reversed = !sel.reversed
11847                }
11848            });
11849        });
11850        self.request_autoscroll(Autoscroll::newest(), cx);
11851        cx.notify();
11852    }
11853
11854    pub fn toggle_fold(
11855        &mut self,
11856        _: &actions::ToggleFold,
11857        window: &mut Window,
11858        cx: &mut Context<Self>,
11859    ) {
11860        if self.is_singleton(cx) {
11861            let selection = self.selections.newest::<Point>(cx);
11862
11863            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11864            let range = if selection.is_empty() {
11865                let point = selection.head().to_display_point(&display_map);
11866                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11867                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11868                    .to_point(&display_map);
11869                start..end
11870            } else {
11871                selection.range()
11872            };
11873            if display_map.folds_in_range(range).next().is_some() {
11874                self.unfold_lines(&Default::default(), window, cx)
11875            } else {
11876                self.fold(&Default::default(), window, cx)
11877            }
11878        } else {
11879            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11880            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11881                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11882                .map(|(snapshot, _, _)| snapshot.remote_id())
11883                .collect();
11884
11885            for buffer_id in buffer_ids {
11886                if self.is_buffer_folded(buffer_id, cx) {
11887                    self.unfold_buffer(buffer_id, cx);
11888                } else {
11889                    self.fold_buffer(buffer_id, cx);
11890                }
11891            }
11892        }
11893    }
11894
11895    pub fn toggle_fold_recursive(
11896        &mut self,
11897        _: &actions::ToggleFoldRecursive,
11898        window: &mut Window,
11899        cx: &mut Context<Self>,
11900    ) {
11901        let selection = self.selections.newest::<Point>(cx);
11902
11903        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11904        let range = if selection.is_empty() {
11905            let point = selection.head().to_display_point(&display_map);
11906            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11907            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11908                .to_point(&display_map);
11909            start..end
11910        } else {
11911            selection.range()
11912        };
11913        if display_map.folds_in_range(range).next().is_some() {
11914            self.unfold_recursive(&Default::default(), window, cx)
11915        } else {
11916            self.fold_recursive(&Default::default(), window, cx)
11917        }
11918    }
11919
11920    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11921        if self.is_singleton(cx) {
11922            let mut to_fold = Vec::new();
11923            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11924            let selections = self.selections.all_adjusted(cx);
11925
11926            for selection in selections {
11927                let range = selection.range().sorted();
11928                let buffer_start_row = range.start.row;
11929
11930                if range.start.row != range.end.row {
11931                    let mut found = false;
11932                    let mut row = range.start.row;
11933                    while row <= range.end.row {
11934                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11935                        {
11936                            found = true;
11937                            row = crease.range().end.row + 1;
11938                            to_fold.push(crease);
11939                        } else {
11940                            row += 1
11941                        }
11942                    }
11943                    if found {
11944                        continue;
11945                    }
11946                }
11947
11948                for row in (0..=range.start.row).rev() {
11949                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11950                        if crease.range().end.row >= buffer_start_row {
11951                            to_fold.push(crease);
11952                            if row <= range.start.row {
11953                                break;
11954                            }
11955                        }
11956                    }
11957                }
11958            }
11959
11960            self.fold_creases(to_fold, true, window, cx);
11961        } else {
11962            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11963
11964            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11965                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11966                .map(|(snapshot, _, _)| snapshot.remote_id())
11967                .collect();
11968            for buffer_id in buffer_ids {
11969                self.fold_buffer(buffer_id, cx);
11970            }
11971        }
11972    }
11973
11974    fn fold_at_level(
11975        &mut self,
11976        fold_at: &FoldAtLevel,
11977        window: &mut Window,
11978        cx: &mut Context<Self>,
11979    ) {
11980        if !self.buffer.read(cx).is_singleton() {
11981            return;
11982        }
11983
11984        let fold_at_level = fold_at.0;
11985        let snapshot = self.buffer.read(cx).snapshot(cx);
11986        let mut to_fold = Vec::new();
11987        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11988
11989        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11990            while start_row < end_row {
11991                match self
11992                    .snapshot(window, cx)
11993                    .crease_for_buffer_row(MultiBufferRow(start_row))
11994                {
11995                    Some(crease) => {
11996                        let nested_start_row = crease.range().start.row + 1;
11997                        let nested_end_row = crease.range().end.row;
11998
11999                        if current_level < fold_at_level {
12000                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12001                        } else if current_level == fold_at_level {
12002                            to_fold.push(crease);
12003                        }
12004
12005                        start_row = nested_end_row + 1;
12006                    }
12007                    None => start_row += 1,
12008                }
12009            }
12010        }
12011
12012        self.fold_creases(to_fold, true, window, cx);
12013    }
12014
12015    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12016        if self.buffer.read(cx).is_singleton() {
12017            let mut fold_ranges = Vec::new();
12018            let snapshot = self.buffer.read(cx).snapshot(cx);
12019
12020            for row in 0..snapshot.max_row().0 {
12021                if let Some(foldable_range) = self
12022                    .snapshot(window, cx)
12023                    .crease_for_buffer_row(MultiBufferRow(row))
12024                {
12025                    fold_ranges.push(foldable_range);
12026                }
12027            }
12028
12029            self.fold_creases(fold_ranges, true, window, cx);
12030        } else {
12031            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12032                editor
12033                    .update_in(&mut cx, |editor, _, cx| {
12034                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12035                            editor.fold_buffer(buffer_id, cx);
12036                        }
12037                    })
12038                    .ok();
12039            });
12040        }
12041    }
12042
12043    pub fn fold_function_bodies(
12044        &mut self,
12045        _: &actions::FoldFunctionBodies,
12046        window: &mut Window,
12047        cx: &mut Context<Self>,
12048    ) {
12049        let snapshot = self.buffer.read(cx).snapshot(cx);
12050
12051        let ranges = snapshot
12052            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12053            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12054            .collect::<Vec<_>>();
12055
12056        let creases = ranges
12057            .into_iter()
12058            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12059            .collect();
12060
12061        self.fold_creases(creases, true, window, cx);
12062    }
12063
12064    pub fn fold_recursive(
12065        &mut self,
12066        _: &actions::FoldRecursive,
12067        window: &mut Window,
12068        cx: &mut Context<Self>,
12069    ) {
12070        let mut to_fold = Vec::new();
12071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12072        let selections = self.selections.all_adjusted(cx);
12073
12074        for selection in selections {
12075            let range = selection.range().sorted();
12076            let buffer_start_row = range.start.row;
12077
12078            if range.start.row != range.end.row {
12079                let mut found = false;
12080                for row in range.start.row..=range.end.row {
12081                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12082                        found = true;
12083                        to_fold.push(crease);
12084                    }
12085                }
12086                if found {
12087                    continue;
12088                }
12089            }
12090
12091            for row in (0..=range.start.row).rev() {
12092                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12093                    if crease.range().end.row >= buffer_start_row {
12094                        to_fold.push(crease);
12095                    } else {
12096                        break;
12097                    }
12098                }
12099            }
12100        }
12101
12102        self.fold_creases(to_fold, true, window, cx);
12103    }
12104
12105    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12106        let buffer_row = fold_at.buffer_row;
12107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12108
12109        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12110            let autoscroll = self
12111                .selections
12112                .all::<Point>(cx)
12113                .iter()
12114                .any(|selection| crease.range().overlaps(&selection.range()));
12115
12116            self.fold_creases(vec![crease], autoscroll, window, cx);
12117        }
12118    }
12119
12120    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12121        if self.is_singleton(cx) {
12122            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12123            let buffer = &display_map.buffer_snapshot;
12124            let selections = self.selections.all::<Point>(cx);
12125            let ranges = selections
12126                .iter()
12127                .map(|s| {
12128                    let range = s.display_range(&display_map).sorted();
12129                    let mut start = range.start.to_point(&display_map);
12130                    let mut end = range.end.to_point(&display_map);
12131                    start.column = 0;
12132                    end.column = buffer.line_len(MultiBufferRow(end.row));
12133                    start..end
12134                })
12135                .collect::<Vec<_>>();
12136
12137            self.unfold_ranges(&ranges, true, true, cx);
12138        } else {
12139            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12140            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12141                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12142                .map(|(snapshot, _, _)| snapshot.remote_id())
12143                .collect();
12144            for buffer_id in buffer_ids {
12145                self.unfold_buffer(buffer_id, cx);
12146            }
12147        }
12148    }
12149
12150    pub fn unfold_recursive(
12151        &mut self,
12152        _: &UnfoldRecursive,
12153        _window: &mut Window,
12154        cx: &mut Context<Self>,
12155    ) {
12156        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12157        let selections = self.selections.all::<Point>(cx);
12158        let ranges = selections
12159            .iter()
12160            .map(|s| {
12161                let mut range = s.display_range(&display_map).sorted();
12162                *range.start.column_mut() = 0;
12163                *range.end.column_mut() = display_map.line_len(range.end.row());
12164                let start = range.start.to_point(&display_map);
12165                let end = range.end.to_point(&display_map);
12166                start..end
12167            })
12168            .collect::<Vec<_>>();
12169
12170        self.unfold_ranges(&ranges, true, true, cx);
12171    }
12172
12173    pub fn unfold_at(
12174        &mut self,
12175        unfold_at: &UnfoldAt,
12176        _window: &mut Window,
12177        cx: &mut Context<Self>,
12178    ) {
12179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12180
12181        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12182            ..Point::new(
12183                unfold_at.buffer_row.0,
12184                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12185            );
12186
12187        let autoscroll = self
12188            .selections
12189            .all::<Point>(cx)
12190            .iter()
12191            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12192
12193        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12194    }
12195
12196    pub fn unfold_all(
12197        &mut self,
12198        _: &actions::UnfoldAll,
12199        _window: &mut Window,
12200        cx: &mut Context<Self>,
12201    ) {
12202        if self.buffer.read(cx).is_singleton() {
12203            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12204            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12205        } else {
12206            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12207                editor
12208                    .update(&mut cx, |editor, cx| {
12209                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12210                            editor.unfold_buffer(buffer_id, cx);
12211                        }
12212                    })
12213                    .ok();
12214            });
12215        }
12216    }
12217
12218    pub fn fold_selected_ranges(
12219        &mut self,
12220        _: &FoldSelectedRanges,
12221        window: &mut Window,
12222        cx: &mut Context<Self>,
12223    ) {
12224        let selections = self.selections.all::<Point>(cx);
12225        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12226        let line_mode = self.selections.line_mode;
12227        let ranges = selections
12228            .into_iter()
12229            .map(|s| {
12230                if line_mode {
12231                    let start = Point::new(s.start.row, 0);
12232                    let end = Point::new(
12233                        s.end.row,
12234                        display_map
12235                            .buffer_snapshot
12236                            .line_len(MultiBufferRow(s.end.row)),
12237                    );
12238                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12239                } else {
12240                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12241                }
12242            })
12243            .collect::<Vec<_>>();
12244        self.fold_creases(ranges, true, window, cx);
12245    }
12246
12247    pub fn fold_ranges<T: ToOffset + Clone>(
12248        &mut self,
12249        ranges: Vec<Range<T>>,
12250        auto_scroll: bool,
12251        window: &mut Window,
12252        cx: &mut Context<Self>,
12253    ) {
12254        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12255        let ranges = ranges
12256            .into_iter()
12257            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12258            .collect::<Vec<_>>();
12259        self.fold_creases(ranges, auto_scroll, window, cx);
12260    }
12261
12262    pub fn fold_creases<T: ToOffset + Clone>(
12263        &mut self,
12264        creases: Vec<Crease<T>>,
12265        auto_scroll: bool,
12266        window: &mut Window,
12267        cx: &mut Context<Self>,
12268    ) {
12269        if creases.is_empty() {
12270            return;
12271        }
12272
12273        let mut buffers_affected = HashSet::default();
12274        let multi_buffer = self.buffer().read(cx);
12275        for crease in &creases {
12276            if let Some((_, buffer, _)) =
12277                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12278            {
12279                buffers_affected.insert(buffer.read(cx).remote_id());
12280            };
12281        }
12282
12283        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12284
12285        if auto_scroll {
12286            self.request_autoscroll(Autoscroll::fit(), cx);
12287        }
12288
12289        cx.notify();
12290
12291        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12292            // Clear diagnostics block when folding a range that contains it.
12293            let snapshot = self.snapshot(window, cx);
12294            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12295                drop(snapshot);
12296                self.active_diagnostics = Some(active_diagnostics);
12297                self.dismiss_diagnostics(cx);
12298            } else {
12299                self.active_diagnostics = Some(active_diagnostics);
12300            }
12301        }
12302
12303        self.scrollbar_marker_state.dirty = true;
12304    }
12305
12306    /// Removes any folds whose ranges intersect any of the given ranges.
12307    pub fn unfold_ranges<T: ToOffset + Clone>(
12308        &mut self,
12309        ranges: &[Range<T>],
12310        inclusive: bool,
12311        auto_scroll: bool,
12312        cx: &mut Context<Self>,
12313    ) {
12314        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12315            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12316        });
12317    }
12318
12319    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12320        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12321            return;
12322        }
12323        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12324        self.display_map
12325            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12326        cx.emit(EditorEvent::BufferFoldToggled {
12327            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12328            folded: true,
12329        });
12330        cx.notify();
12331    }
12332
12333    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12334        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12335            return;
12336        }
12337        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12338        self.display_map.update(cx, |display_map, cx| {
12339            display_map.unfold_buffer(buffer_id, cx);
12340        });
12341        cx.emit(EditorEvent::BufferFoldToggled {
12342            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12343            folded: false,
12344        });
12345        cx.notify();
12346    }
12347
12348    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12349        self.display_map.read(cx).is_buffer_folded(buffer)
12350    }
12351
12352    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12353        self.display_map.read(cx).folded_buffers()
12354    }
12355
12356    /// Removes any folds with the given ranges.
12357    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12358        &mut self,
12359        ranges: &[Range<T>],
12360        type_id: TypeId,
12361        auto_scroll: bool,
12362        cx: &mut Context<Self>,
12363    ) {
12364        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12365            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12366        });
12367    }
12368
12369    fn remove_folds_with<T: ToOffset + Clone>(
12370        &mut self,
12371        ranges: &[Range<T>],
12372        auto_scroll: bool,
12373        cx: &mut Context<Self>,
12374        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12375    ) {
12376        if ranges.is_empty() {
12377            return;
12378        }
12379
12380        let mut buffers_affected = HashSet::default();
12381        let multi_buffer = self.buffer().read(cx);
12382        for range in ranges {
12383            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12384                buffers_affected.insert(buffer.read(cx).remote_id());
12385            };
12386        }
12387
12388        self.display_map.update(cx, update);
12389
12390        if auto_scroll {
12391            self.request_autoscroll(Autoscroll::fit(), cx);
12392        }
12393
12394        cx.notify();
12395        self.scrollbar_marker_state.dirty = true;
12396        self.active_indent_guides_state.dirty = true;
12397    }
12398
12399    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12400        self.display_map.read(cx).fold_placeholder.clone()
12401    }
12402
12403    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12404        self.buffer.update(cx, |buffer, cx| {
12405            buffer.set_all_diff_hunks_expanded(cx);
12406        });
12407    }
12408
12409    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12410        self.distinguish_unstaged_diff_hunks = true;
12411    }
12412
12413    pub fn expand_all_diff_hunks(
12414        &mut self,
12415        _: &ExpandAllHunkDiffs,
12416        _window: &mut Window,
12417        cx: &mut Context<Self>,
12418    ) {
12419        self.buffer.update(cx, |buffer, cx| {
12420            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12421        });
12422    }
12423
12424    pub fn toggle_selected_diff_hunks(
12425        &mut self,
12426        _: &ToggleSelectedDiffHunks,
12427        _window: &mut Window,
12428        cx: &mut Context<Self>,
12429    ) {
12430        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12431        self.toggle_diff_hunks_in_ranges(ranges, cx);
12432    }
12433
12434    fn diff_hunks_in_ranges<'a>(
12435        &'a self,
12436        ranges: &'a [Range<Anchor>],
12437        buffer: &'a MultiBufferSnapshot,
12438    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12439        ranges.iter().flat_map(move |range| {
12440            let end_excerpt_id = range.end.excerpt_id;
12441            let range = range.to_point(buffer);
12442            let mut peek_end = range.end;
12443            if range.end.row < buffer.max_row().0 {
12444                peek_end = Point::new(range.end.row + 1, 0);
12445            }
12446            buffer
12447                .diff_hunks_in_range(range.start..peek_end)
12448                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12449        })
12450    }
12451
12452    pub fn has_stageable_diff_hunks_in_ranges(
12453        &self,
12454        ranges: &[Range<Anchor>],
12455        snapshot: &MultiBufferSnapshot,
12456    ) -> bool {
12457        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12458        hunks.any(|hunk| {
12459            log::debug!("considering {hunk:?}");
12460            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12461        })
12462    }
12463
12464    pub fn toggle_staged_selected_diff_hunks(
12465        &mut self,
12466        _: &ToggleStagedSelectedDiffHunks,
12467        _window: &mut Window,
12468        cx: &mut Context<Self>,
12469    ) {
12470        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12471        self.stage_or_unstage_diff_hunks(&ranges, cx);
12472    }
12473
12474    pub fn stage_or_unstage_diff_hunks(
12475        &mut self,
12476        ranges: &[Range<Anchor>],
12477        cx: &mut Context<Self>,
12478    ) {
12479        let Some(project) = &self.project else {
12480            return;
12481        };
12482        let snapshot = self.buffer.read(cx).snapshot(cx);
12483        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12484
12485        let chunk_by = self
12486            .diff_hunks_in_ranges(&ranges, &snapshot)
12487            .chunk_by(|hunk| hunk.buffer_id);
12488        for (buffer_id, hunks) in &chunk_by {
12489            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12490                log::debug!("no buffer for id");
12491                continue;
12492            };
12493            let buffer = buffer.read(cx).snapshot();
12494            let Some((repo, path)) = project
12495                .read(cx)
12496                .repository_and_path_for_buffer_id(buffer_id, cx)
12497            else {
12498                log::debug!("no git repo for buffer id");
12499                continue;
12500            };
12501            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12502                log::debug!("no diff for buffer id");
12503                continue;
12504            };
12505            let Some(secondary_diff) = diff.secondary_diff() else {
12506                log::debug!("no secondary diff for buffer id");
12507                continue;
12508            };
12509
12510            let edits = diff.secondary_edits_for_stage_or_unstage(
12511                stage,
12512                hunks.map(|hunk| {
12513                    (
12514                        hunk.diff_base_byte_range.clone(),
12515                        hunk.secondary_diff_base_byte_range.clone(),
12516                        hunk.buffer_range.clone(),
12517                    )
12518                }),
12519                &buffer,
12520            );
12521
12522            let index_base = secondary_diff.base_text().map_or_else(
12523                || Rope::from(""),
12524                |snapshot| snapshot.text.as_rope().clone(),
12525            );
12526            let index_buffer = cx.new(|cx| {
12527                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12528            });
12529            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12530                index_buffer.edit(edits, None, cx);
12531                index_buffer.snapshot().as_rope().to_string()
12532            });
12533            let new_index_text = if new_index_text.is_empty()
12534                && (diff.is_single_insertion
12535                    || buffer
12536                        .file()
12537                        .map_or(false, |file| file.disk_state() == DiskState::New))
12538            {
12539                log::debug!("removing from index");
12540                None
12541            } else {
12542                Some(new_index_text)
12543            };
12544
12545            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12546        }
12547    }
12548
12549    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12550        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12551        self.buffer
12552            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12553    }
12554
12555    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12556        self.buffer.update(cx, |buffer, cx| {
12557            let ranges = vec![Anchor::min()..Anchor::max()];
12558            if !buffer.all_diff_hunks_expanded()
12559                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12560            {
12561                buffer.collapse_diff_hunks(ranges, cx);
12562                true
12563            } else {
12564                false
12565            }
12566        })
12567    }
12568
12569    fn toggle_diff_hunks_in_ranges(
12570        &mut self,
12571        ranges: Vec<Range<Anchor>>,
12572        cx: &mut Context<'_, Editor>,
12573    ) {
12574        self.buffer.update(cx, |buffer, cx| {
12575            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12576            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12577        })
12578    }
12579
12580    fn toggle_diff_hunks_in_ranges_narrow(
12581        &mut self,
12582        ranges: Vec<Range<Anchor>>,
12583        cx: &mut Context<'_, Editor>,
12584    ) {
12585        self.buffer.update(cx, |buffer, cx| {
12586            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12587            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12588        })
12589    }
12590
12591    pub(crate) fn apply_all_diff_hunks(
12592        &mut self,
12593        _: &ApplyAllDiffHunks,
12594        window: &mut Window,
12595        cx: &mut Context<Self>,
12596    ) {
12597        let buffers = self.buffer.read(cx).all_buffers();
12598        for branch_buffer in buffers {
12599            branch_buffer.update(cx, |branch_buffer, cx| {
12600                branch_buffer.merge_into_base(Vec::new(), cx);
12601            });
12602        }
12603
12604        if let Some(project) = self.project.clone() {
12605            self.save(true, project, window, cx).detach_and_log_err(cx);
12606        }
12607    }
12608
12609    pub(crate) fn apply_selected_diff_hunks(
12610        &mut self,
12611        _: &ApplyDiffHunk,
12612        window: &mut Window,
12613        cx: &mut Context<Self>,
12614    ) {
12615        let snapshot = self.snapshot(window, cx);
12616        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12617        let mut ranges_by_buffer = HashMap::default();
12618        self.transact(window, cx, |editor, _window, cx| {
12619            for hunk in hunks {
12620                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12621                    ranges_by_buffer
12622                        .entry(buffer.clone())
12623                        .or_insert_with(Vec::new)
12624                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12625                }
12626            }
12627
12628            for (buffer, ranges) in ranges_by_buffer {
12629                buffer.update(cx, |buffer, cx| {
12630                    buffer.merge_into_base(ranges, cx);
12631                });
12632            }
12633        });
12634
12635        if let Some(project) = self.project.clone() {
12636            self.save(true, project, window, cx).detach_and_log_err(cx);
12637        }
12638    }
12639
12640    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12641        if hovered != self.gutter_hovered {
12642            self.gutter_hovered = hovered;
12643            cx.notify();
12644        }
12645    }
12646
12647    pub fn insert_blocks(
12648        &mut self,
12649        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12650        autoscroll: Option<Autoscroll>,
12651        cx: &mut Context<Self>,
12652    ) -> Vec<CustomBlockId> {
12653        let blocks = self
12654            .display_map
12655            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12656        if let Some(autoscroll) = autoscroll {
12657            self.request_autoscroll(autoscroll, cx);
12658        }
12659        cx.notify();
12660        blocks
12661    }
12662
12663    pub fn resize_blocks(
12664        &mut self,
12665        heights: HashMap<CustomBlockId, u32>,
12666        autoscroll: Option<Autoscroll>,
12667        cx: &mut Context<Self>,
12668    ) {
12669        self.display_map
12670            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12671        if let Some(autoscroll) = autoscroll {
12672            self.request_autoscroll(autoscroll, cx);
12673        }
12674        cx.notify();
12675    }
12676
12677    pub fn replace_blocks(
12678        &mut self,
12679        renderers: HashMap<CustomBlockId, RenderBlock>,
12680        autoscroll: Option<Autoscroll>,
12681        cx: &mut Context<Self>,
12682    ) {
12683        self.display_map
12684            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12685        if let Some(autoscroll) = autoscroll {
12686            self.request_autoscroll(autoscroll, cx);
12687        }
12688        cx.notify();
12689    }
12690
12691    pub fn remove_blocks(
12692        &mut self,
12693        block_ids: HashSet<CustomBlockId>,
12694        autoscroll: Option<Autoscroll>,
12695        cx: &mut Context<Self>,
12696    ) {
12697        self.display_map.update(cx, |display_map, cx| {
12698            display_map.remove_blocks(block_ids, cx)
12699        });
12700        if let Some(autoscroll) = autoscroll {
12701            self.request_autoscroll(autoscroll, cx);
12702        }
12703        cx.notify();
12704    }
12705
12706    pub fn row_for_block(
12707        &self,
12708        block_id: CustomBlockId,
12709        cx: &mut Context<Self>,
12710    ) -> Option<DisplayRow> {
12711        self.display_map
12712            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12713    }
12714
12715    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12716        self.focused_block = Some(focused_block);
12717    }
12718
12719    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12720        self.focused_block.take()
12721    }
12722
12723    pub fn insert_creases(
12724        &mut self,
12725        creases: impl IntoIterator<Item = Crease<Anchor>>,
12726        cx: &mut Context<Self>,
12727    ) -> Vec<CreaseId> {
12728        self.display_map
12729            .update(cx, |map, cx| map.insert_creases(creases, cx))
12730    }
12731
12732    pub fn remove_creases(
12733        &mut self,
12734        ids: impl IntoIterator<Item = CreaseId>,
12735        cx: &mut Context<Self>,
12736    ) {
12737        self.display_map
12738            .update(cx, |map, cx| map.remove_creases(ids, cx));
12739    }
12740
12741    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12742        self.display_map
12743            .update(cx, |map, cx| map.snapshot(cx))
12744            .longest_row()
12745    }
12746
12747    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12748        self.display_map
12749            .update(cx, |map, cx| map.snapshot(cx))
12750            .max_point()
12751    }
12752
12753    pub fn text(&self, cx: &App) -> String {
12754        self.buffer.read(cx).read(cx).text()
12755    }
12756
12757    pub fn is_empty(&self, cx: &App) -> bool {
12758        self.buffer.read(cx).read(cx).is_empty()
12759    }
12760
12761    pub fn text_option(&self, cx: &App) -> Option<String> {
12762        let text = self.text(cx);
12763        let text = text.trim();
12764
12765        if text.is_empty() {
12766            return None;
12767        }
12768
12769        Some(text.to_string())
12770    }
12771
12772    pub fn set_text(
12773        &mut self,
12774        text: impl Into<Arc<str>>,
12775        window: &mut Window,
12776        cx: &mut Context<Self>,
12777    ) {
12778        self.transact(window, cx, |this, _, cx| {
12779            this.buffer
12780                .read(cx)
12781                .as_singleton()
12782                .expect("you can only call set_text on editors for singleton buffers")
12783                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12784        });
12785    }
12786
12787    pub fn display_text(&self, cx: &mut App) -> String {
12788        self.display_map
12789            .update(cx, |map, cx| map.snapshot(cx))
12790            .text()
12791    }
12792
12793    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12794        let mut wrap_guides = smallvec::smallvec![];
12795
12796        if self.show_wrap_guides == Some(false) {
12797            return wrap_guides;
12798        }
12799
12800        let settings = self.buffer.read(cx).settings_at(0, cx);
12801        if settings.show_wrap_guides {
12802            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12803                wrap_guides.push((soft_wrap as usize, true));
12804            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12805                wrap_guides.push((soft_wrap as usize, true));
12806            }
12807            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12808        }
12809
12810        wrap_guides
12811    }
12812
12813    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12814        let settings = self.buffer.read(cx).settings_at(0, cx);
12815        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12816        match mode {
12817            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12818                SoftWrap::None
12819            }
12820            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12821            language_settings::SoftWrap::PreferredLineLength => {
12822                SoftWrap::Column(settings.preferred_line_length)
12823            }
12824            language_settings::SoftWrap::Bounded => {
12825                SoftWrap::Bounded(settings.preferred_line_length)
12826            }
12827        }
12828    }
12829
12830    pub fn set_soft_wrap_mode(
12831        &mut self,
12832        mode: language_settings::SoftWrap,
12833
12834        cx: &mut Context<Self>,
12835    ) {
12836        self.soft_wrap_mode_override = Some(mode);
12837        cx.notify();
12838    }
12839
12840    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12841        self.text_style_refinement = Some(style);
12842    }
12843
12844    /// called by the Element so we know what style we were most recently rendered with.
12845    pub(crate) fn set_style(
12846        &mut self,
12847        style: EditorStyle,
12848        window: &mut Window,
12849        cx: &mut Context<Self>,
12850    ) {
12851        let rem_size = window.rem_size();
12852        self.display_map.update(cx, |map, cx| {
12853            map.set_font(
12854                style.text.font(),
12855                style.text.font_size.to_pixels(rem_size),
12856                cx,
12857            )
12858        });
12859        self.style = Some(style);
12860    }
12861
12862    pub fn style(&self) -> Option<&EditorStyle> {
12863        self.style.as_ref()
12864    }
12865
12866    // Called by the element. This method is not designed to be called outside of the editor
12867    // element's layout code because it does not notify when rewrapping is computed synchronously.
12868    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12869        self.display_map
12870            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12871    }
12872
12873    pub fn set_soft_wrap(&mut self) {
12874        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12875    }
12876
12877    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12878        if self.soft_wrap_mode_override.is_some() {
12879            self.soft_wrap_mode_override.take();
12880        } else {
12881            let soft_wrap = match self.soft_wrap_mode(cx) {
12882                SoftWrap::GitDiff => return,
12883                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12884                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12885                    language_settings::SoftWrap::None
12886                }
12887            };
12888            self.soft_wrap_mode_override = Some(soft_wrap);
12889        }
12890        cx.notify();
12891    }
12892
12893    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12894        let Some(workspace) = self.workspace() else {
12895            return;
12896        };
12897        let fs = workspace.read(cx).app_state().fs.clone();
12898        let current_show = TabBarSettings::get_global(cx).show;
12899        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12900            setting.show = Some(!current_show);
12901        });
12902    }
12903
12904    pub fn toggle_indent_guides(
12905        &mut self,
12906        _: &ToggleIndentGuides,
12907        _: &mut Window,
12908        cx: &mut Context<Self>,
12909    ) {
12910        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12911            self.buffer
12912                .read(cx)
12913                .settings_at(0, cx)
12914                .indent_guides
12915                .enabled
12916        });
12917        self.show_indent_guides = Some(!currently_enabled);
12918        cx.notify();
12919    }
12920
12921    fn should_show_indent_guides(&self) -> Option<bool> {
12922        self.show_indent_guides
12923    }
12924
12925    pub fn toggle_line_numbers(
12926        &mut self,
12927        _: &ToggleLineNumbers,
12928        _: &mut Window,
12929        cx: &mut Context<Self>,
12930    ) {
12931        let mut editor_settings = EditorSettings::get_global(cx).clone();
12932        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12933        EditorSettings::override_global(editor_settings, cx);
12934    }
12935
12936    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12937        self.use_relative_line_numbers
12938            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12939    }
12940
12941    pub fn toggle_relative_line_numbers(
12942        &mut self,
12943        _: &ToggleRelativeLineNumbers,
12944        _: &mut Window,
12945        cx: &mut Context<Self>,
12946    ) {
12947        let is_relative = self.should_use_relative_line_numbers(cx);
12948        self.set_relative_line_number(Some(!is_relative), cx)
12949    }
12950
12951    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12952        self.use_relative_line_numbers = is_relative;
12953        cx.notify();
12954    }
12955
12956    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12957        self.show_gutter = show_gutter;
12958        cx.notify();
12959    }
12960
12961    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12962        self.show_scrollbars = show_scrollbars;
12963        cx.notify();
12964    }
12965
12966    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12967        self.show_line_numbers = Some(show_line_numbers);
12968        cx.notify();
12969    }
12970
12971    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12972        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12973        cx.notify();
12974    }
12975
12976    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12977        self.show_code_actions = Some(show_code_actions);
12978        cx.notify();
12979    }
12980
12981    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12982        self.show_runnables = Some(show_runnables);
12983        cx.notify();
12984    }
12985
12986    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12987        if self.display_map.read(cx).masked != masked {
12988            self.display_map.update(cx, |map, _| map.masked = masked);
12989        }
12990        cx.notify()
12991    }
12992
12993    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12994        self.show_wrap_guides = Some(show_wrap_guides);
12995        cx.notify();
12996    }
12997
12998    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12999        self.show_indent_guides = Some(show_indent_guides);
13000        cx.notify();
13001    }
13002
13003    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13004        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13005            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13006                if let Some(dir) = file.abs_path(cx).parent() {
13007                    return Some(dir.to_owned());
13008                }
13009            }
13010
13011            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13012                return Some(project_path.path.to_path_buf());
13013            }
13014        }
13015
13016        None
13017    }
13018
13019    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13020        self.active_excerpt(cx)?
13021            .1
13022            .read(cx)
13023            .file()
13024            .and_then(|f| f.as_local())
13025    }
13026
13027    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13028        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13029            let buffer = buffer.read(cx);
13030            if let Some(project_path) = buffer.project_path(cx) {
13031                let project = self.project.as_ref()?.read(cx);
13032                project.absolute_path(&project_path, cx)
13033            } else {
13034                buffer
13035                    .file()
13036                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13037            }
13038        })
13039    }
13040
13041    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13042        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13043            let project_path = buffer.read(cx).project_path(cx)?;
13044            let project = self.project.as_ref()?.read(cx);
13045            let entry = project.entry_for_path(&project_path, cx)?;
13046            let path = entry.path.to_path_buf();
13047            Some(path)
13048        })
13049    }
13050
13051    pub fn reveal_in_finder(
13052        &mut self,
13053        _: &RevealInFileManager,
13054        _window: &mut Window,
13055        cx: &mut Context<Self>,
13056    ) {
13057        if let Some(target) = self.target_file(cx) {
13058            cx.reveal_path(&target.abs_path(cx));
13059        }
13060    }
13061
13062    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13063        if let Some(path) = self.target_file_abs_path(cx) {
13064            if let Some(path) = path.to_str() {
13065                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13066            }
13067        }
13068    }
13069
13070    pub fn copy_relative_path(
13071        &mut self,
13072        _: &CopyRelativePath,
13073        _window: &mut Window,
13074        cx: &mut Context<Self>,
13075    ) {
13076        if let Some(path) = self.target_file_path(cx) {
13077            if let Some(path) = path.to_str() {
13078                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13079            }
13080        }
13081    }
13082
13083    pub fn copy_file_name_without_extension(
13084        &mut self,
13085        _: &CopyFileNameWithoutExtension,
13086        _: &mut Window,
13087        cx: &mut Context<Self>,
13088    ) {
13089        if let Some(file) = self.target_file(cx) {
13090            if let Some(file_stem) = file.path().file_stem() {
13091                if let Some(name) = file_stem.to_str() {
13092                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13093                }
13094            }
13095        }
13096    }
13097
13098    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13099        if let Some(file) = self.target_file(cx) {
13100            if let Some(file_name) = file.path().file_name() {
13101                if let Some(name) = file_name.to_str() {
13102                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13103                }
13104            }
13105        }
13106    }
13107
13108    pub fn toggle_git_blame(
13109        &mut self,
13110        _: &ToggleGitBlame,
13111        window: &mut Window,
13112        cx: &mut Context<Self>,
13113    ) {
13114        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13115
13116        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13117            self.start_git_blame(true, window, cx);
13118        }
13119
13120        cx.notify();
13121    }
13122
13123    pub fn toggle_git_blame_inline(
13124        &mut self,
13125        _: &ToggleGitBlameInline,
13126        window: &mut Window,
13127        cx: &mut Context<Self>,
13128    ) {
13129        self.toggle_git_blame_inline_internal(true, window, cx);
13130        cx.notify();
13131    }
13132
13133    pub fn git_blame_inline_enabled(&self) -> bool {
13134        self.git_blame_inline_enabled
13135    }
13136
13137    pub fn toggle_selection_menu(
13138        &mut self,
13139        _: &ToggleSelectionMenu,
13140        _: &mut Window,
13141        cx: &mut Context<Self>,
13142    ) {
13143        self.show_selection_menu = self
13144            .show_selection_menu
13145            .map(|show_selections_menu| !show_selections_menu)
13146            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13147
13148        cx.notify();
13149    }
13150
13151    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13152        self.show_selection_menu
13153            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13154    }
13155
13156    fn start_git_blame(
13157        &mut self,
13158        user_triggered: bool,
13159        window: &mut Window,
13160        cx: &mut Context<Self>,
13161    ) {
13162        if let Some(project) = self.project.as_ref() {
13163            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13164                return;
13165            };
13166
13167            if buffer.read(cx).file().is_none() {
13168                return;
13169            }
13170
13171            let focused = self.focus_handle(cx).contains_focused(window, cx);
13172
13173            let project = project.clone();
13174            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13175            self.blame_subscription =
13176                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13177            self.blame = Some(blame);
13178        }
13179    }
13180
13181    fn toggle_git_blame_inline_internal(
13182        &mut self,
13183        user_triggered: bool,
13184        window: &mut Window,
13185        cx: &mut Context<Self>,
13186    ) {
13187        if self.git_blame_inline_enabled {
13188            self.git_blame_inline_enabled = false;
13189            self.show_git_blame_inline = false;
13190            self.show_git_blame_inline_delay_task.take();
13191        } else {
13192            self.git_blame_inline_enabled = true;
13193            self.start_git_blame_inline(user_triggered, window, cx);
13194        }
13195
13196        cx.notify();
13197    }
13198
13199    fn start_git_blame_inline(
13200        &mut self,
13201        user_triggered: bool,
13202        window: &mut Window,
13203        cx: &mut Context<Self>,
13204    ) {
13205        self.start_git_blame(user_triggered, window, cx);
13206
13207        if ProjectSettings::get_global(cx)
13208            .git
13209            .inline_blame_delay()
13210            .is_some()
13211        {
13212            self.start_inline_blame_timer(window, cx);
13213        } else {
13214            self.show_git_blame_inline = true
13215        }
13216    }
13217
13218    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13219        self.blame.as_ref()
13220    }
13221
13222    pub fn show_git_blame_gutter(&self) -> bool {
13223        self.show_git_blame_gutter
13224    }
13225
13226    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13227        self.show_git_blame_gutter && self.has_blame_entries(cx)
13228    }
13229
13230    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13231        self.show_git_blame_inline
13232            && self.focus_handle.is_focused(window)
13233            && !self.newest_selection_head_on_empty_line(cx)
13234            && self.has_blame_entries(cx)
13235    }
13236
13237    fn has_blame_entries(&self, cx: &App) -> bool {
13238        self.blame()
13239            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13240    }
13241
13242    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13243        let cursor_anchor = self.selections.newest_anchor().head();
13244
13245        let snapshot = self.buffer.read(cx).snapshot(cx);
13246        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13247
13248        snapshot.line_len(buffer_row) == 0
13249    }
13250
13251    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13252        let buffer_and_selection = maybe!({
13253            let selection = self.selections.newest::<Point>(cx);
13254            let selection_range = selection.range();
13255
13256            let multi_buffer = self.buffer().read(cx);
13257            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13258            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13259
13260            let (buffer, range, _) = if selection.reversed {
13261                buffer_ranges.first()
13262            } else {
13263                buffer_ranges.last()
13264            }?;
13265
13266            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13267                ..text::ToPoint::to_point(&range.end, &buffer).row;
13268            Some((
13269                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13270                selection,
13271            ))
13272        });
13273
13274        let Some((buffer, selection)) = buffer_and_selection else {
13275            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13276        };
13277
13278        let Some(project) = self.project.as_ref() else {
13279            return Task::ready(Err(anyhow!("editor does not have project")));
13280        };
13281
13282        project.update(cx, |project, cx| {
13283            project.get_permalink_to_line(&buffer, selection, cx)
13284        })
13285    }
13286
13287    pub fn copy_permalink_to_line(
13288        &mut self,
13289        _: &CopyPermalinkToLine,
13290        window: &mut Window,
13291        cx: &mut Context<Self>,
13292    ) {
13293        let permalink_task = self.get_permalink_to_line(cx);
13294        let workspace = self.workspace();
13295
13296        cx.spawn_in(window, |_, mut cx| async move {
13297            match permalink_task.await {
13298                Ok(permalink) => {
13299                    cx.update(|_, cx| {
13300                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13301                    })
13302                    .ok();
13303                }
13304                Err(err) => {
13305                    let message = format!("Failed to copy permalink: {err}");
13306
13307                    Err::<(), anyhow::Error>(err).log_err();
13308
13309                    if let Some(workspace) = workspace {
13310                        workspace
13311                            .update_in(&mut cx, |workspace, _, cx| {
13312                                struct CopyPermalinkToLine;
13313
13314                                workspace.show_toast(
13315                                    Toast::new(
13316                                        NotificationId::unique::<CopyPermalinkToLine>(),
13317                                        message,
13318                                    ),
13319                                    cx,
13320                                )
13321                            })
13322                            .ok();
13323                    }
13324                }
13325            }
13326        })
13327        .detach();
13328    }
13329
13330    pub fn copy_file_location(
13331        &mut self,
13332        _: &CopyFileLocation,
13333        _: &mut Window,
13334        cx: &mut Context<Self>,
13335    ) {
13336        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13337        if let Some(file) = self.target_file(cx) {
13338            if let Some(path) = file.path().to_str() {
13339                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13340            }
13341        }
13342    }
13343
13344    pub fn open_permalink_to_line(
13345        &mut self,
13346        _: &OpenPermalinkToLine,
13347        window: &mut Window,
13348        cx: &mut Context<Self>,
13349    ) {
13350        let permalink_task = self.get_permalink_to_line(cx);
13351        let workspace = self.workspace();
13352
13353        cx.spawn_in(window, |_, mut cx| async move {
13354            match permalink_task.await {
13355                Ok(permalink) => {
13356                    cx.update(|_, cx| {
13357                        cx.open_url(permalink.as_ref());
13358                    })
13359                    .ok();
13360                }
13361                Err(err) => {
13362                    let message = format!("Failed to open permalink: {err}");
13363
13364                    Err::<(), anyhow::Error>(err).log_err();
13365
13366                    if let Some(workspace) = workspace {
13367                        workspace
13368                            .update(&mut cx, |workspace, cx| {
13369                                struct OpenPermalinkToLine;
13370
13371                                workspace.show_toast(
13372                                    Toast::new(
13373                                        NotificationId::unique::<OpenPermalinkToLine>(),
13374                                        message,
13375                                    ),
13376                                    cx,
13377                                )
13378                            })
13379                            .ok();
13380                    }
13381                }
13382            }
13383        })
13384        .detach();
13385    }
13386
13387    pub fn insert_uuid_v4(
13388        &mut self,
13389        _: &InsertUuidV4,
13390        window: &mut Window,
13391        cx: &mut Context<Self>,
13392    ) {
13393        self.insert_uuid(UuidVersion::V4, window, cx);
13394    }
13395
13396    pub fn insert_uuid_v7(
13397        &mut self,
13398        _: &InsertUuidV7,
13399        window: &mut Window,
13400        cx: &mut Context<Self>,
13401    ) {
13402        self.insert_uuid(UuidVersion::V7, window, cx);
13403    }
13404
13405    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13406        self.transact(window, cx, |this, window, cx| {
13407            let edits = this
13408                .selections
13409                .all::<Point>(cx)
13410                .into_iter()
13411                .map(|selection| {
13412                    let uuid = match version {
13413                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13414                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13415                    };
13416
13417                    (selection.range(), uuid.to_string())
13418                });
13419            this.edit(edits, cx);
13420            this.refresh_inline_completion(true, false, window, cx);
13421        });
13422    }
13423
13424    pub fn open_selections_in_multibuffer(
13425        &mut self,
13426        _: &OpenSelectionsInMultibuffer,
13427        window: &mut Window,
13428        cx: &mut Context<Self>,
13429    ) {
13430        let multibuffer = self.buffer.read(cx);
13431
13432        let Some(buffer) = multibuffer.as_singleton() else {
13433            return;
13434        };
13435
13436        let Some(workspace) = self.workspace() else {
13437            return;
13438        };
13439
13440        let locations = self
13441            .selections
13442            .disjoint_anchors()
13443            .iter()
13444            .map(|range| Location {
13445                buffer: buffer.clone(),
13446                range: range.start.text_anchor..range.end.text_anchor,
13447            })
13448            .collect::<Vec<_>>();
13449
13450        let title = multibuffer.title(cx).to_string();
13451
13452        cx.spawn_in(window, |_, mut cx| async move {
13453            workspace.update_in(&mut cx, |workspace, window, cx| {
13454                Self::open_locations_in_multibuffer(
13455                    workspace,
13456                    locations,
13457                    format!("Selections for '{title}'"),
13458                    false,
13459                    MultibufferSelectionMode::All,
13460                    window,
13461                    cx,
13462                );
13463            })
13464        })
13465        .detach();
13466    }
13467
13468    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13469    /// last highlight added will be used.
13470    ///
13471    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13472    pub fn highlight_rows<T: 'static>(
13473        &mut self,
13474        range: Range<Anchor>,
13475        color: Hsla,
13476        should_autoscroll: bool,
13477        cx: &mut Context<Self>,
13478    ) {
13479        let snapshot = self.buffer().read(cx).snapshot(cx);
13480        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13481        let ix = row_highlights.binary_search_by(|highlight| {
13482            Ordering::Equal
13483                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13484                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13485        });
13486
13487        if let Err(mut ix) = ix {
13488            let index = post_inc(&mut self.highlight_order);
13489
13490            // If this range intersects with the preceding highlight, then merge it with
13491            // the preceding highlight. Otherwise insert a new highlight.
13492            let mut merged = false;
13493            if ix > 0 {
13494                let prev_highlight = &mut row_highlights[ix - 1];
13495                if prev_highlight
13496                    .range
13497                    .end
13498                    .cmp(&range.start, &snapshot)
13499                    .is_ge()
13500                {
13501                    ix -= 1;
13502                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13503                        prev_highlight.range.end = range.end;
13504                    }
13505                    merged = true;
13506                    prev_highlight.index = index;
13507                    prev_highlight.color = color;
13508                    prev_highlight.should_autoscroll = should_autoscroll;
13509                }
13510            }
13511
13512            if !merged {
13513                row_highlights.insert(
13514                    ix,
13515                    RowHighlight {
13516                        range: range.clone(),
13517                        index,
13518                        color,
13519                        should_autoscroll,
13520                    },
13521                );
13522            }
13523
13524            // If any of the following highlights intersect with this one, merge them.
13525            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13526                let highlight = &row_highlights[ix];
13527                if next_highlight
13528                    .range
13529                    .start
13530                    .cmp(&highlight.range.end, &snapshot)
13531                    .is_le()
13532                {
13533                    if next_highlight
13534                        .range
13535                        .end
13536                        .cmp(&highlight.range.end, &snapshot)
13537                        .is_gt()
13538                    {
13539                        row_highlights[ix].range.end = next_highlight.range.end;
13540                    }
13541                    row_highlights.remove(ix + 1);
13542                } else {
13543                    break;
13544                }
13545            }
13546        }
13547    }
13548
13549    /// Remove any highlighted row ranges of the given type that intersect the
13550    /// given ranges.
13551    pub fn remove_highlighted_rows<T: 'static>(
13552        &mut self,
13553        ranges_to_remove: Vec<Range<Anchor>>,
13554        cx: &mut Context<Self>,
13555    ) {
13556        let snapshot = self.buffer().read(cx).snapshot(cx);
13557        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13558        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13559        row_highlights.retain(|highlight| {
13560            while let Some(range_to_remove) = ranges_to_remove.peek() {
13561                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13562                    Ordering::Less | Ordering::Equal => {
13563                        ranges_to_remove.next();
13564                    }
13565                    Ordering::Greater => {
13566                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13567                            Ordering::Less | Ordering::Equal => {
13568                                return false;
13569                            }
13570                            Ordering::Greater => break,
13571                        }
13572                    }
13573                }
13574            }
13575
13576            true
13577        })
13578    }
13579
13580    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13581    pub fn clear_row_highlights<T: 'static>(&mut self) {
13582        self.highlighted_rows.remove(&TypeId::of::<T>());
13583    }
13584
13585    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13586    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13587        self.highlighted_rows
13588            .get(&TypeId::of::<T>())
13589            .map_or(&[] as &[_], |vec| vec.as_slice())
13590            .iter()
13591            .map(|highlight| (highlight.range.clone(), highlight.color))
13592    }
13593
13594    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13595    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13596    /// Allows to ignore certain kinds of highlights.
13597    pub fn highlighted_display_rows(
13598        &self,
13599        window: &mut Window,
13600        cx: &mut App,
13601    ) -> BTreeMap<DisplayRow, Background> {
13602        let snapshot = self.snapshot(window, cx);
13603        let mut used_highlight_orders = HashMap::default();
13604        self.highlighted_rows
13605            .iter()
13606            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13607            .fold(
13608                BTreeMap::<DisplayRow, Background>::new(),
13609                |mut unique_rows, highlight| {
13610                    let start = highlight.range.start.to_display_point(&snapshot);
13611                    let end = highlight.range.end.to_display_point(&snapshot);
13612                    let start_row = start.row().0;
13613                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13614                        && end.column() == 0
13615                    {
13616                        end.row().0.saturating_sub(1)
13617                    } else {
13618                        end.row().0
13619                    };
13620                    for row in start_row..=end_row {
13621                        let used_index =
13622                            used_highlight_orders.entry(row).or_insert(highlight.index);
13623                        if highlight.index >= *used_index {
13624                            *used_index = highlight.index;
13625                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13626                        }
13627                    }
13628                    unique_rows
13629                },
13630            )
13631    }
13632
13633    pub fn highlighted_display_row_for_autoscroll(
13634        &self,
13635        snapshot: &DisplaySnapshot,
13636    ) -> Option<DisplayRow> {
13637        self.highlighted_rows
13638            .values()
13639            .flat_map(|highlighted_rows| highlighted_rows.iter())
13640            .filter_map(|highlight| {
13641                if highlight.should_autoscroll {
13642                    Some(highlight.range.start.to_display_point(snapshot).row())
13643                } else {
13644                    None
13645                }
13646            })
13647            .min()
13648    }
13649
13650    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13651        self.highlight_background::<SearchWithinRange>(
13652            ranges,
13653            |colors| colors.editor_document_highlight_read_background,
13654            cx,
13655        )
13656    }
13657
13658    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13659        self.breadcrumb_header = Some(new_header);
13660    }
13661
13662    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13663        self.clear_background_highlights::<SearchWithinRange>(cx);
13664    }
13665
13666    pub fn highlight_background<T: 'static>(
13667        &mut self,
13668        ranges: &[Range<Anchor>],
13669        color_fetcher: fn(&ThemeColors) -> Hsla,
13670        cx: &mut Context<Self>,
13671    ) {
13672        self.background_highlights
13673            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13674        self.scrollbar_marker_state.dirty = true;
13675        cx.notify();
13676    }
13677
13678    pub fn clear_background_highlights<T: 'static>(
13679        &mut self,
13680        cx: &mut Context<Self>,
13681    ) -> Option<BackgroundHighlight> {
13682        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13683        if !text_highlights.1.is_empty() {
13684            self.scrollbar_marker_state.dirty = true;
13685            cx.notify();
13686        }
13687        Some(text_highlights)
13688    }
13689
13690    pub fn highlight_gutter<T: 'static>(
13691        &mut self,
13692        ranges: &[Range<Anchor>],
13693        color_fetcher: fn(&App) -> Hsla,
13694        cx: &mut Context<Self>,
13695    ) {
13696        self.gutter_highlights
13697            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13698        cx.notify();
13699    }
13700
13701    pub fn clear_gutter_highlights<T: 'static>(
13702        &mut self,
13703        cx: &mut Context<Self>,
13704    ) -> Option<GutterHighlight> {
13705        cx.notify();
13706        self.gutter_highlights.remove(&TypeId::of::<T>())
13707    }
13708
13709    #[cfg(feature = "test-support")]
13710    pub fn all_text_background_highlights(
13711        &self,
13712        window: &mut Window,
13713        cx: &mut Context<Self>,
13714    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13715        let snapshot = self.snapshot(window, cx);
13716        let buffer = &snapshot.buffer_snapshot;
13717        let start = buffer.anchor_before(0);
13718        let end = buffer.anchor_after(buffer.len());
13719        let theme = cx.theme().colors();
13720        self.background_highlights_in_range(start..end, &snapshot, theme)
13721    }
13722
13723    #[cfg(feature = "test-support")]
13724    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13725        let snapshot = self.buffer().read(cx).snapshot(cx);
13726
13727        let highlights = self
13728            .background_highlights
13729            .get(&TypeId::of::<items::BufferSearchHighlights>());
13730
13731        if let Some((_color, ranges)) = highlights {
13732            ranges
13733                .iter()
13734                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13735                .collect_vec()
13736        } else {
13737            vec![]
13738        }
13739    }
13740
13741    fn document_highlights_for_position<'a>(
13742        &'a self,
13743        position: Anchor,
13744        buffer: &'a MultiBufferSnapshot,
13745    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13746        let read_highlights = self
13747            .background_highlights
13748            .get(&TypeId::of::<DocumentHighlightRead>())
13749            .map(|h| &h.1);
13750        let write_highlights = self
13751            .background_highlights
13752            .get(&TypeId::of::<DocumentHighlightWrite>())
13753            .map(|h| &h.1);
13754        let left_position = position.bias_left(buffer);
13755        let right_position = position.bias_right(buffer);
13756        read_highlights
13757            .into_iter()
13758            .chain(write_highlights)
13759            .flat_map(move |ranges| {
13760                let start_ix = match ranges.binary_search_by(|probe| {
13761                    let cmp = probe.end.cmp(&left_position, buffer);
13762                    if cmp.is_ge() {
13763                        Ordering::Greater
13764                    } else {
13765                        Ordering::Less
13766                    }
13767                }) {
13768                    Ok(i) | Err(i) => i,
13769                };
13770
13771                ranges[start_ix..]
13772                    .iter()
13773                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13774            })
13775    }
13776
13777    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13778        self.background_highlights
13779            .get(&TypeId::of::<T>())
13780            .map_or(false, |(_, highlights)| !highlights.is_empty())
13781    }
13782
13783    pub fn background_highlights_in_range(
13784        &self,
13785        search_range: Range<Anchor>,
13786        display_snapshot: &DisplaySnapshot,
13787        theme: &ThemeColors,
13788    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13789        let mut results = Vec::new();
13790        for (color_fetcher, ranges) in self.background_highlights.values() {
13791            let color = color_fetcher(theme);
13792            let start_ix = match ranges.binary_search_by(|probe| {
13793                let cmp = probe
13794                    .end
13795                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13796                if cmp.is_gt() {
13797                    Ordering::Greater
13798                } else {
13799                    Ordering::Less
13800                }
13801            }) {
13802                Ok(i) | Err(i) => i,
13803            };
13804            for range in &ranges[start_ix..] {
13805                if range
13806                    .start
13807                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13808                    .is_ge()
13809                {
13810                    break;
13811                }
13812
13813                let start = range.start.to_display_point(display_snapshot);
13814                let end = range.end.to_display_point(display_snapshot);
13815                results.push((start..end, color))
13816            }
13817        }
13818        results
13819    }
13820
13821    pub fn background_highlight_row_ranges<T: 'static>(
13822        &self,
13823        search_range: Range<Anchor>,
13824        display_snapshot: &DisplaySnapshot,
13825        count: usize,
13826    ) -> Vec<RangeInclusive<DisplayPoint>> {
13827        let mut results = Vec::new();
13828        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13829            return vec![];
13830        };
13831
13832        let start_ix = match ranges.binary_search_by(|probe| {
13833            let cmp = probe
13834                .end
13835                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13836            if cmp.is_gt() {
13837                Ordering::Greater
13838            } else {
13839                Ordering::Less
13840            }
13841        }) {
13842            Ok(i) | Err(i) => i,
13843        };
13844        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13845            if let (Some(start_display), Some(end_display)) = (start, end) {
13846                results.push(
13847                    start_display.to_display_point(display_snapshot)
13848                        ..=end_display.to_display_point(display_snapshot),
13849                );
13850            }
13851        };
13852        let mut start_row: Option<Point> = None;
13853        let mut end_row: Option<Point> = None;
13854        if ranges.len() > count {
13855            return Vec::new();
13856        }
13857        for range in &ranges[start_ix..] {
13858            if range
13859                .start
13860                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13861                .is_ge()
13862            {
13863                break;
13864            }
13865            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13866            if let Some(current_row) = &end_row {
13867                if end.row == current_row.row {
13868                    continue;
13869                }
13870            }
13871            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13872            if start_row.is_none() {
13873                assert_eq!(end_row, None);
13874                start_row = Some(start);
13875                end_row = Some(end);
13876                continue;
13877            }
13878            if let Some(current_end) = end_row.as_mut() {
13879                if start.row > current_end.row + 1 {
13880                    push_region(start_row, end_row);
13881                    start_row = Some(start);
13882                    end_row = Some(end);
13883                } else {
13884                    // Merge two hunks.
13885                    *current_end = end;
13886                }
13887            } else {
13888                unreachable!();
13889            }
13890        }
13891        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13892        push_region(start_row, end_row);
13893        results
13894    }
13895
13896    pub fn gutter_highlights_in_range(
13897        &self,
13898        search_range: Range<Anchor>,
13899        display_snapshot: &DisplaySnapshot,
13900        cx: &App,
13901    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13902        let mut results = Vec::new();
13903        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13904            let color = color_fetcher(cx);
13905            let start_ix = match ranges.binary_search_by(|probe| {
13906                let cmp = probe
13907                    .end
13908                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13909                if cmp.is_gt() {
13910                    Ordering::Greater
13911                } else {
13912                    Ordering::Less
13913                }
13914            }) {
13915                Ok(i) | Err(i) => i,
13916            };
13917            for range in &ranges[start_ix..] {
13918                if range
13919                    .start
13920                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13921                    .is_ge()
13922                {
13923                    break;
13924                }
13925
13926                let start = range.start.to_display_point(display_snapshot);
13927                let end = range.end.to_display_point(display_snapshot);
13928                results.push((start..end, color))
13929            }
13930        }
13931        results
13932    }
13933
13934    /// Get the text ranges corresponding to the redaction query
13935    pub fn redacted_ranges(
13936        &self,
13937        search_range: Range<Anchor>,
13938        display_snapshot: &DisplaySnapshot,
13939        cx: &App,
13940    ) -> Vec<Range<DisplayPoint>> {
13941        display_snapshot
13942            .buffer_snapshot
13943            .redacted_ranges(search_range, |file| {
13944                if let Some(file) = file {
13945                    file.is_private()
13946                        && EditorSettings::get(
13947                            Some(SettingsLocation {
13948                                worktree_id: file.worktree_id(cx),
13949                                path: file.path().as_ref(),
13950                            }),
13951                            cx,
13952                        )
13953                        .redact_private_values
13954                } else {
13955                    false
13956                }
13957            })
13958            .map(|range| {
13959                range.start.to_display_point(display_snapshot)
13960                    ..range.end.to_display_point(display_snapshot)
13961            })
13962            .collect()
13963    }
13964
13965    pub fn highlight_text<T: 'static>(
13966        &mut self,
13967        ranges: Vec<Range<Anchor>>,
13968        style: HighlightStyle,
13969        cx: &mut Context<Self>,
13970    ) {
13971        self.display_map.update(cx, |map, _| {
13972            map.highlight_text(TypeId::of::<T>(), ranges, style)
13973        });
13974        cx.notify();
13975    }
13976
13977    pub(crate) fn highlight_inlays<T: 'static>(
13978        &mut self,
13979        highlights: Vec<InlayHighlight>,
13980        style: HighlightStyle,
13981        cx: &mut Context<Self>,
13982    ) {
13983        self.display_map.update(cx, |map, _| {
13984            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13985        });
13986        cx.notify();
13987    }
13988
13989    pub fn text_highlights<'a, T: 'static>(
13990        &'a self,
13991        cx: &'a App,
13992    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13993        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13994    }
13995
13996    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13997        let cleared = self
13998            .display_map
13999            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14000        if cleared {
14001            cx.notify();
14002        }
14003    }
14004
14005    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14006        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14007            && self.focus_handle.is_focused(window)
14008    }
14009
14010    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14011        self.show_cursor_when_unfocused = is_enabled;
14012        cx.notify();
14013    }
14014
14015    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14016        self.project
14017            .as_ref()
14018            .map(|project| project.read(cx).lsp_store())
14019    }
14020
14021    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14022        cx.notify();
14023    }
14024
14025    fn on_buffer_event(
14026        &mut self,
14027        multibuffer: &Entity<MultiBuffer>,
14028        event: &multi_buffer::Event,
14029        window: &mut Window,
14030        cx: &mut Context<Self>,
14031    ) {
14032        match event {
14033            multi_buffer::Event::Edited {
14034                singleton_buffer_edited,
14035                edited_buffer: buffer_edited,
14036            } => {
14037                self.scrollbar_marker_state.dirty = true;
14038                self.active_indent_guides_state.dirty = true;
14039                self.refresh_active_diagnostics(cx);
14040                self.refresh_code_actions(window, cx);
14041                if self.has_active_inline_completion() {
14042                    self.update_visible_inline_completion(window, cx);
14043                }
14044                if let Some(buffer) = buffer_edited {
14045                    let buffer_id = buffer.read(cx).remote_id();
14046                    if !self.registered_buffers.contains_key(&buffer_id) {
14047                        if let Some(lsp_store) = self.lsp_store(cx) {
14048                            lsp_store.update(cx, |lsp_store, cx| {
14049                                self.registered_buffers.insert(
14050                                    buffer_id,
14051                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14052                                );
14053                            })
14054                        }
14055                    }
14056                }
14057                cx.emit(EditorEvent::BufferEdited);
14058                cx.emit(SearchEvent::MatchesInvalidated);
14059                if *singleton_buffer_edited {
14060                    if let Some(project) = &self.project {
14061                        let project = project.read(cx);
14062                        #[allow(clippy::mutable_key_type)]
14063                        let languages_affected = multibuffer
14064                            .read(cx)
14065                            .all_buffers()
14066                            .into_iter()
14067                            .filter_map(|buffer| {
14068                                let buffer = buffer.read(cx);
14069                                let language = buffer.language()?;
14070                                if project.is_local()
14071                                    && project
14072                                        .language_servers_for_local_buffer(buffer, cx)
14073                                        .count()
14074                                        == 0
14075                                {
14076                                    None
14077                                } else {
14078                                    Some(language)
14079                                }
14080                            })
14081                            .cloned()
14082                            .collect::<HashSet<_>>();
14083                        if !languages_affected.is_empty() {
14084                            self.refresh_inlay_hints(
14085                                InlayHintRefreshReason::BufferEdited(languages_affected),
14086                                cx,
14087                            );
14088                        }
14089                    }
14090                }
14091
14092                let Some(project) = &self.project else { return };
14093                let (telemetry, is_via_ssh) = {
14094                    let project = project.read(cx);
14095                    let telemetry = project.client().telemetry().clone();
14096                    let is_via_ssh = project.is_via_ssh();
14097                    (telemetry, is_via_ssh)
14098                };
14099                refresh_linked_ranges(self, window, cx);
14100                telemetry.log_edit_event("editor", is_via_ssh);
14101            }
14102            multi_buffer::Event::ExcerptsAdded {
14103                buffer,
14104                predecessor,
14105                excerpts,
14106            } => {
14107                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14108                let buffer_id = buffer.read(cx).remote_id();
14109                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14110                    if let Some(project) = &self.project {
14111                        get_uncommitted_diff_for_buffer(
14112                            project,
14113                            [buffer.clone()],
14114                            self.buffer.clone(),
14115                            cx,
14116                        );
14117                    }
14118                }
14119                cx.emit(EditorEvent::ExcerptsAdded {
14120                    buffer: buffer.clone(),
14121                    predecessor: *predecessor,
14122                    excerpts: excerpts.clone(),
14123                });
14124                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14125            }
14126            multi_buffer::Event::ExcerptsRemoved { ids } => {
14127                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14128                let buffer = self.buffer.read(cx);
14129                self.registered_buffers
14130                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14131                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14132            }
14133            multi_buffer::Event::ExcerptsEdited { ids } => {
14134                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14135            }
14136            multi_buffer::Event::ExcerptsExpanded { ids } => {
14137                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14138                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14139            }
14140            multi_buffer::Event::Reparsed(buffer_id) => {
14141                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14142
14143                cx.emit(EditorEvent::Reparsed(*buffer_id));
14144            }
14145            multi_buffer::Event::DiffHunksToggled => {
14146                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14147            }
14148            multi_buffer::Event::LanguageChanged(buffer_id) => {
14149                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14150                cx.emit(EditorEvent::Reparsed(*buffer_id));
14151                cx.notify();
14152            }
14153            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14154            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14155            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14156                cx.emit(EditorEvent::TitleChanged)
14157            }
14158            // multi_buffer::Event::DiffBaseChanged => {
14159            //     self.scrollbar_marker_state.dirty = true;
14160            //     cx.emit(EditorEvent::DiffBaseChanged);
14161            //     cx.notify();
14162            // }
14163            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14164            multi_buffer::Event::DiagnosticsUpdated => {
14165                self.refresh_active_diagnostics(cx);
14166                self.scrollbar_marker_state.dirty = true;
14167                cx.notify();
14168            }
14169            _ => {}
14170        };
14171    }
14172
14173    fn on_display_map_changed(
14174        &mut self,
14175        _: Entity<DisplayMap>,
14176        _: &mut Window,
14177        cx: &mut Context<Self>,
14178    ) {
14179        cx.notify();
14180    }
14181
14182    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14183        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14184        self.refresh_inline_completion(true, false, window, cx);
14185        self.refresh_inlay_hints(
14186            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14187                self.selections.newest_anchor().head(),
14188                &self.buffer.read(cx).snapshot(cx),
14189                cx,
14190            )),
14191            cx,
14192        );
14193
14194        let old_cursor_shape = self.cursor_shape;
14195
14196        {
14197            let editor_settings = EditorSettings::get_global(cx);
14198            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14199            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14200            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14201        }
14202
14203        if old_cursor_shape != self.cursor_shape {
14204            cx.emit(EditorEvent::CursorShapeChanged);
14205        }
14206
14207        let project_settings = ProjectSettings::get_global(cx);
14208        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14209
14210        if self.mode == EditorMode::Full {
14211            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14212            if self.git_blame_inline_enabled != inline_blame_enabled {
14213                self.toggle_git_blame_inline_internal(false, window, cx);
14214            }
14215        }
14216
14217        cx.notify();
14218    }
14219
14220    pub fn set_searchable(&mut self, searchable: bool) {
14221        self.searchable = searchable;
14222    }
14223
14224    pub fn searchable(&self) -> bool {
14225        self.searchable
14226    }
14227
14228    fn open_proposed_changes_editor(
14229        &mut self,
14230        _: &OpenProposedChangesEditor,
14231        window: &mut Window,
14232        cx: &mut Context<Self>,
14233    ) {
14234        let Some(workspace) = self.workspace() else {
14235            cx.propagate();
14236            return;
14237        };
14238
14239        let selections = self.selections.all::<usize>(cx);
14240        let multi_buffer = self.buffer.read(cx);
14241        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14242        let mut new_selections_by_buffer = HashMap::default();
14243        for selection in selections {
14244            for (buffer, range, _) in
14245                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14246            {
14247                let mut range = range.to_point(buffer);
14248                range.start.column = 0;
14249                range.end.column = buffer.line_len(range.end.row);
14250                new_selections_by_buffer
14251                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14252                    .or_insert(Vec::new())
14253                    .push(range)
14254            }
14255        }
14256
14257        let proposed_changes_buffers = new_selections_by_buffer
14258            .into_iter()
14259            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14260            .collect::<Vec<_>>();
14261        let proposed_changes_editor = cx.new(|cx| {
14262            ProposedChangesEditor::new(
14263                "Proposed changes",
14264                proposed_changes_buffers,
14265                self.project.clone(),
14266                window,
14267                cx,
14268            )
14269        });
14270
14271        window.defer(cx, move |window, cx| {
14272            workspace.update(cx, |workspace, cx| {
14273                workspace.active_pane().update(cx, |pane, cx| {
14274                    pane.add_item(
14275                        Box::new(proposed_changes_editor),
14276                        true,
14277                        true,
14278                        None,
14279                        window,
14280                        cx,
14281                    );
14282                });
14283            });
14284        });
14285    }
14286
14287    pub fn open_excerpts_in_split(
14288        &mut self,
14289        _: &OpenExcerptsSplit,
14290        window: &mut Window,
14291        cx: &mut Context<Self>,
14292    ) {
14293        self.open_excerpts_common(None, true, window, cx)
14294    }
14295
14296    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14297        self.open_excerpts_common(None, false, window, cx)
14298    }
14299
14300    fn open_excerpts_common(
14301        &mut self,
14302        jump_data: Option<JumpData>,
14303        split: bool,
14304        window: &mut Window,
14305        cx: &mut Context<Self>,
14306    ) {
14307        let Some(workspace) = self.workspace() else {
14308            cx.propagate();
14309            return;
14310        };
14311
14312        if self.buffer.read(cx).is_singleton() {
14313            cx.propagate();
14314            return;
14315        }
14316
14317        let mut new_selections_by_buffer = HashMap::default();
14318        match &jump_data {
14319            Some(JumpData::MultiBufferPoint {
14320                excerpt_id,
14321                position,
14322                anchor,
14323                line_offset_from_top,
14324            }) => {
14325                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14326                if let Some(buffer) = multi_buffer_snapshot
14327                    .buffer_id_for_excerpt(*excerpt_id)
14328                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14329                {
14330                    let buffer_snapshot = buffer.read(cx).snapshot();
14331                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14332                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14333                    } else {
14334                        buffer_snapshot.clip_point(*position, Bias::Left)
14335                    };
14336                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14337                    new_selections_by_buffer.insert(
14338                        buffer,
14339                        (
14340                            vec![jump_to_offset..jump_to_offset],
14341                            Some(*line_offset_from_top),
14342                        ),
14343                    );
14344                }
14345            }
14346            Some(JumpData::MultiBufferRow {
14347                row,
14348                line_offset_from_top,
14349            }) => {
14350                let point = MultiBufferPoint::new(row.0, 0);
14351                if let Some((buffer, buffer_point, _)) =
14352                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14353                {
14354                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14355                    new_selections_by_buffer
14356                        .entry(buffer)
14357                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14358                        .0
14359                        .push(buffer_offset..buffer_offset)
14360                }
14361            }
14362            None => {
14363                let selections = self.selections.all::<usize>(cx);
14364                let multi_buffer = self.buffer.read(cx);
14365                for selection in selections {
14366                    for (buffer, mut range, _) in multi_buffer
14367                        .snapshot(cx)
14368                        .range_to_buffer_ranges(selection.range())
14369                    {
14370                        // When editing branch buffers, jump to the corresponding location
14371                        // in their base buffer.
14372                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14373                        let buffer = buffer_handle.read(cx);
14374                        if let Some(base_buffer) = buffer.base_buffer() {
14375                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14376                            buffer_handle = base_buffer;
14377                        }
14378
14379                        if selection.reversed {
14380                            mem::swap(&mut range.start, &mut range.end);
14381                        }
14382                        new_selections_by_buffer
14383                            .entry(buffer_handle)
14384                            .or_insert((Vec::new(), None))
14385                            .0
14386                            .push(range)
14387                    }
14388                }
14389            }
14390        }
14391
14392        if new_selections_by_buffer.is_empty() {
14393            return;
14394        }
14395
14396        // We defer the pane interaction because we ourselves are a workspace item
14397        // and activating a new item causes the pane to call a method on us reentrantly,
14398        // which panics if we're on the stack.
14399        window.defer(cx, move |window, cx| {
14400            workspace.update(cx, |workspace, cx| {
14401                let pane = if split {
14402                    workspace.adjacent_pane(window, cx)
14403                } else {
14404                    workspace.active_pane().clone()
14405                };
14406
14407                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14408                    let editor = buffer
14409                        .read(cx)
14410                        .file()
14411                        .is_none()
14412                        .then(|| {
14413                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14414                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14415                            // Instead, we try to activate the existing editor in the pane first.
14416                            let (editor, pane_item_index) =
14417                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14418                                    let editor = item.downcast::<Editor>()?;
14419                                    let singleton_buffer =
14420                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14421                                    if singleton_buffer == buffer {
14422                                        Some((editor, i))
14423                                    } else {
14424                                        None
14425                                    }
14426                                })?;
14427                            pane.update(cx, |pane, cx| {
14428                                pane.activate_item(pane_item_index, true, true, window, cx)
14429                            });
14430                            Some(editor)
14431                        })
14432                        .flatten()
14433                        .unwrap_or_else(|| {
14434                            workspace.open_project_item::<Self>(
14435                                pane.clone(),
14436                                buffer,
14437                                true,
14438                                true,
14439                                window,
14440                                cx,
14441                            )
14442                        });
14443
14444                    editor.update(cx, |editor, cx| {
14445                        let autoscroll = match scroll_offset {
14446                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14447                            None => Autoscroll::newest(),
14448                        };
14449                        let nav_history = editor.nav_history.take();
14450                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14451                            s.select_ranges(ranges);
14452                        });
14453                        editor.nav_history = nav_history;
14454                    });
14455                }
14456            })
14457        });
14458    }
14459
14460    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14461        let snapshot = self.buffer.read(cx).read(cx);
14462        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14463        Some(
14464            ranges
14465                .iter()
14466                .map(move |range| {
14467                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14468                })
14469                .collect(),
14470        )
14471    }
14472
14473    fn selection_replacement_ranges(
14474        &self,
14475        range: Range<OffsetUtf16>,
14476        cx: &mut App,
14477    ) -> Vec<Range<OffsetUtf16>> {
14478        let selections = self.selections.all::<OffsetUtf16>(cx);
14479        let newest_selection = selections
14480            .iter()
14481            .max_by_key(|selection| selection.id)
14482            .unwrap();
14483        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14484        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14485        let snapshot = self.buffer.read(cx).read(cx);
14486        selections
14487            .into_iter()
14488            .map(|mut selection| {
14489                selection.start.0 =
14490                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14491                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14492                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14493                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14494            })
14495            .collect()
14496    }
14497
14498    fn report_editor_event(
14499        &self,
14500        event_type: &'static str,
14501        file_extension: Option<String>,
14502        cx: &App,
14503    ) {
14504        if cfg!(any(test, feature = "test-support")) {
14505            return;
14506        }
14507
14508        let Some(project) = &self.project else { return };
14509
14510        // If None, we are in a file without an extension
14511        let file = self
14512            .buffer
14513            .read(cx)
14514            .as_singleton()
14515            .and_then(|b| b.read(cx).file());
14516        let file_extension = file_extension.or(file
14517            .as_ref()
14518            .and_then(|file| Path::new(file.file_name(cx)).extension())
14519            .and_then(|e| e.to_str())
14520            .map(|a| a.to_string()));
14521
14522        let vim_mode = cx
14523            .global::<SettingsStore>()
14524            .raw_user_settings()
14525            .get("vim_mode")
14526            == Some(&serde_json::Value::Bool(true));
14527
14528        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14529        let copilot_enabled = edit_predictions_provider
14530            == language::language_settings::EditPredictionProvider::Copilot;
14531        let copilot_enabled_for_language = self
14532            .buffer
14533            .read(cx)
14534            .settings_at(0, cx)
14535            .show_edit_predictions;
14536
14537        let project = project.read(cx);
14538        telemetry::event!(
14539            event_type,
14540            file_extension,
14541            vim_mode,
14542            copilot_enabled,
14543            copilot_enabled_for_language,
14544            edit_predictions_provider,
14545            is_via_ssh = project.is_via_ssh(),
14546        );
14547    }
14548
14549    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14550    /// with each line being an array of {text, highlight} objects.
14551    fn copy_highlight_json(
14552        &mut self,
14553        _: &CopyHighlightJson,
14554        window: &mut Window,
14555        cx: &mut Context<Self>,
14556    ) {
14557        #[derive(Serialize)]
14558        struct Chunk<'a> {
14559            text: String,
14560            highlight: Option<&'a str>,
14561        }
14562
14563        let snapshot = self.buffer.read(cx).snapshot(cx);
14564        let range = self
14565            .selected_text_range(false, window, cx)
14566            .and_then(|selection| {
14567                if selection.range.is_empty() {
14568                    None
14569                } else {
14570                    Some(selection.range)
14571                }
14572            })
14573            .unwrap_or_else(|| 0..snapshot.len());
14574
14575        let chunks = snapshot.chunks(range, true);
14576        let mut lines = Vec::new();
14577        let mut line: VecDeque<Chunk> = VecDeque::new();
14578
14579        let Some(style) = self.style.as_ref() else {
14580            return;
14581        };
14582
14583        for chunk in chunks {
14584            let highlight = chunk
14585                .syntax_highlight_id
14586                .and_then(|id| id.name(&style.syntax));
14587            let mut chunk_lines = chunk.text.split('\n').peekable();
14588            while let Some(text) = chunk_lines.next() {
14589                let mut merged_with_last_token = false;
14590                if let Some(last_token) = line.back_mut() {
14591                    if last_token.highlight == highlight {
14592                        last_token.text.push_str(text);
14593                        merged_with_last_token = true;
14594                    }
14595                }
14596
14597                if !merged_with_last_token {
14598                    line.push_back(Chunk {
14599                        text: text.into(),
14600                        highlight,
14601                    });
14602                }
14603
14604                if chunk_lines.peek().is_some() {
14605                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14606                        line.pop_front();
14607                    }
14608                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14609                        line.pop_back();
14610                    }
14611
14612                    lines.push(mem::take(&mut line));
14613                }
14614            }
14615        }
14616
14617        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14618            return;
14619        };
14620        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14621    }
14622
14623    pub fn open_context_menu(
14624        &mut self,
14625        _: &OpenContextMenu,
14626        window: &mut Window,
14627        cx: &mut Context<Self>,
14628    ) {
14629        self.request_autoscroll(Autoscroll::newest(), cx);
14630        let position = self.selections.newest_display(cx).start;
14631        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14632    }
14633
14634    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14635        &self.inlay_hint_cache
14636    }
14637
14638    pub fn replay_insert_event(
14639        &mut self,
14640        text: &str,
14641        relative_utf16_range: Option<Range<isize>>,
14642        window: &mut Window,
14643        cx: &mut Context<Self>,
14644    ) {
14645        if !self.input_enabled {
14646            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14647            return;
14648        }
14649        if let Some(relative_utf16_range) = relative_utf16_range {
14650            let selections = self.selections.all::<OffsetUtf16>(cx);
14651            self.change_selections(None, window, cx, |s| {
14652                let new_ranges = selections.into_iter().map(|range| {
14653                    let start = OffsetUtf16(
14654                        range
14655                            .head()
14656                            .0
14657                            .saturating_add_signed(relative_utf16_range.start),
14658                    );
14659                    let end = OffsetUtf16(
14660                        range
14661                            .head()
14662                            .0
14663                            .saturating_add_signed(relative_utf16_range.end),
14664                    );
14665                    start..end
14666                });
14667                s.select_ranges(new_ranges);
14668            });
14669        }
14670
14671        self.handle_input(text, window, cx);
14672    }
14673
14674    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14675        let Some(provider) = self.semantics_provider.as_ref() else {
14676            return false;
14677        };
14678
14679        let mut supports = false;
14680        self.buffer().read(cx).for_each_buffer(|buffer| {
14681            supports |= provider.supports_inlay_hints(buffer, cx);
14682        });
14683        supports
14684    }
14685
14686    pub fn is_focused(&self, window: &Window) -> bool {
14687        self.focus_handle.is_focused(window)
14688    }
14689
14690    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14691        cx.emit(EditorEvent::Focused);
14692
14693        if let Some(descendant) = self
14694            .last_focused_descendant
14695            .take()
14696            .and_then(|descendant| descendant.upgrade())
14697        {
14698            window.focus(&descendant);
14699        } else {
14700            if let Some(blame) = self.blame.as_ref() {
14701                blame.update(cx, GitBlame::focus)
14702            }
14703
14704            self.blink_manager.update(cx, BlinkManager::enable);
14705            self.show_cursor_names(window, cx);
14706            self.buffer.update(cx, |buffer, cx| {
14707                buffer.finalize_last_transaction(cx);
14708                if self.leader_peer_id.is_none() {
14709                    buffer.set_active_selections(
14710                        &self.selections.disjoint_anchors(),
14711                        self.selections.line_mode,
14712                        self.cursor_shape,
14713                        cx,
14714                    );
14715                }
14716            });
14717        }
14718    }
14719
14720    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14721        cx.emit(EditorEvent::FocusedIn)
14722    }
14723
14724    fn handle_focus_out(
14725        &mut self,
14726        event: FocusOutEvent,
14727        _window: &mut Window,
14728        _cx: &mut Context<Self>,
14729    ) {
14730        if event.blurred != self.focus_handle {
14731            self.last_focused_descendant = Some(event.blurred);
14732        }
14733    }
14734
14735    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14736        self.blink_manager.update(cx, BlinkManager::disable);
14737        self.buffer
14738            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14739
14740        if let Some(blame) = self.blame.as_ref() {
14741            blame.update(cx, GitBlame::blur)
14742        }
14743        if !self.hover_state.focused(window, cx) {
14744            hide_hover(self, cx);
14745        }
14746
14747        self.hide_context_menu(window, cx);
14748        self.discard_inline_completion(false, cx);
14749        cx.emit(EditorEvent::Blurred);
14750        cx.notify();
14751    }
14752
14753    pub fn register_action<A: Action>(
14754        &mut self,
14755        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14756    ) -> Subscription {
14757        let id = self.next_editor_action_id.post_inc();
14758        let listener = Arc::new(listener);
14759        self.editor_actions.borrow_mut().insert(
14760            id,
14761            Box::new(move |window, _| {
14762                let listener = listener.clone();
14763                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14764                    let action = action.downcast_ref().unwrap();
14765                    if phase == DispatchPhase::Bubble {
14766                        listener(action, window, cx)
14767                    }
14768                })
14769            }),
14770        );
14771
14772        let editor_actions = self.editor_actions.clone();
14773        Subscription::new(move || {
14774            editor_actions.borrow_mut().remove(&id);
14775        })
14776    }
14777
14778    pub fn file_header_size(&self) -> u32 {
14779        FILE_HEADER_HEIGHT
14780    }
14781
14782    pub fn revert(
14783        &mut self,
14784        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14785        window: &mut Window,
14786        cx: &mut Context<Self>,
14787    ) {
14788        self.buffer().update(cx, |multi_buffer, cx| {
14789            for (buffer_id, changes) in revert_changes {
14790                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14791                    buffer.update(cx, |buffer, cx| {
14792                        buffer.edit(
14793                            changes.into_iter().map(|(range, text)| {
14794                                (range, text.to_string().map(Arc::<str>::from))
14795                            }),
14796                            None,
14797                            cx,
14798                        );
14799                    });
14800                }
14801            }
14802        });
14803        self.change_selections(None, window, cx, |selections| selections.refresh());
14804    }
14805
14806    pub fn to_pixel_point(
14807        &self,
14808        source: multi_buffer::Anchor,
14809        editor_snapshot: &EditorSnapshot,
14810        window: &mut Window,
14811    ) -> Option<gpui::Point<Pixels>> {
14812        let source_point = source.to_display_point(editor_snapshot);
14813        self.display_to_pixel_point(source_point, editor_snapshot, window)
14814    }
14815
14816    pub fn display_to_pixel_point(
14817        &self,
14818        source: DisplayPoint,
14819        editor_snapshot: &EditorSnapshot,
14820        window: &mut Window,
14821    ) -> Option<gpui::Point<Pixels>> {
14822        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14823        let text_layout_details = self.text_layout_details(window);
14824        let scroll_top = text_layout_details
14825            .scroll_anchor
14826            .scroll_position(editor_snapshot)
14827            .y;
14828
14829        if source.row().as_f32() < scroll_top.floor() {
14830            return None;
14831        }
14832        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14833        let source_y = line_height * (source.row().as_f32() - scroll_top);
14834        Some(gpui::Point::new(source_x, source_y))
14835    }
14836
14837    pub fn has_visible_completions_menu(&self) -> bool {
14838        !self.edit_prediction_preview_is_active()
14839            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14840                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14841            })
14842    }
14843
14844    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14845        self.addons
14846            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14847    }
14848
14849    pub fn unregister_addon<T: Addon>(&mut self) {
14850        self.addons.remove(&std::any::TypeId::of::<T>());
14851    }
14852
14853    pub fn addon<T: Addon>(&self) -> Option<&T> {
14854        let type_id = std::any::TypeId::of::<T>();
14855        self.addons
14856            .get(&type_id)
14857            .and_then(|item| item.to_any().downcast_ref::<T>())
14858    }
14859
14860    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14861        let text_layout_details = self.text_layout_details(window);
14862        let style = &text_layout_details.editor_style;
14863        let font_id = window.text_system().resolve_font(&style.text.font());
14864        let font_size = style.text.font_size.to_pixels(window.rem_size());
14865        let line_height = style.text.line_height_in_pixels(window.rem_size());
14866        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14867
14868        gpui::Size::new(em_width, line_height)
14869    }
14870}
14871
14872fn get_uncommitted_diff_for_buffer(
14873    project: &Entity<Project>,
14874    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14875    buffer: Entity<MultiBuffer>,
14876    cx: &mut App,
14877) {
14878    let mut tasks = Vec::new();
14879    project.update(cx, |project, cx| {
14880        for buffer in buffers {
14881            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14882        }
14883    });
14884    cx.spawn(|mut cx| async move {
14885        let diffs = futures::future::join_all(tasks).await;
14886        buffer
14887            .update(&mut cx, |buffer, cx| {
14888                for diff in diffs.into_iter().flatten() {
14889                    buffer.add_diff(diff, cx);
14890                }
14891            })
14892            .ok();
14893    })
14894    .detach();
14895}
14896
14897fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14898    let tab_size = tab_size.get() as usize;
14899    let mut width = offset;
14900
14901    for ch in text.chars() {
14902        width += if ch == '\t' {
14903            tab_size - (width % tab_size)
14904        } else {
14905            1
14906        };
14907    }
14908
14909    width - offset
14910}
14911
14912#[cfg(test)]
14913mod tests {
14914    use super::*;
14915
14916    #[test]
14917    fn test_string_size_with_expanded_tabs() {
14918        let nz = |val| NonZeroU32::new(val).unwrap();
14919        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14920        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14921        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14922        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14923        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14924        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14925        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14926        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14927    }
14928}
14929
14930/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14931struct WordBreakingTokenizer<'a> {
14932    input: &'a str,
14933}
14934
14935impl<'a> WordBreakingTokenizer<'a> {
14936    fn new(input: &'a str) -> Self {
14937        Self { input }
14938    }
14939}
14940
14941fn is_char_ideographic(ch: char) -> bool {
14942    use unicode_script::Script::*;
14943    use unicode_script::UnicodeScript;
14944    matches!(ch.script(), Han | Tangut | Yi)
14945}
14946
14947fn is_grapheme_ideographic(text: &str) -> bool {
14948    text.chars().any(is_char_ideographic)
14949}
14950
14951fn is_grapheme_whitespace(text: &str) -> bool {
14952    text.chars().any(|x| x.is_whitespace())
14953}
14954
14955fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14956    text.chars().next().map_or(false, |ch| {
14957        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14958    })
14959}
14960
14961#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14962struct WordBreakToken<'a> {
14963    token: &'a str,
14964    grapheme_len: usize,
14965    is_whitespace: bool,
14966}
14967
14968impl<'a> Iterator for WordBreakingTokenizer<'a> {
14969    /// Yields a span, the count of graphemes in the token, and whether it was
14970    /// whitespace. Note that it also breaks at word boundaries.
14971    type Item = WordBreakToken<'a>;
14972
14973    fn next(&mut self) -> Option<Self::Item> {
14974        use unicode_segmentation::UnicodeSegmentation;
14975        if self.input.is_empty() {
14976            return None;
14977        }
14978
14979        let mut iter = self.input.graphemes(true).peekable();
14980        let mut offset = 0;
14981        let mut graphemes = 0;
14982        if let Some(first_grapheme) = iter.next() {
14983            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14984            offset += first_grapheme.len();
14985            graphemes += 1;
14986            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14987                if let Some(grapheme) = iter.peek().copied() {
14988                    if should_stay_with_preceding_ideograph(grapheme) {
14989                        offset += grapheme.len();
14990                        graphemes += 1;
14991                    }
14992                }
14993            } else {
14994                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14995                let mut next_word_bound = words.peek().copied();
14996                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14997                    next_word_bound = words.next();
14998                }
14999                while let Some(grapheme) = iter.peek().copied() {
15000                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15001                        break;
15002                    };
15003                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15004                        break;
15005                    };
15006                    offset += grapheme.len();
15007                    graphemes += 1;
15008                    iter.next();
15009                }
15010            }
15011            let token = &self.input[..offset];
15012            self.input = &self.input[offset..];
15013            if is_whitespace {
15014                Some(WordBreakToken {
15015                    token: " ",
15016                    grapheme_len: 1,
15017                    is_whitespace: true,
15018                })
15019            } else {
15020                Some(WordBreakToken {
15021                    token,
15022                    grapheme_len: graphemes,
15023                    is_whitespace: false,
15024                })
15025            }
15026        } else {
15027            None
15028        }
15029    }
15030}
15031
15032#[test]
15033fn test_word_breaking_tokenizer() {
15034    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15035        ("", &[]),
15036        ("  ", &[(" ", 1, true)]),
15037        ("Ʒ", &[("Ʒ", 1, false)]),
15038        ("Ǽ", &[("Ǽ", 1, false)]),
15039        ("", &[("", 1, false)]),
15040        ("⋑⋑", &[("⋑⋑", 2, false)]),
15041        (
15042            "原理,进而",
15043            &[
15044                ("", 1, false),
15045                ("理,", 2, false),
15046                ("", 1, false),
15047                ("", 1, false),
15048            ],
15049        ),
15050        (
15051            "hello world",
15052            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15053        ),
15054        (
15055            "hello, world",
15056            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15057        ),
15058        (
15059            "  hello world",
15060            &[
15061                (" ", 1, true),
15062                ("hello", 5, false),
15063                (" ", 1, true),
15064                ("world", 5, false),
15065            ],
15066        ),
15067        (
15068            "这是什么 \n 钢笔",
15069            &[
15070                ("", 1, false),
15071                ("", 1, false),
15072                ("", 1, false),
15073                ("", 1, false),
15074                (" ", 1, true),
15075                ("", 1, false),
15076                ("", 1, false),
15077            ],
15078        ),
15079        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15080    ];
15081
15082    for (input, result) in tests {
15083        assert_eq!(
15084            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15085            result
15086                .iter()
15087                .copied()
15088                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15089                    token,
15090                    grapheme_len,
15091                    is_whitespace,
15092                })
15093                .collect::<Vec<_>>()
15094        );
15095    }
15096}
15097
15098fn wrap_with_prefix(
15099    line_prefix: String,
15100    unwrapped_text: String,
15101    wrap_column: usize,
15102    tab_size: NonZeroU32,
15103) -> String {
15104    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15105    let mut wrapped_text = String::new();
15106    let mut current_line = line_prefix.clone();
15107
15108    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15109    let mut current_line_len = line_prefix_len;
15110    for WordBreakToken {
15111        token,
15112        grapheme_len,
15113        is_whitespace,
15114    } in tokenizer
15115    {
15116        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15117            wrapped_text.push_str(current_line.trim_end());
15118            wrapped_text.push('\n');
15119            current_line.truncate(line_prefix.len());
15120            current_line_len = line_prefix_len;
15121            if !is_whitespace {
15122                current_line.push_str(token);
15123                current_line_len += grapheme_len;
15124            }
15125        } else if !is_whitespace {
15126            current_line.push_str(token);
15127            current_line_len += grapheme_len;
15128        } else if current_line_len != line_prefix_len {
15129            current_line.push(' ');
15130            current_line_len += 1;
15131        }
15132    }
15133
15134    if !current_line.is_empty() {
15135        wrapped_text.push_str(&current_line);
15136    }
15137    wrapped_text
15138}
15139
15140#[test]
15141fn test_wrap_with_prefix() {
15142    assert_eq!(
15143        wrap_with_prefix(
15144            "# ".to_string(),
15145            "abcdefg".to_string(),
15146            4,
15147            NonZeroU32::new(4).unwrap()
15148        ),
15149        "# abcdefg"
15150    );
15151    assert_eq!(
15152        wrap_with_prefix(
15153            "".to_string(),
15154            "\thello world".to_string(),
15155            8,
15156            NonZeroU32::new(4).unwrap()
15157        ),
15158        "hello\nworld"
15159    );
15160    assert_eq!(
15161        wrap_with_prefix(
15162            "// ".to_string(),
15163            "xx \nyy zz aa bb cc".to_string(),
15164            12,
15165            NonZeroU32::new(4).unwrap()
15166        ),
15167        "// xx yy zz\n// aa bb cc"
15168    );
15169    assert_eq!(
15170        wrap_with_prefix(
15171            String::new(),
15172            "这是什么 \n 钢笔".to_string(),
15173            3,
15174            NonZeroU32::new(4).unwrap()
15175        ),
15176        "这是什\n么 钢\n"
15177    );
15178}
15179
15180pub trait CollaborationHub {
15181    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15182    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15183    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15184}
15185
15186impl CollaborationHub for Entity<Project> {
15187    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15188        self.read(cx).collaborators()
15189    }
15190
15191    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15192        self.read(cx).user_store().read(cx).participant_indices()
15193    }
15194
15195    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15196        let this = self.read(cx);
15197        let user_ids = this.collaborators().values().map(|c| c.user_id);
15198        this.user_store().read_with(cx, |user_store, cx| {
15199            user_store.participant_names(user_ids, cx)
15200        })
15201    }
15202}
15203
15204pub trait SemanticsProvider {
15205    fn hover(
15206        &self,
15207        buffer: &Entity<Buffer>,
15208        position: text::Anchor,
15209        cx: &mut App,
15210    ) -> Option<Task<Vec<project::Hover>>>;
15211
15212    fn inlay_hints(
15213        &self,
15214        buffer_handle: Entity<Buffer>,
15215        range: Range<text::Anchor>,
15216        cx: &mut App,
15217    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15218
15219    fn resolve_inlay_hint(
15220        &self,
15221        hint: InlayHint,
15222        buffer_handle: Entity<Buffer>,
15223        server_id: LanguageServerId,
15224        cx: &mut App,
15225    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15226
15227    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15228
15229    fn document_highlights(
15230        &self,
15231        buffer: &Entity<Buffer>,
15232        position: text::Anchor,
15233        cx: &mut App,
15234    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15235
15236    fn definitions(
15237        &self,
15238        buffer: &Entity<Buffer>,
15239        position: text::Anchor,
15240        kind: GotoDefinitionKind,
15241        cx: &mut App,
15242    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15243
15244    fn range_for_rename(
15245        &self,
15246        buffer: &Entity<Buffer>,
15247        position: text::Anchor,
15248        cx: &mut App,
15249    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15250
15251    fn perform_rename(
15252        &self,
15253        buffer: &Entity<Buffer>,
15254        position: text::Anchor,
15255        new_name: String,
15256        cx: &mut App,
15257    ) -> Option<Task<Result<ProjectTransaction>>>;
15258}
15259
15260pub trait CompletionProvider {
15261    fn completions(
15262        &self,
15263        buffer: &Entity<Buffer>,
15264        buffer_position: text::Anchor,
15265        trigger: CompletionContext,
15266        window: &mut Window,
15267        cx: &mut Context<Editor>,
15268    ) -> Task<Result<Vec<Completion>>>;
15269
15270    fn resolve_completions(
15271        &self,
15272        buffer: Entity<Buffer>,
15273        completion_indices: Vec<usize>,
15274        completions: Rc<RefCell<Box<[Completion]>>>,
15275        cx: &mut Context<Editor>,
15276    ) -> Task<Result<bool>>;
15277
15278    fn apply_additional_edits_for_completion(
15279        &self,
15280        _buffer: Entity<Buffer>,
15281        _completions: Rc<RefCell<Box<[Completion]>>>,
15282        _completion_index: usize,
15283        _push_to_history: bool,
15284        _cx: &mut Context<Editor>,
15285    ) -> Task<Result<Option<language::Transaction>>> {
15286        Task::ready(Ok(None))
15287    }
15288
15289    fn is_completion_trigger(
15290        &self,
15291        buffer: &Entity<Buffer>,
15292        position: language::Anchor,
15293        text: &str,
15294        trigger_in_words: bool,
15295        cx: &mut Context<Editor>,
15296    ) -> bool;
15297
15298    fn sort_completions(&self) -> bool {
15299        true
15300    }
15301}
15302
15303pub trait CodeActionProvider {
15304    fn id(&self) -> Arc<str>;
15305
15306    fn code_actions(
15307        &self,
15308        buffer: &Entity<Buffer>,
15309        range: Range<text::Anchor>,
15310        window: &mut Window,
15311        cx: &mut App,
15312    ) -> Task<Result<Vec<CodeAction>>>;
15313
15314    fn apply_code_action(
15315        &self,
15316        buffer_handle: Entity<Buffer>,
15317        action: CodeAction,
15318        excerpt_id: ExcerptId,
15319        push_to_history: bool,
15320        window: &mut Window,
15321        cx: &mut App,
15322    ) -> Task<Result<ProjectTransaction>>;
15323}
15324
15325impl CodeActionProvider for Entity<Project> {
15326    fn id(&self) -> Arc<str> {
15327        "project".into()
15328    }
15329
15330    fn code_actions(
15331        &self,
15332        buffer: &Entity<Buffer>,
15333        range: Range<text::Anchor>,
15334        _window: &mut Window,
15335        cx: &mut App,
15336    ) -> Task<Result<Vec<CodeAction>>> {
15337        self.update(cx, |project, cx| {
15338            project.code_actions(buffer, range, None, cx)
15339        })
15340    }
15341
15342    fn apply_code_action(
15343        &self,
15344        buffer_handle: Entity<Buffer>,
15345        action: CodeAction,
15346        _excerpt_id: ExcerptId,
15347        push_to_history: bool,
15348        _window: &mut Window,
15349        cx: &mut App,
15350    ) -> Task<Result<ProjectTransaction>> {
15351        self.update(cx, |project, cx| {
15352            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15353        })
15354    }
15355}
15356
15357fn snippet_completions(
15358    project: &Project,
15359    buffer: &Entity<Buffer>,
15360    buffer_position: text::Anchor,
15361    cx: &mut App,
15362) -> Task<Result<Vec<Completion>>> {
15363    let language = buffer.read(cx).language_at(buffer_position);
15364    let language_name = language.as_ref().map(|language| language.lsp_id());
15365    let snippet_store = project.snippets().read(cx);
15366    let snippets = snippet_store.snippets_for(language_name, cx);
15367
15368    if snippets.is_empty() {
15369        return Task::ready(Ok(vec![]));
15370    }
15371    let snapshot = buffer.read(cx).text_snapshot();
15372    let chars: String = snapshot
15373        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15374        .collect();
15375
15376    let scope = language.map(|language| language.default_scope());
15377    let executor = cx.background_executor().clone();
15378
15379    cx.background_executor().spawn(async move {
15380        let classifier = CharClassifier::new(scope).for_completion(true);
15381        let mut last_word = chars
15382            .chars()
15383            .take_while(|c| classifier.is_word(*c))
15384            .collect::<String>();
15385        last_word = last_word.chars().rev().collect();
15386
15387        if last_word.is_empty() {
15388            return Ok(vec![]);
15389        }
15390
15391        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15392        let to_lsp = |point: &text::Anchor| {
15393            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15394            point_to_lsp(end)
15395        };
15396        let lsp_end = to_lsp(&buffer_position);
15397
15398        let candidates = snippets
15399            .iter()
15400            .enumerate()
15401            .flat_map(|(ix, snippet)| {
15402                snippet
15403                    .prefix
15404                    .iter()
15405                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15406            })
15407            .collect::<Vec<StringMatchCandidate>>();
15408
15409        let mut matches = fuzzy::match_strings(
15410            &candidates,
15411            &last_word,
15412            last_word.chars().any(|c| c.is_uppercase()),
15413            100,
15414            &Default::default(),
15415            executor,
15416        )
15417        .await;
15418
15419        // Remove all candidates where the query's start does not match the start of any word in the candidate
15420        if let Some(query_start) = last_word.chars().next() {
15421            matches.retain(|string_match| {
15422                split_words(&string_match.string).any(|word| {
15423                    // Check that the first codepoint of the word as lowercase matches the first
15424                    // codepoint of the query as lowercase
15425                    word.chars()
15426                        .flat_map(|codepoint| codepoint.to_lowercase())
15427                        .zip(query_start.to_lowercase())
15428                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15429                })
15430            });
15431        }
15432
15433        let matched_strings = matches
15434            .into_iter()
15435            .map(|m| m.string)
15436            .collect::<HashSet<_>>();
15437
15438        let result: Vec<Completion> = snippets
15439            .into_iter()
15440            .filter_map(|snippet| {
15441                let matching_prefix = snippet
15442                    .prefix
15443                    .iter()
15444                    .find(|prefix| matched_strings.contains(*prefix))?;
15445                let start = as_offset - last_word.len();
15446                let start = snapshot.anchor_before(start);
15447                let range = start..buffer_position;
15448                let lsp_start = to_lsp(&start);
15449                let lsp_range = lsp::Range {
15450                    start: lsp_start,
15451                    end: lsp_end,
15452                };
15453                Some(Completion {
15454                    old_range: range,
15455                    new_text: snippet.body.clone(),
15456                    resolved: false,
15457                    label: CodeLabel {
15458                        text: matching_prefix.clone(),
15459                        runs: vec![],
15460                        filter_range: 0..matching_prefix.len(),
15461                    },
15462                    server_id: LanguageServerId(usize::MAX),
15463                    documentation: snippet
15464                        .description
15465                        .clone()
15466                        .map(CompletionDocumentation::SingleLine),
15467                    lsp_completion: lsp::CompletionItem {
15468                        label: snippet.prefix.first().unwrap().clone(),
15469                        kind: Some(CompletionItemKind::SNIPPET),
15470                        label_details: snippet.description.as_ref().map(|description| {
15471                            lsp::CompletionItemLabelDetails {
15472                                detail: Some(description.clone()),
15473                                description: None,
15474                            }
15475                        }),
15476                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15477                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15478                            lsp::InsertReplaceEdit {
15479                                new_text: snippet.body.clone(),
15480                                insert: lsp_range,
15481                                replace: lsp_range,
15482                            },
15483                        )),
15484                        filter_text: Some(snippet.body.clone()),
15485                        sort_text: Some(char::MAX.to_string()),
15486                        ..Default::default()
15487                    },
15488                    confirm: None,
15489                })
15490            })
15491            .collect();
15492
15493        Ok(result)
15494    })
15495}
15496
15497impl CompletionProvider for Entity<Project> {
15498    fn completions(
15499        &self,
15500        buffer: &Entity<Buffer>,
15501        buffer_position: text::Anchor,
15502        options: CompletionContext,
15503        _window: &mut Window,
15504        cx: &mut Context<Editor>,
15505    ) -> Task<Result<Vec<Completion>>> {
15506        self.update(cx, |project, cx| {
15507            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15508            let project_completions = project.completions(buffer, buffer_position, options, cx);
15509            cx.background_executor().spawn(async move {
15510                let mut completions = project_completions.await?;
15511                let snippets_completions = snippets.await?;
15512                completions.extend(snippets_completions);
15513                Ok(completions)
15514            })
15515        })
15516    }
15517
15518    fn resolve_completions(
15519        &self,
15520        buffer: Entity<Buffer>,
15521        completion_indices: Vec<usize>,
15522        completions: Rc<RefCell<Box<[Completion]>>>,
15523        cx: &mut Context<Editor>,
15524    ) -> Task<Result<bool>> {
15525        self.update(cx, |project, cx| {
15526            project.lsp_store().update(cx, |lsp_store, cx| {
15527                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15528            })
15529        })
15530    }
15531
15532    fn apply_additional_edits_for_completion(
15533        &self,
15534        buffer: Entity<Buffer>,
15535        completions: Rc<RefCell<Box<[Completion]>>>,
15536        completion_index: usize,
15537        push_to_history: bool,
15538        cx: &mut Context<Editor>,
15539    ) -> Task<Result<Option<language::Transaction>>> {
15540        self.update(cx, |project, cx| {
15541            project.lsp_store().update(cx, |lsp_store, cx| {
15542                lsp_store.apply_additional_edits_for_completion(
15543                    buffer,
15544                    completions,
15545                    completion_index,
15546                    push_to_history,
15547                    cx,
15548                )
15549            })
15550        })
15551    }
15552
15553    fn is_completion_trigger(
15554        &self,
15555        buffer: &Entity<Buffer>,
15556        position: language::Anchor,
15557        text: &str,
15558        trigger_in_words: bool,
15559        cx: &mut Context<Editor>,
15560    ) -> bool {
15561        let mut chars = text.chars();
15562        let char = if let Some(char) = chars.next() {
15563            char
15564        } else {
15565            return false;
15566        };
15567        if chars.next().is_some() {
15568            return false;
15569        }
15570
15571        let buffer = buffer.read(cx);
15572        let snapshot = buffer.snapshot();
15573        if !snapshot.settings_at(position, cx).show_completions_on_input {
15574            return false;
15575        }
15576        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15577        if trigger_in_words && classifier.is_word(char) {
15578            return true;
15579        }
15580
15581        buffer.completion_triggers().contains(text)
15582    }
15583}
15584
15585impl SemanticsProvider for Entity<Project> {
15586    fn hover(
15587        &self,
15588        buffer: &Entity<Buffer>,
15589        position: text::Anchor,
15590        cx: &mut App,
15591    ) -> Option<Task<Vec<project::Hover>>> {
15592        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15593    }
15594
15595    fn document_highlights(
15596        &self,
15597        buffer: &Entity<Buffer>,
15598        position: text::Anchor,
15599        cx: &mut App,
15600    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15601        Some(self.update(cx, |project, cx| {
15602            project.document_highlights(buffer, position, cx)
15603        }))
15604    }
15605
15606    fn definitions(
15607        &self,
15608        buffer: &Entity<Buffer>,
15609        position: text::Anchor,
15610        kind: GotoDefinitionKind,
15611        cx: &mut App,
15612    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15613        Some(self.update(cx, |project, cx| match kind {
15614            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15615            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15616            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15617            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15618        }))
15619    }
15620
15621    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15622        // TODO: make this work for remote projects
15623        self.read(cx)
15624            .language_servers_for_local_buffer(buffer.read(cx), cx)
15625            .any(
15626                |(_, server)| match server.capabilities().inlay_hint_provider {
15627                    Some(lsp::OneOf::Left(enabled)) => enabled,
15628                    Some(lsp::OneOf::Right(_)) => true,
15629                    None => false,
15630                },
15631            )
15632    }
15633
15634    fn inlay_hints(
15635        &self,
15636        buffer_handle: Entity<Buffer>,
15637        range: Range<text::Anchor>,
15638        cx: &mut App,
15639    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15640        Some(self.update(cx, |project, cx| {
15641            project.inlay_hints(buffer_handle, range, cx)
15642        }))
15643    }
15644
15645    fn resolve_inlay_hint(
15646        &self,
15647        hint: InlayHint,
15648        buffer_handle: Entity<Buffer>,
15649        server_id: LanguageServerId,
15650        cx: &mut App,
15651    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15652        Some(self.update(cx, |project, cx| {
15653            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15654        }))
15655    }
15656
15657    fn range_for_rename(
15658        &self,
15659        buffer: &Entity<Buffer>,
15660        position: text::Anchor,
15661        cx: &mut App,
15662    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15663        Some(self.update(cx, |project, cx| {
15664            let buffer = buffer.clone();
15665            let task = project.prepare_rename(buffer.clone(), position, cx);
15666            cx.spawn(|_, mut cx| async move {
15667                Ok(match task.await? {
15668                    PrepareRenameResponse::Success(range) => Some(range),
15669                    PrepareRenameResponse::InvalidPosition => None,
15670                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15671                        // Fallback on using TreeSitter info to determine identifier range
15672                        buffer.update(&mut cx, |buffer, _| {
15673                            let snapshot = buffer.snapshot();
15674                            let (range, kind) = snapshot.surrounding_word(position);
15675                            if kind != Some(CharKind::Word) {
15676                                return None;
15677                            }
15678                            Some(
15679                                snapshot.anchor_before(range.start)
15680                                    ..snapshot.anchor_after(range.end),
15681                            )
15682                        })?
15683                    }
15684                })
15685            })
15686        }))
15687    }
15688
15689    fn perform_rename(
15690        &self,
15691        buffer: &Entity<Buffer>,
15692        position: text::Anchor,
15693        new_name: String,
15694        cx: &mut App,
15695    ) -> Option<Task<Result<ProjectTransaction>>> {
15696        Some(self.update(cx, |project, cx| {
15697            project.perform_rename(buffer.clone(), position, new_name, cx)
15698        }))
15699    }
15700}
15701
15702fn inlay_hint_settings(
15703    location: Anchor,
15704    snapshot: &MultiBufferSnapshot,
15705    cx: &mut Context<Editor>,
15706) -> InlayHintSettings {
15707    let file = snapshot.file_at(location);
15708    let language = snapshot.language_at(location).map(|l| l.name());
15709    language_settings(language, file, cx).inlay_hints
15710}
15711
15712fn consume_contiguous_rows(
15713    contiguous_row_selections: &mut Vec<Selection<Point>>,
15714    selection: &Selection<Point>,
15715    display_map: &DisplaySnapshot,
15716    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15717) -> (MultiBufferRow, MultiBufferRow) {
15718    contiguous_row_selections.push(selection.clone());
15719    let start_row = MultiBufferRow(selection.start.row);
15720    let mut end_row = ending_row(selection, display_map);
15721
15722    while let Some(next_selection) = selections.peek() {
15723        if next_selection.start.row <= end_row.0 {
15724            end_row = ending_row(next_selection, display_map);
15725            contiguous_row_selections.push(selections.next().unwrap().clone());
15726        } else {
15727            break;
15728        }
15729    }
15730    (start_row, end_row)
15731}
15732
15733fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15734    if next_selection.end.column > 0 || next_selection.is_empty() {
15735        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15736    } else {
15737        MultiBufferRow(next_selection.end.row)
15738    }
15739}
15740
15741impl EditorSnapshot {
15742    pub fn remote_selections_in_range<'a>(
15743        &'a self,
15744        range: &'a Range<Anchor>,
15745        collaboration_hub: &dyn CollaborationHub,
15746        cx: &'a App,
15747    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15748        let participant_names = collaboration_hub.user_names(cx);
15749        let participant_indices = collaboration_hub.user_participant_indices(cx);
15750        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15751        let collaborators_by_replica_id = collaborators_by_peer_id
15752            .iter()
15753            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15754            .collect::<HashMap<_, _>>();
15755        self.buffer_snapshot
15756            .selections_in_range(range, false)
15757            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15758                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15759                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15760                let user_name = participant_names.get(&collaborator.user_id).cloned();
15761                Some(RemoteSelection {
15762                    replica_id,
15763                    selection,
15764                    cursor_shape,
15765                    line_mode,
15766                    participant_index,
15767                    peer_id: collaborator.peer_id,
15768                    user_name,
15769                })
15770            })
15771    }
15772
15773    pub fn hunks_for_ranges(
15774        &self,
15775        ranges: impl Iterator<Item = Range<Point>>,
15776    ) -> Vec<MultiBufferDiffHunk> {
15777        let mut hunks = Vec::new();
15778        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15779            HashMap::default();
15780        for query_range in ranges {
15781            let query_rows =
15782                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15783            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15784                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15785            ) {
15786                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15787                // when the caret is just above or just below the deleted hunk.
15788                let allow_adjacent = hunk.status().is_removed();
15789                let related_to_selection = if allow_adjacent {
15790                    hunk.row_range.overlaps(&query_rows)
15791                        || hunk.row_range.start == query_rows.end
15792                        || hunk.row_range.end == query_rows.start
15793                } else {
15794                    hunk.row_range.overlaps(&query_rows)
15795                };
15796                if related_to_selection {
15797                    if !processed_buffer_rows
15798                        .entry(hunk.buffer_id)
15799                        .or_default()
15800                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15801                    {
15802                        continue;
15803                    }
15804                    hunks.push(hunk);
15805                }
15806            }
15807        }
15808
15809        hunks
15810    }
15811
15812    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15813        self.display_snapshot.buffer_snapshot.language_at(position)
15814    }
15815
15816    pub fn is_focused(&self) -> bool {
15817        self.is_focused
15818    }
15819
15820    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15821        self.placeholder_text.as_ref()
15822    }
15823
15824    pub fn scroll_position(&self) -> gpui::Point<f32> {
15825        self.scroll_anchor.scroll_position(&self.display_snapshot)
15826    }
15827
15828    fn gutter_dimensions(
15829        &self,
15830        font_id: FontId,
15831        font_size: Pixels,
15832        max_line_number_width: Pixels,
15833        cx: &App,
15834    ) -> Option<GutterDimensions> {
15835        if !self.show_gutter {
15836            return None;
15837        }
15838
15839        let descent = cx.text_system().descent(font_id, font_size);
15840        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15841        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15842
15843        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15844            matches!(
15845                ProjectSettings::get_global(cx).git.git_gutter,
15846                Some(GitGutterSetting::TrackedFiles)
15847            )
15848        });
15849        let gutter_settings = EditorSettings::get_global(cx).gutter;
15850        let show_line_numbers = self
15851            .show_line_numbers
15852            .unwrap_or(gutter_settings.line_numbers);
15853        let line_gutter_width = if show_line_numbers {
15854            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15855            let min_width_for_number_on_gutter = em_advance * 4.0;
15856            max_line_number_width.max(min_width_for_number_on_gutter)
15857        } else {
15858            0.0.into()
15859        };
15860
15861        let show_code_actions = self
15862            .show_code_actions
15863            .unwrap_or(gutter_settings.code_actions);
15864
15865        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15866
15867        let git_blame_entries_width =
15868            self.git_blame_gutter_max_author_length
15869                .map(|max_author_length| {
15870                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15871
15872                    /// The number of characters to dedicate to gaps and margins.
15873                    const SPACING_WIDTH: usize = 4;
15874
15875                    let max_char_count = max_author_length
15876                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15877                        + ::git::SHORT_SHA_LENGTH
15878                        + MAX_RELATIVE_TIMESTAMP.len()
15879                        + SPACING_WIDTH;
15880
15881                    em_advance * max_char_count
15882                });
15883
15884        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15885        left_padding += if show_code_actions || show_runnables {
15886            em_width * 3.0
15887        } else if show_git_gutter && show_line_numbers {
15888            em_width * 2.0
15889        } else if show_git_gutter || show_line_numbers {
15890            em_width
15891        } else {
15892            px(0.)
15893        };
15894
15895        let right_padding = if gutter_settings.folds && show_line_numbers {
15896            em_width * 4.0
15897        } else if gutter_settings.folds {
15898            em_width * 3.0
15899        } else if show_line_numbers {
15900            em_width
15901        } else {
15902            px(0.)
15903        };
15904
15905        Some(GutterDimensions {
15906            left_padding,
15907            right_padding,
15908            width: line_gutter_width + left_padding + right_padding,
15909            margin: -descent,
15910            git_blame_entries_width,
15911        })
15912    }
15913
15914    pub fn render_crease_toggle(
15915        &self,
15916        buffer_row: MultiBufferRow,
15917        row_contains_cursor: bool,
15918        editor: Entity<Editor>,
15919        window: &mut Window,
15920        cx: &mut App,
15921    ) -> Option<AnyElement> {
15922        let folded = self.is_line_folded(buffer_row);
15923        let mut is_foldable = false;
15924
15925        if let Some(crease) = self
15926            .crease_snapshot
15927            .query_row(buffer_row, &self.buffer_snapshot)
15928        {
15929            is_foldable = true;
15930            match crease {
15931                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15932                    if let Some(render_toggle) = render_toggle {
15933                        let toggle_callback =
15934                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15935                                if folded {
15936                                    editor.update(cx, |editor, cx| {
15937                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15938                                    });
15939                                } else {
15940                                    editor.update(cx, |editor, cx| {
15941                                        editor.unfold_at(
15942                                            &crate::UnfoldAt { buffer_row },
15943                                            window,
15944                                            cx,
15945                                        )
15946                                    });
15947                                }
15948                            });
15949                        return Some((render_toggle)(
15950                            buffer_row,
15951                            folded,
15952                            toggle_callback,
15953                            window,
15954                            cx,
15955                        ));
15956                    }
15957                }
15958            }
15959        }
15960
15961        is_foldable |= self.starts_indent(buffer_row);
15962
15963        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15964            Some(
15965                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15966                    .toggle_state(folded)
15967                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15968                        if folded {
15969                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15970                        } else {
15971                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15972                        }
15973                    }))
15974                    .into_any_element(),
15975            )
15976        } else {
15977            None
15978        }
15979    }
15980
15981    pub fn render_crease_trailer(
15982        &self,
15983        buffer_row: MultiBufferRow,
15984        window: &mut Window,
15985        cx: &mut App,
15986    ) -> Option<AnyElement> {
15987        let folded = self.is_line_folded(buffer_row);
15988        if let Crease::Inline { render_trailer, .. } = self
15989            .crease_snapshot
15990            .query_row(buffer_row, &self.buffer_snapshot)?
15991        {
15992            let render_trailer = render_trailer.as_ref()?;
15993            Some(render_trailer(buffer_row, folded, window, cx))
15994        } else {
15995            None
15996        }
15997    }
15998}
15999
16000impl Deref for EditorSnapshot {
16001    type Target = DisplaySnapshot;
16002
16003    fn deref(&self) -> &Self::Target {
16004        &self.display_snapshot
16005    }
16006}
16007
16008#[derive(Clone, Debug, PartialEq, Eq)]
16009pub enum EditorEvent {
16010    InputIgnored {
16011        text: Arc<str>,
16012    },
16013    InputHandled {
16014        utf16_range_to_replace: Option<Range<isize>>,
16015        text: Arc<str>,
16016    },
16017    ExcerptsAdded {
16018        buffer: Entity<Buffer>,
16019        predecessor: ExcerptId,
16020        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16021    },
16022    ExcerptsRemoved {
16023        ids: Vec<ExcerptId>,
16024    },
16025    BufferFoldToggled {
16026        ids: Vec<ExcerptId>,
16027        folded: bool,
16028    },
16029    ExcerptsEdited {
16030        ids: Vec<ExcerptId>,
16031    },
16032    ExcerptsExpanded {
16033        ids: Vec<ExcerptId>,
16034    },
16035    BufferEdited,
16036    Edited {
16037        transaction_id: clock::Lamport,
16038    },
16039    Reparsed(BufferId),
16040    Focused,
16041    FocusedIn,
16042    Blurred,
16043    DirtyChanged,
16044    Saved,
16045    TitleChanged,
16046    DiffBaseChanged,
16047    SelectionsChanged {
16048        local: bool,
16049    },
16050    ScrollPositionChanged {
16051        local: bool,
16052        autoscroll: bool,
16053    },
16054    Closed,
16055    TransactionUndone {
16056        transaction_id: clock::Lamport,
16057    },
16058    TransactionBegun {
16059        transaction_id: clock::Lamport,
16060    },
16061    Reloaded,
16062    CursorShapeChanged,
16063}
16064
16065impl EventEmitter<EditorEvent> for Editor {}
16066
16067impl Focusable for Editor {
16068    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16069        self.focus_handle.clone()
16070    }
16071}
16072
16073impl Render for Editor {
16074    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16075        let settings = ThemeSettings::get_global(cx);
16076
16077        let mut text_style = match self.mode {
16078            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16079                color: cx.theme().colors().editor_foreground,
16080                font_family: settings.ui_font.family.clone(),
16081                font_features: settings.ui_font.features.clone(),
16082                font_fallbacks: settings.ui_font.fallbacks.clone(),
16083                font_size: rems(0.875).into(),
16084                font_weight: settings.ui_font.weight,
16085                line_height: relative(settings.buffer_line_height.value()),
16086                ..Default::default()
16087            },
16088            EditorMode::Full => TextStyle {
16089                color: cx.theme().colors().editor_foreground,
16090                font_family: settings.buffer_font.family.clone(),
16091                font_features: settings.buffer_font.features.clone(),
16092                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16093                font_size: settings.buffer_font_size(cx).into(),
16094                font_weight: settings.buffer_font.weight,
16095                line_height: relative(settings.buffer_line_height.value()),
16096                ..Default::default()
16097            },
16098        };
16099        if let Some(text_style_refinement) = &self.text_style_refinement {
16100            text_style.refine(text_style_refinement)
16101        }
16102
16103        let background = match self.mode {
16104            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16105            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16106            EditorMode::Full => cx.theme().colors().editor_background,
16107        };
16108
16109        EditorElement::new(
16110            &cx.entity(),
16111            EditorStyle {
16112                background,
16113                local_player: cx.theme().players().local(),
16114                text: text_style,
16115                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16116                syntax: cx.theme().syntax().clone(),
16117                status: cx.theme().status().clone(),
16118                inlay_hints_style: make_inlay_hints_style(cx),
16119                inline_completion_styles: make_suggestion_styles(cx),
16120                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16121            },
16122        )
16123    }
16124}
16125
16126impl EntityInputHandler for Editor {
16127    fn text_for_range(
16128        &mut self,
16129        range_utf16: Range<usize>,
16130        adjusted_range: &mut Option<Range<usize>>,
16131        _: &mut Window,
16132        cx: &mut Context<Self>,
16133    ) -> Option<String> {
16134        let snapshot = self.buffer.read(cx).read(cx);
16135        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16136        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16137        if (start.0..end.0) != range_utf16 {
16138            adjusted_range.replace(start.0..end.0);
16139        }
16140        Some(snapshot.text_for_range(start..end).collect())
16141    }
16142
16143    fn selected_text_range(
16144        &mut self,
16145        ignore_disabled_input: bool,
16146        _: &mut Window,
16147        cx: &mut Context<Self>,
16148    ) -> Option<UTF16Selection> {
16149        // Prevent the IME menu from appearing when holding down an alphabetic key
16150        // while input is disabled.
16151        if !ignore_disabled_input && !self.input_enabled {
16152            return None;
16153        }
16154
16155        let selection = self.selections.newest::<OffsetUtf16>(cx);
16156        let range = selection.range();
16157
16158        Some(UTF16Selection {
16159            range: range.start.0..range.end.0,
16160            reversed: selection.reversed,
16161        })
16162    }
16163
16164    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16165        let snapshot = self.buffer.read(cx).read(cx);
16166        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16167        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16168    }
16169
16170    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16171        self.clear_highlights::<InputComposition>(cx);
16172        self.ime_transaction.take();
16173    }
16174
16175    fn replace_text_in_range(
16176        &mut self,
16177        range_utf16: Option<Range<usize>>,
16178        text: &str,
16179        window: &mut Window,
16180        cx: &mut Context<Self>,
16181    ) {
16182        if !self.input_enabled {
16183            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16184            return;
16185        }
16186
16187        self.transact(window, cx, |this, window, cx| {
16188            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16189                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16190                Some(this.selection_replacement_ranges(range_utf16, cx))
16191            } else {
16192                this.marked_text_ranges(cx)
16193            };
16194
16195            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16196                let newest_selection_id = this.selections.newest_anchor().id;
16197                this.selections
16198                    .all::<OffsetUtf16>(cx)
16199                    .iter()
16200                    .zip(ranges_to_replace.iter())
16201                    .find_map(|(selection, range)| {
16202                        if selection.id == newest_selection_id {
16203                            Some(
16204                                (range.start.0 as isize - selection.head().0 as isize)
16205                                    ..(range.end.0 as isize - selection.head().0 as isize),
16206                            )
16207                        } else {
16208                            None
16209                        }
16210                    })
16211            });
16212
16213            cx.emit(EditorEvent::InputHandled {
16214                utf16_range_to_replace: range_to_replace,
16215                text: text.into(),
16216            });
16217
16218            if let Some(new_selected_ranges) = new_selected_ranges {
16219                this.change_selections(None, window, cx, |selections| {
16220                    selections.select_ranges(new_selected_ranges)
16221                });
16222                this.backspace(&Default::default(), window, cx);
16223            }
16224
16225            this.handle_input(text, window, cx);
16226        });
16227
16228        if let Some(transaction) = self.ime_transaction {
16229            self.buffer.update(cx, |buffer, cx| {
16230                buffer.group_until_transaction(transaction, cx);
16231            });
16232        }
16233
16234        self.unmark_text(window, cx);
16235    }
16236
16237    fn replace_and_mark_text_in_range(
16238        &mut self,
16239        range_utf16: Option<Range<usize>>,
16240        text: &str,
16241        new_selected_range_utf16: Option<Range<usize>>,
16242        window: &mut Window,
16243        cx: &mut Context<Self>,
16244    ) {
16245        if !self.input_enabled {
16246            return;
16247        }
16248
16249        let transaction = self.transact(window, cx, |this, window, cx| {
16250            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16251                let snapshot = this.buffer.read(cx).read(cx);
16252                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16253                    for marked_range in &mut marked_ranges {
16254                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16255                        marked_range.start.0 += relative_range_utf16.start;
16256                        marked_range.start =
16257                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16258                        marked_range.end =
16259                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16260                    }
16261                }
16262                Some(marked_ranges)
16263            } else if let Some(range_utf16) = range_utf16 {
16264                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16265                Some(this.selection_replacement_ranges(range_utf16, cx))
16266            } else {
16267                None
16268            };
16269
16270            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16271                let newest_selection_id = this.selections.newest_anchor().id;
16272                this.selections
16273                    .all::<OffsetUtf16>(cx)
16274                    .iter()
16275                    .zip(ranges_to_replace.iter())
16276                    .find_map(|(selection, range)| {
16277                        if selection.id == newest_selection_id {
16278                            Some(
16279                                (range.start.0 as isize - selection.head().0 as isize)
16280                                    ..(range.end.0 as isize - selection.head().0 as isize),
16281                            )
16282                        } else {
16283                            None
16284                        }
16285                    })
16286            });
16287
16288            cx.emit(EditorEvent::InputHandled {
16289                utf16_range_to_replace: range_to_replace,
16290                text: text.into(),
16291            });
16292
16293            if let Some(ranges) = ranges_to_replace {
16294                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16295            }
16296
16297            let marked_ranges = {
16298                let snapshot = this.buffer.read(cx).read(cx);
16299                this.selections
16300                    .disjoint_anchors()
16301                    .iter()
16302                    .map(|selection| {
16303                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16304                    })
16305                    .collect::<Vec<_>>()
16306            };
16307
16308            if text.is_empty() {
16309                this.unmark_text(window, cx);
16310            } else {
16311                this.highlight_text::<InputComposition>(
16312                    marked_ranges.clone(),
16313                    HighlightStyle {
16314                        underline: Some(UnderlineStyle {
16315                            thickness: px(1.),
16316                            color: None,
16317                            wavy: false,
16318                        }),
16319                        ..Default::default()
16320                    },
16321                    cx,
16322                );
16323            }
16324
16325            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16326            let use_autoclose = this.use_autoclose;
16327            let use_auto_surround = this.use_auto_surround;
16328            this.set_use_autoclose(false);
16329            this.set_use_auto_surround(false);
16330            this.handle_input(text, window, cx);
16331            this.set_use_autoclose(use_autoclose);
16332            this.set_use_auto_surround(use_auto_surround);
16333
16334            if let Some(new_selected_range) = new_selected_range_utf16 {
16335                let snapshot = this.buffer.read(cx).read(cx);
16336                let new_selected_ranges = marked_ranges
16337                    .into_iter()
16338                    .map(|marked_range| {
16339                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16340                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16341                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16342                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16343                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16344                    })
16345                    .collect::<Vec<_>>();
16346
16347                drop(snapshot);
16348                this.change_selections(None, window, cx, |selections| {
16349                    selections.select_ranges(new_selected_ranges)
16350                });
16351            }
16352        });
16353
16354        self.ime_transaction = self.ime_transaction.or(transaction);
16355        if let Some(transaction) = self.ime_transaction {
16356            self.buffer.update(cx, |buffer, cx| {
16357                buffer.group_until_transaction(transaction, cx);
16358            });
16359        }
16360
16361        if self.text_highlights::<InputComposition>(cx).is_none() {
16362            self.ime_transaction.take();
16363        }
16364    }
16365
16366    fn bounds_for_range(
16367        &mut self,
16368        range_utf16: Range<usize>,
16369        element_bounds: gpui::Bounds<Pixels>,
16370        window: &mut Window,
16371        cx: &mut Context<Self>,
16372    ) -> Option<gpui::Bounds<Pixels>> {
16373        let text_layout_details = self.text_layout_details(window);
16374        let gpui::Size {
16375            width: em_width,
16376            height: line_height,
16377        } = self.character_size(window);
16378
16379        let snapshot = self.snapshot(window, cx);
16380        let scroll_position = snapshot.scroll_position();
16381        let scroll_left = scroll_position.x * em_width;
16382
16383        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16384        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16385            + self.gutter_dimensions.width
16386            + self.gutter_dimensions.margin;
16387        let y = line_height * (start.row().as_f32() - scroll_position.y);
16388
16389        Some(Bounds {
16390            origin: element_bounds.origin + point(x, y),
16391            size: size(em_width, line_height),
16392        })
16393    }
16394
16395    fn character_index_for_point(
16396        &mut self,
16397        point: gpui::Point<Pixels>,
16398        _window: &mut Window,
16399        _cx: &mut Context<Self>,
16400    ) -> Option<usize> {
16401        let position_map = self.last_position_map.as_ref()?;
16402        if !position_map.text_hitbox.contains(&point) {
16403            return None;
16404        }
16405        let display_point = position_map.point_for_position(point).previous_valid;
16406        let anchor = position_map
16407            .snapshot
16408            .display_point_to_anchor(display_point, Bias::Left);
16409        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16410        Some(utf16_offset.0)
16411    }
16412}
16413
16414trait SelectionExt {
16415    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16416    fn spanned_rows(
16417        &self,
16418        include_end_if_at_line_start: bool,
16419        map: &DisplaySnapshot,
16420    ) -> Range<MultiBufferRow>;
16421}
16422
16423impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16424    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16425        let start = self
16426            .start
16427            .to_point(&map.buffer_snapshot)
16428            .to_display_point(map);
16429        let end = self
16430            .end
16431            .to_point(&map.buffer_snapshot)
16432            .to_display_point(map);
16433        if self.reversed {
16434            end..start
16435        } else {
16436            start..end
16437        }
16438    }
16439
16440    fn spanned_rows(
16441        &self,
16442        include_end_if_at_line_start: bool,
16443        map: &DisplaySnapshot,
16444    ) -> Range<MultiBufferRow> {
16445        let start = self.start.to_point(&map.buffer_snapshot);
16446        let mut end = self.end.to_point(&map.buffer_snapshot);
16447        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16448            end.row -= 1;
16449        }
16450
16451        let buffer_start = map.prev_line_boundary(start).0;
16452        let buffer_end = map.next_line_boundary(end).0;
16453        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16454    }
16455}
16456
16457impl<T: InvalidationRegion> InvalidationStack<T> {
16458    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16459    where
16460        S: Clone + ToOffset,
16461    {
16462        while let Some(region) = self.last() {
16463            let all_selections_inside_invalidation_ranges =
16464                if selections.len() == region.ranges().len() {
16465                    selections
16466                        .iter()
16467                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16468                        .all(|(selection, invalidation_range)| {
16469                            let head = selection.head().to_offset(buffer);
16470                            invalidation_range.start <= head && invalidation_range.end >= head
16471                        })
16472                } else {
16473                    false
16474                };
16475
16476            if all_selections_inside_invalidation_ranges {
16477                break;
16478            } else {
16479                self.pop();
16480            }
16481        }
16482    }
16483}
16484
16485impl<T> Default for InvalidationStack<T> {
16486    fn default() -> Self {
16487        Self(Default::default())
16488    }
16489}
16490
16491impl<T> Deref for InvalidationStack<T> {
16492    type Target = Vec<T>;
16493
16494    fn deref(&self) -> &Self::Target {
16495        &self.0
16496    }
16497}
16498
16499impl<T> DerefMut for InvalidationStack<T> {
16500    fn deref_mut(&mut self) -> &mut Self::Target {
16501        &mut self.0
16502    }
16503}
16504
16505impl InvalidationRegion for SnippetState {
16506    fn ranges(&self) -> &[Range<Anchor>] {
16507        &self.ranges[self.active_index]
16508    }
16509}
16510
16511pub fn diagnostic_block_renderer(
16512    diagnostic: Diagnostic,
16513    max_message_rows: Option<u8>,
16514    allow_closing: bool,
16515    _is_valid: bool,
16516) -> RenderBlock {
16517    let (text_without_backticks, code_ranges) =
16518        highlight_diagnostic_message(&diagnostic, max_message_rows);
16519
16520    Arc::new(move |cx: &mut BlockContext| {
16521        let group_id: SharedString = cx.block_id.to_string().into();
16522
16523        let mut text_style = cx.window.text_style().clone();
16524        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16525        let theme_settings = ThemeSettings::get_global(cx);
16526        text_style.font_family = theme_settings.buffer_font.family.clone();
16527        text_style.font_style = theme_settings.buffer_font.style;
16528        text_style.font_features = theme_settings.buffer_font.features.clone();
16529        text_style.font_weight = theme_settings.buffer_font.weight;
16530
16531        let multi_line_diagnostic = diagnostic.message.contains('\n');
16532
16533        let buttons = |diagnostic: &Diagnostic| {
16534            if multi_line_diagnostic {
16535                v_flex()
16536            } else {
16537                h_flex()
16538            }
16539            .when(allow_closing, |div| {
16540                div.children(diagnostic.is_primary.then(|| {
16541                    IconButton::new("close-block", IconName::XCircle)
16542                        .icon_color(Color::Muted)
16543                        .size(ButtonSize::Compact)
16544                        .style(ButtonStyle::Transparent)
16545                        .visible_on_hover(group_id.clone())
16546                        .on_click(move |_click, window, cx| {
16547                            window.dispatch_action(Box::new(Cancel), cx)
16548                        })
16549                        .tooltip(|window, cx| {
16550                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16551                        })
16552                }))
16553            })
16554            .child(
16555                IconButton::new("copy-block", IconName::Copy)
16556                    .icon_color(Color::Muted)
16557                    .size(ButtonSize::Compact)
16558                    .style(ButtonStyle::Transparent)
16559                    .visible_on_hover(group_id.clone())
16560                    .on_click({
16561                        let message = diagnostic.message.clone();
16562                        move |_click, _, cx| {
16563                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16564                        }
16565                    })
16566                    .tooltip(Tooltip::text("Copy diagnostic message")),
16567            )
16568        };
16569
16570        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16571            AvailableSpace::min_size(),
16572            cx.window,
16573            cx.app,
16574        );
16575
16576        h_flex()
16577            .id(cx.block_id)
16578            .group(group_id.clone())
16579            .relative()
16580            .size_full()
16581            .block_mouse_down()
16582            .pl(cx.gutter_dimensions.width)
16583            .w(cx.max_width - cx.gutter_dimensions.full_width())
16584            .child(
16585                div()
16586                    .flex()
16587                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16588                    .flex_shrink(),
16589            )
16590            .child(buttons(&diagnostic))
16591            .child(div().flex().flex_shrink_0().child(
16592                StyledText::new(text_without_backticks.clone()).with_highlights(
16593                    &text_style,
16594                    code_ranges.iter().map(|range| {
16595                        (
16596                            range.clone(),
16597                            HighlightStyle {
16598                                font_weight: Some(FontWeight::BOLD),
16599                                ..Default::default()
16600                            },
16601                        )
16602                    }),
16603                ),
16604            ))
16605            .into_any_element()
16606    })
16607}
16608
16609fn inline_completion_edit_text(
16610    current_snapshot: &BufferSnapshot,
16611    edits: &[(Range<Anchor>, String)],
16612    edit_preview: &EditPreview,
16613    include_deletions: bool,
16614    cx: &App,
16615) -> HighlightedText {
16616    let edits = edits
16617        .iter()
16618        .map(|(anchor, text)| {
16619            (
16620                anchor.start.text_anchor..anchor.end.text_anchor,
16621                text.clone(),
16622            )
16623        })
16624        .collect::<Vec<_>>();
16625
16626    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16627}
16628
16629pub fn highlight_diagnostic_message(
16630    diagnostic: &Diagnostic,
16631    mut max_message_rows: Option<u8>,
16632) -> (SharedString, Vec<Range<usize>>) {
16633    let mut text_without_backticks = String::new();
16634    let mut code_ranges = Vec::new();
16635
16636    if let Some(source) = &diagnostic.source {
16637        text_without_backticks.push_str(source);
16638        code_ranges.push(0..source.len());
16639        text_without_backticks.push_str(": ");
16640    }
16641
16642    let mut prev_offset = 0;
16643    let mut in_code_block = false;
16644    let has_row_limit = max_message_rows.is_some();
16645    let mut newline_indices = diagnostic
16646        .message
16647        .match_indices('\n')
16648        .filter(|_| has_row_limit)
16649        .map(|(ix, _)| ix)
16650        .fuse()
16651        .peekable();
16652
16653    for (quote_ix, _) in diagnostic
16654        .message
16655        .match_indices('`')
16656        .chain([(diagnostic.message.len(), "")])
16657    {
16658        let mut first_newline_ix = None;
16659        let mut last_newline_ix = None;
16660        while let Some(newline_ix) = newline_indices.peek() {
16661            if *newline_ix < quote_ix {
16662                if first_newline_ix.is_none() {
16663                    first_newline_ix = Some(*newline_ix);
16664                }
16665                last_newline_ix = Some(*newline_ix);
16666
16667                if let Some(rows_left) = &mut max_message_rows {
16668                    if *rows_left == 0 {
16669                        break;
16670                    } else {
16671                        *rows_left -= 1;
16672                    }
16673                }
16674                let _ = newline_indices.next();
16675            } else {
16676                break;
16677            }
16678        }
16679        let prev_len = text_without_backticks.len();
16680        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16681        text_without_backticks.push_str(new_text);
16682        if in_code_block {
16683            code_ranges.push(prev_len..text_without_backticks.len());
16684        }
16685        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16686        in_code_block = !in_code_block;
16687        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16688            text_without_backticks.push_str("...");
16689            break;
16690        }
16691    }
16692
16693    (text_without_backticks.into(), code_ranges)
16694}
16695
16696fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16697    match severity {
16698        DiagnosticSeverity::ERROR => colors.error,
16699        DiagnosticSeverity::WARNING => colors.warning,
16700        DiagnosticSeverity::INFORMATION => colors.info,
16701        DiagnosticSeverity::HINT => colors.info,
16702        _ => colors.ignored,
16703    }
16704}
16705
16706pub fn styled_runs_for_code_label<'a>(
16707    label: &'a CodeLabel,
16708    syntax_theme: &'a theme::SyntaxTheme,
16709) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16710    let fade_out = HighlightStyle {
16711        fade_out: Some(0.35),
16712        ..Default::default()
16713    };
16714
16715    let mut prev_end = label.filter_range.end;
16716    label
16717        .runs
16718        .iter()
16719        .enumerate()
16720        .flat_map(move |(ix, (range, highlight_id))| {
16721            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16722                style
16723            } else {
16724                return Default::default();
16725            };
16726            let mut muted_style = style;
16727            muted_style.highlight(fade_out);
16728
16729            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16730            if range.start >= label.filter_range.end {
16731                if range.start > prev_end {
16732                    runs.push((prev_end..range.start, fade_out));
16733                }
16734                runs.push((range.clone(), muted_style));
16735            } else if range.end <= label.filter_range.end {
16736                runs.push((range.clone(), style));
16737            } else {
16738                runs.push((range.start..label.filter_range.end, style));
16739                runs.push((label.filter_range.end..range.end, muted_style));
16740            }
16741            prev_end = cmp::max(prev_end, range.end);
16742
16743            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16744                runs.push((prev_end..label.text.len(), fade_out));
16745            }
16746
16747            runs
16748        })
16749}
16750
16751pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16752    let mut prev_index = 0;
16753    let mut prev_codepoint: Option<char> = None;
16754    text.char_indices()
16755        .chain([(text.len(), '\0')])
16756        .filter_map(move |(index, codepoint)| {
16757            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16758            let is_boundary = index == text.len()
16759                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16760                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16761            if is_boundary {
16762                let chunk = &text[prev_index..index];
16763                prev_index = index;
16764                Some(chunk)
16765            } else {
16766                None
16767            }
16768        })
16769}
16770
16771pub trait RangeToAnchorExt: Sized {
16772    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16773
16774    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16775        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16776        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16777    }
16778}
16779
16780impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16781    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16782        let start_offset = self.start.to_offset(snapshot);
16783        let end_offset = self.end.to_offset(snapshot);
16784        if start_offset == end_offset {
16785            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16786        } else {
16787            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16788        }
16789    }
16790}
16791
16792pub trait RowExt {
16793    fn as_f32(&self) -> f32;
16794
16795    fn next_row(&self) -> Self;
16796
16797    fn previous_row(&self) -> Self;
16798
16799    fn minus(&self, other: Self) -> u32;
16800}
16801
16802impl RowExt for DisplayRow {
16803    fn as_f32(&self) -> f32 {
16804        self.0 as f32
16805    }
16806
16807    fn next_row(&self) -> Self {
16808        Self(self.0 + 1)
16809    }
16810
16811    fn previous_row(&self) -> Self {
16812        Self(self.0.saturating_sub(1))
16813    }
16814
16815    fn minus(&self, other: Self) -> u32 {
16816        self.0 - other.0
16817    }
16818}
16819
16820impl RowExt for MultiBufferRow {
16821    fn as_f32(&self) -> f32 {
16822        self.0 as f32
16823    }
16824
16825    fn next_row(&self) -> Self {
16826        Self(self.0 + 1)
16827    }
16828
16829    fn previous_row(&self) -> Self {
16830        Self(self.0.saturating_sub(1))
16831    }
16832
16833    fn minus(&self, other: Self) -> u32 {
16834        self.0 - other.0
16835    }
16836}
16837
16838trait RowRangeExt {
16839    type Row;
16840
16841    fn len(&self) -> usize;
16842
16843    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16844}
16845
16846impl RowRangeExt for Range<MultiBufferRow> {
16847    type Row = MultiBufferRow;
16848
16849    fn len(&self) -> usize {
16850        (self.end.0 - self.start.0) as usize
16851    }
16852
16853    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16854        (self.start.0..self.end.0).map(MultiBufferRow)
16855    }
16856}
16857
16858impl RowRangeExt for Range<DisplayRow> {
16859    type Row = DisplayRow;
16860
16861    fn len(&self) -> usize {
16862        (self.end.0 - self.start.0) as usize
16863    }
16864
16865    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16866        (self.start.0..self.end.0).map(DisplayRow)
16867    }
16868}
16869
16870/// If select range has more than one line, we
16871/// just point the cursor to range.start.
16872fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16873    if range.start.row == range.end.row {
16874        range
16875    } else {
16876        range.start..range.start
16877    }
16878}
16879pub struct KillRing(ClipboardItem);
16880impl Global for KillRing {}
16881
16882const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16883
16884fn all_edits_insertions_or_deletions(
16885    edits: &Vec<(Range<Anchor>, String)>,
16886    snapshot: &MultiBufferSnapshot,
16887) -> bool {
16888    let mut all_insertions = true;
16889    let mut all_deletions = true;
16890
16891    for (range, new_text) in edits.iter() {
16892        let range_is_empty = range.to_offset(&snapshot).is_empty();
16893        let text_is_empty = new_text.is_empty();
16894
16895        if range_is_empty != text_is_empty {
16896            if range_is_empty {
16897                all_deletions = false;
16898            } else {
16899                all_insertions = false;
16900            }
16901        } else {
16902            return false;
16903        }
16904
16905        if !all_insertions && !all_deletions {
16906            return false;
16907        }
16908    }
16909    all_insertions || all_deletions
16910}