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::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  194pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakEntity<Workspace>>,
  201    cx: &mut App,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(
  246        link_ranges,
  247        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace
  253                            .open_abs_path(path.clone(), false, window, cx)
  254                            .detach();
  255                    });
  256                }
  257            }
  258        },
  259    )
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub enum InlayId {
  264    InlineCompletion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::InlineCompletion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DocumentHighlightRead {}
  278enum DocumentHighlightWrite {}
  279enum InputComposition {}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut App) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut App) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new(
  309        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313            workspace.register_action(Editor::cancel_language_server_work);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    Editor::new_file(workspace, &Default::default(), window, cx)
  327                },
  328            )
  329            .detach();
  330        }
  331    });
  332    cx.on_action(move |_: &workspace::NewWindow, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    cx.activate(true);
  341                    Editor::new_file(workspace, &Default::default(), window, cx)
  342                },
  343            )
  344            .detach();
  345        }
  346    });
  347}
  348
  349pub struct SearchWithinRange;
  350
  351trait InvalidationRegion {
  352    fn ranges(&self) -> &[Range<Anchor>];
  353}
  354
  355#[derive(Clone, Debug, PartialEq)]
  356pub enum SelectPhase {
  357    Begin {
  358        position: DisplayPoint,
  359        add: bool,
  360        click_count: usize,
  361    },
  362    BeginColumnar {
  363        position: DisplayPoint,
  364        reset: bool,
  365        goal_column: u32,
  366    },
  367    Extend {
  368        position: DisplayPoint,
  369        click_count: usize,
  370    },
  371    Update {
  372        position: DisplayPoint,
  373        goal_column: u32,
  374        scroll_delta: gpui::Point<f32>,
  375    },
  376    End,
  377}
  378
  379#[derive(Clone, Debug)]
  380pub enum SelectMode {
  381    Character,
  382    Word(Range<Anchor>),
  383    Line(Range<Anchor>),
  384    All,
  385}
  386
  387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  388pub enum EditorMode {
  389    SingleLine { auto_width: bool },
  390    AutoHeight { max_lines: usize },
  391    Full,
  392}
  393
  394#[derive(Copy, Clone, Debug)]
  395pub enum SoftWrap {
  396    /// Prefer not to wrap at all.
  397    ///
  398    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  399    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  400    GitDiff,
  401    /// Prefer a single line generally, unless an overly long line is encountered.
  402    None,
  403    /// Soft wrap lines that exceed the editor width.
  404    EditorWidth,
  405    /// Soft wrap lines at the preferred line length.
  406    Column(u32),
  407    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  408    Bounded(u32),
  409}
  410
  411#[derive(Clone)]
  412pub struct EditorStyle {
  413    pub background: Hsla,
  414    pub local_player: PlayerColor,
  415    pub text: TextStyle,
  416    pub scrollbar_width: Pixels,
  417    pub syntax: Arc<SyntaxTheme>,
  418    pub status: StatusColors,
  419    pub inlay_hints_style: HighlightStyle,
  420    pub inline_completion_styles: InlineCompletionStyles,
  421    pub unnecessary_code_fade: f32,
  422}
  423
  424impl Default for EditorStyle {
  425    fn default() -> Self {
  426        Self {
  427            background: Hsla::default(),
  428            local_player: PlayerColor::default(),
  429            text: TextStyle::default(),
  430            scrollbar_width: Pixels::default(),
  431            syntax: Default::default(),
  432            // HACK: Status colors don't have a real default.
  433            // We should look into removing the status colors from the editor
  434            // style and retrieve them directly from the theme.
  435            status: StatusColors::dark(),
  436            inlay_hints_style: HighlightStyle::default(),
  437            inline_completion_styles: InlineCompletionStyles {
  438                insertion: HighlightStyle::default(),
  439                whitespace: HighlightStyle::default(),
  440            },
  441            unnecessary_code_fade: Default::default(),
  442        }
  443    }
  444}
  445
  446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  447    let show_background = language_settings::language_settings(None, None, cx)
  448        .inlay_hints
  449        .show_background;
  450
  451    HighlightStyle {
  452        color: Some(cx.theme().status().hint),
  453        background_color: show_background.then(|| cx.theme().status().hint_background),
  454        ..HighlightStyle::default()
  455    }
  456}
  457
  458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  459    InlineCompletionStyles {
  460        insertion: HighlightStyle {
  461            color: Some(cx.theme().status().predictive),
  462            ..HighlightStyle::default()
  463        },
  464        whitespace: HighlightStyle {
  465            background_color: Some(cx.theme().status().created_background),
  466            ..HighlightStyle::default()
  467        },
  468    }
  469}
  470
  471type CompletionId = usize;
  472
  473pub(crate) enum EditDisplayMode {
  474    TabAccept,
  475    DiffPopover,
  476    Inline,
  477}
  478
  479enum InlineCompletion {
  480    Edit {
  481        edits: Vec<(Range<Anchor>, String)>,
  482        edit_preview: Option<EditPreview>,
  483        display_mode: EditDisplayMode,
  484        snapshot: BufferSnapshot,
  485    },
  486    Move {
  487        target: Anchor,
  488        snapshot: BufferSnapshot,
  489    },
  490}
  491
  492struct InlineCompletionState {
  493    inlay_ids: Vec<InlayId>,
  494    completion: InlineCompletion,
  495    completion_id: Option<SharedString>,
  496    invalidation_range: Range<Anchor>,
  497}
  498
  499enum EditPredictionSettings {
  500    Disabled,
  501    Enabled {
  502        show_in_menu: bool,
  503        preview_requires_modifier: bool,
  504    },
  505}
  506
  507impl EditPredictionSettings {
  508    pub fn is_enabled(&self) -> bool {
  509        match self {
  510            EditPredictionSettings::Disabled => false,
  511            EditPredictionSettings::Enabled { .. } => true,
  512        }
  513    }
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523pub enum EditPredictionPreview {
  524    /// Modifier is not pressed
  525    Inactive,
  526    /// Modifier pressed
  527    Active {
  528        previous_scroll_position: Option<ScrollAnchor>,
  529    },
  530}
  531
  532#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  533struct EditorActionId(usize);
  534
  535impl EditorActionId {
  536    pub fn post_inc(&mut self) -> Self {
  537        let answer = self.0;
  538
  539        *self = Self(answer + 1);
  540
  541        Self(answer)
  542    }
  543}
  544
  545// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  546// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  547
  548type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  549type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  550
  551#[derive(Default)]
  552struct ScrollbarMarkerState {
  553    scrollbar_size: Size<Pixels>,
  554    dirty: bool,
  555    markers: Arc<[PaintQuad]>,
  556    pending_refresh: Option<Task<Result<()>>>,
  557}
  558
  559impl ScrollbarMarkerState {
  560    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  561        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  562    }
  563}
  564
  565#[derive(Clone, Debug)]
  566struct RunnableTasks {
  567    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  568    offset: MultiBufferOffset,
  569    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  570    column: u32,
  571    // Values of all named captures, including those starting with '_'
  572    extra_variables: HashMap<String, String>,
  573    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  574    context_range: Range<BufferOffset>,
  575}
  576
  577impl RunnableTasks {
  578    fn resolve<'a>(
  579        &'a self,
  580        cx: &'a task::TaskContext,
  581    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  582        self.templates.iter().filter_map(|(kind, template)| {
  583            template
  584                .resolve_task(&kind.to_id_base(), cx)
  585                .map(|task| (kind.clone(), task))
  586        })
  587    }
  588}
  589
  590#[derive(Clone)]
  591struct ResolvedTasks {
  592    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  593    position: Anchor,
  594}
  595#[derive(Copy, Clone, Debug)]
  596struct MultiBufferOffset(usize);
  597#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  598struct BufferOffset(usize);
  599
  600// Addons allow storing per-editor state in other crates (e.g. Vim)
  601pub trait Addon: 'static {
  602    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  603
  604    fn render_buffer_header_controls(
  605        &self,
  606        _: &ExcerptInfo,
  607        _: &Window,
  608        _: &App,
  609    ) -> Option<AnyElement> {
  610        None
  611    }
  612
  613    fn to_any(&self) -> &dyn std::any::Any;
  614}
  615
  616#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  617pub enum IsVimMode {
  618    Yes,
  619    No,
  620}
  621
  622/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  623///
  624/// See the [module level documentation](self) for more information.
  625pub struct Editor {
  626    focus_handle: FocusHandle,
  627    last_focused_descendant: Option<WeakFocusHandle>,
  628    /// The text buffer being edited
  629    buffer: Entity<MultiBuffer>,
  630    /// Map of how text in the buffer should be displayed.
  631    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  632    pub display_map: Entity<DisplayMap>,
  633    pub selections: SelectionsCollection,
  634    pub scroll_manager: ScrollManager,
  635    /// When inline assist editors are linked, they all render cursors because
  636    /// typing enters text into each of them, even the ones that aren't focused.
  637    pub(crate) show_cursor_when_unfocused: bool,
  638    columnar_selection_tail: Option<Anchor>,
  639    add_selections_state: Option<AddSelectionsState>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    selection_history: SelectionHistory,
  643    autoclose_regions: Vec<AutocloseRegion>,
  644    snippet_stack: InvalidationStack<SnippetState>,
  645    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  646    ime_transaction: Option<TransactionId>,
  647    active_diagnostics: Option<ActiveDiagnosticGroup>,
  648    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  649
  650    // TODO: make this a access method
  651    pub project: Option<Entity<Project>>,
  652    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  653    completion_provider: Option<Box<dyn CompletionProvider>>,
  654    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  655    blink_manager: Entity<BlinkManager>,
  656    show_cursor_names: bool,
  657    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  658    pub show_local_selections: bool,
  659    mode: EditorMode,
  660    show_breadcrumbs: bool,
  661    show_gutter: bool,
  662    show_scrollbars: bool,
  663    show_line_numbers: Option<bool>,
  664    use_relative_line_numbers: Option<bool>,
  665    show_git_diff_gutter: Option<bool>,
  666    show_code_actions: Option<bool>,
  667    show_runnables: Option<bool>,
  668    show_wrap_guides: Option<bool>,
  669    show_indent_guides: Option<bool>,
  670    placeholder_text: Option<Arc<str>>,
  671    highlight_order: usize,
  672    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  673    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  674    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  675    scrollbar_marker_state: ScrollbarMarkerState,
  676    active_indent_guides_state: ActiveIndentGuidesState,
  677    nav_history: Option<ItemNavHistory>,
  678    context_menu: RefCell<Option<CodeContextMenu>>,
  679    mouse_context_menu: Option<MouseContextMenu>,
  680    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  681    signature_help_state: SignatureHelpState,
  682    auto_signature_help: Option<bool>,
  683    find_all_references_task_sources: Vec<Anchor>,
  684    next_completion_id: CompletionId,
  685    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  686    code_actions_task: Option<Task<Result<()>>>,
  687    document_highlights_task: Option<Task<()>>,
  688    linked_editing_range_task: Option<Task<Option<()>>>,
  689    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  690    pending_rename: Option<RenameState>,
  691    searchable: bool,
  692    cursor_shape: CursorShape,
  693    current_line_highlight: Option<CurrentLineHighlight>,
  694    collapse_matches: bool,
  695    autoindent_mode: Option<AutoindentMode>,
  696    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  697    input_enabled: bool,
  698    use_modal_editing: bool,
  699    read_only: bool,
  700    leader_peer_id: Option<PeerId>,
  701    remote_id: Option<ViewId>,
  702    hover_state: HoverState,
  703    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  704    gutter_hovered: bool,
  705    hovered_link_state: Option<HoveredLinkState>,
  706    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  707    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  708    active_inline_completion: Option<InlineCompletionState>,
  709    /// Used to prevent flickering as the user types while the menu is open
  710    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  711    edit_prediction_settings: EditPredictionSettings,
  712    inline_completions_hidden_for_vim_mode: bool,
  713    show_inline_completions_override: Option<bool>,
  714    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  715    edit_prediction_preview: EditPredictionPreview,
  716    edit_prediction_cursor_on_leading_whitespace: bool,
  717    edit_prediction_requires_modifier_in_leading_space: bool,
  718    inlay_hint_cache: InlayHintCache,
  719    next_inlay_id: usize,
  720    _subscriptions: Vec<Subscription>,
  721    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  722    gutter_dimensions: GutterDimensions,
  723    style: Option<EditorStyle>,
  724    text_style_refinement: Option<TextStyleRefinement>,
  725    next_editor_action_id: EditorActionId,
  726    editor_actions:
  727        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  728    use_autoclose: bool,
  729    use_auto_surround: bool,
  730    auto_replace_emoji_shortcode: bool,
  731    show_git_blame_gutter: bool,
  732    show_git_blame_inline: bool,
  733    show_git_blame_inline_delay_task: Option<Task<()>>,
  734    distinguish_unstaged_diff_hunks: bool,
  735    git_blame_inline_enabled: bool,
  736    serialize_dirty_buffers: bool,
  737    show_selection_menu: Option<bool>,
  738    blame: Option<Entity<GitBlame>>,
  739    blame_subscription: Option<Subscription>,
  740    custom_context_menu: Option<
  741        Box<
  742            dyn 'static
  743                + Fn(
  744                    &mut Self,
  745                    DisplayPoint,
  746                    &mut Window,
  747                    &mut Context<Self>,
  748                ) -> Option<Entity<ui::ContextMenu>>,
  749        >,
  750    >,
  751    last_bounds: Option<Bounds<Pixels>>,
  752    last_position_map: Option<Rc<PositionMap>>,
  753    expect_bounds_change: Option<Bounds<Pixels>>,
  754    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  755    tasks_update_task: Option<Task<()>>,
  756    in_project_search: bool,
  757    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  758    breadcrumb_header: Option<String>,
  759    focused_block: Option<FocusedBlock>,
  760    next_scroll_position: NextScrollCursorCenterTopBottom,
  761    addons: HashMap<TypeId, Box<dyn Addon>>,
  762    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  763    selection_mark_mode: bool,
  764    toggle_fold_multiple_buffers: Task<()>,
  765    _scroll_cursor_center_top_bottom_task: Task<()>,
  766}
  767
  768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  769enum NextScrollCursorCenterTopBottom {
  770    #[default]
  771    Center,
  772    Top,
  773    Bottom,
  774}
  775
  776impl NextScrollCursorCenterTopBottom {
  777    fn next(&self) -> Self {
  778        match self {
  779            Self::Center => Self::Top,
  780            Self::Top => Self::Bottom,
  781            Self::Bottom => Self::Center,
  782        }
  783    }
  784}
  785
  786#[derive(Clone)]
  787pub struct EditorSnapshot {
  788    pub mode: EditorMode,
  789    show_gutter: bool,
  790    show_line_numbers: Option<bool>,
  791    show_git_diff_gutter: Option<bool>,
  792    show_code_actions: Option<bool>,
  793    show_runnables: Option<bool>,
  794    git_blame_gutter_max_author_length: Option<usize>,
  795    pub display_snapshot: DisplaySnapshot,
  796    pub placeholder_text: Option<Arc<str>>,
  797    is_focused: bool,
  798    scroll_anchor: ScrollAnchor,
  799    ongoing_scroll: OngoingScroll,
  800    current_line_highlight: CurrentLineHighlight,
  801    gutter_hovered: bool,
  802}
  803
  804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  805
  806#[derive(Default, Debug, Clone, Copy)]
  807pub struct GutterDimensions {
  808    pub left_padding: Pixels,
  809    pub right_padding: Pixels,
  810    pub width: Pixels,
  811    pub margin: Pixels,
  812    pub git_blame_entries_width: Option<Pixels>,
  813}
  814
  815impl GutterDimensions {
  816    /// The full width of the space taken up by the gutter.
  817    pub fn full_width(&self) -> Pixels {
  818        self.margin + self.width
  819    }
  820
  821    /// The width of the space reserved for the fold indicators,
  822    /// use alongside 'justify_end' and `gutter_width` to
  823    /// right align content with the line numbers
  824    pub fn fold_area_width(&self) -> Pixels {
  825        self.margin + self.right_padding
  826    }
  827}
  828
  829#[derive(Debug)]
  830pub struct RemoteSelection {
  831    pub replica_id: ReplicaId,
  832    pub selection: Selection<Anchor>,
  833    pub cursor_shape: CursorShape,
  834    pub peer_id: PeerId,
  835    pub line_mode: bool,
  836    pub participant_index: Option<ParticipantIndex>,
  837    pub user_name: Option<SharedString>,
  838}
  839
  840#[derive(Clone, Debug)]
  841struct SelectionHistoryEntry {
  842    selections: Arc<[Selection<Anchor>]>,
  843    select_next_state: Option<SelectNextState>,
  844    select_prev_state: Option<SelectNextState>,
  845    add_selections_state: Option<AddSelectionsState>,
  846}
  847
  848enum SelectionHistoryMode {
  849    Normal,
  850    Undoing,
  851    Redoing,
  852}
  853
  854#[derive(Clone, PartialEq, Eq, Hash)]
  855struct HoveredCursor {
  856    replica_id: u16,
  857    selection_id: usize,
  858}
  859
  860impl Default for SelectionHistoryMode {
  861    fn default() -> Self {
  862        Self::Normal
  863    }
  864}
  865
  866#[derive(Default)]
  867struct SelectionHistory {
  868    #[allow(clippy::type_complexity)]
  869    selections_by_transaction:
  870        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  871    mode: SelectionHistoryMode,
  872    undo_stack: VecDeque<SelectionHistoryEntry>,
  873    redo_stack: VecDeque<SelectionHistoryEntry>,
  874}
  875
  876impl SelectionHistory {
  877    fn insert_transaction(
  878        &mut self,
  879        transaction_id: TransactionId,
  880        selections: Arc<[Selection<Anchor>]>,
  881    ) {
  882        self.selections_by_transaction
  883            .insert(transaction_id, (selections, None));
  884    }
  885
  886    #[allow(clippy::type_complexity)]
  887    fn transaction(
  888        &self,
  889        transaction_id: TransactionId,
  890    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  891        self.selections_by_transaction.get(&transaction_id)
  892    }
  893
  894    #[allow(clippy::type_complexity)]
  895    fn transaction_mut(
  896        &mut self,
  897        transaction_id: TransactionId,
  898    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  899        self.selections_by_transaction.get_mut(&transaction_id)
  900    }
  901
  902    fn push(&mut self, entry: SelectionHistoryEntry) {
  903        if !entry.selections.is_empty() {
  904            match self.mode {
  905                SelectionHistoryMode::Normal => {
  906                    self.push_undo(entry);
  907                    self.redo_stack.clear();
  908                }
  909                SelectionHistoryMode::Undoing => self.push_redo(entry),
  910                SelectionHistoryMode::Redoing => self.push_undo(entry),
  911            }
  912        }
  913    }
  914
  915    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  916        if self
  917            .undo_stack
  918            .back()
  919            .map_or(true, |e| e.selections != entry.selections)
  920        {
  921            self.undo_stack.push_back(entry);
  922            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  923                self.undo_stack.pop_front();
  924            }
  925        }
  926    }
  927
  928    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  929        if self
  930            .redo_stack
  931            .back()
  932            .map_or(true, |e| e.selections != entry.selections)
  933        {
  934            self.redo_stack.push_back(entry);
  935            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  936                self.redo_stack.pop_front();
  937            }
  938        }
  939    }
  940}
  941
  942struct RowHighlight {
  943    index: usize,
  944    range: Range<Anchor>,
  945    color: Hsla,
  946    should_autoscroll: bool,
  947}
  948
  949#[derive(Clone, Debug)]
  950struct AddSelectionsState {
  951    above: bool,
  952    stack: Vec<usize>,
  953}
  954
  955#[derive(Clone)]
  956struct SelectNextState {
  957    query: AhoCorasick,
  958    wordwise: bool,
  959    done: bool,
  960}
  961
  962impl std::fmt::Debug for SelectNextState {
  963    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  964        f.debug_struct(std::any::type_name::<Self>())
  965            .field("wordwise", &self.wordwise)
  966            .field("done", &self.done)
  967            .finish()
  968    }
  969}
  970
  971#[derive(Debug)]
  972struct AutocloseRegion {
  973    selection_id: usize,
  974    range: Range<Anchor>,
  975    pair: BracketPair,
  976}
  977
  978#[derive(Debug)]
  979struct SnippetState {
  980    ranges: Vec<Vec<Range<Anchor>>>,
  981    active_index: usize,
  982    choices: Vec<Option<Vec<String>>>,
  983}
  984
  985#[doc(hidden)]
  986pub struct RenameState {
  987    pub range: Range<Anchor>,
  988    pub old_name: Arc<str>,
  989    pub editor: Entity<Editor>,
  990    block_id: CustomBlockId,
  991}
  992
  993struct InvalidationStack<T>(Vec<T>);
  994
  995struct RegisteredInlineCompletionProvider {
  996    provider: Arc<dyn InlineCompletionProviderHandle>,
  997    _subscription: Subscription,
  998}
  999
 1000#[derive(Debug)]
 1001struct ActiveDiagnosticGroup {
 1002    primary_range: Range<Anchor>,
 1003    primary_message: String,
 1004    group_id: usize,
 1005    blocks: HashMap<CustomBlockId, Diagnostic>,
 1006    is_valid: bool,
 1007}
 1008
 1009#[derive(Serialize, Deserialize, Clone, Debug)]
 1010pub struct ClipboardSelection {
 1011    pub len: usize,
 1012    pub is_entire_line: bool,
 1013    pub first_line_indent: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    Toggle(bool),
 1035    SettingsChange(InlayHintSettings),
 1036    NewLinesShown,
 1037    BufferEdited(HashSet<Arc<Language>>),
 1038    RefreshRequested,
 1039    ExcerptsRemoved(Vec<ExcerptId>),
 1040}
 1041
 1042impl InlayHintRefreshReason {
 1043    fn description(&self) -> &'static str {
 1044        match self {
 1045            Self::Toggle(_) => "toggle",
 1046            Self::SettingsChange(_) => "settings change",
 1047            Self::NewLinesShown => "new lines shown",
 1048            Self::BufferEdited(_) => "buffer edited",
 1049            Self::RefreshRequested => "refresh requested",
 1050            Self::ExcerptsRemoved(_) => "excerpts removed",
 1051        }
 1052    }
 1053}
 1054
 1055pub enum FormatTarget {
 1056    Buffers,
 1057    Ranges(Vec<Range<MultiBufferPoint>>),
 1058}
 1059
 1060pub(crate) struct FocusedBlock {
 1061    id: BlockId,
 1062    focus_handle: WeakFocusHandle,
 1063}
 1064
 1065#[derive(Clone)]
 1066enum JumpData {
 1067    MultiBufferRow {
 1068        row: MultiBufferRow,
 1069        line_offset_from_top: u32,
 1070    },
 1071    MultiBufferPoint {
 1072        excerpt_id: ExcerptId,
 1073        position: Point,
 1074        anchor: text::Anchor,
 1075        line_offset_from_top: u32,
 1076    },
 1077}
 1078
 1079pub enum MultibufferSelectionMode {
 1080    First,
 1081    All,
 1082}
 1083
 1084impl Editor {
 1085    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::SingleLine { auto_width: false },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn multi_line(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(EditorMode::Full, buffer, None, false, window, cx)
 1102    }
 1103
 1104    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1105        let buffer = cx.new(|cx| Buffer::local("", cx));
 1106        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1107        Self::new(
 1108            EditorMode::SingleLine { auto_width: true },
 1109            buffer,
 1110            None,
 1111            false,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            false,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn for_buffer(
 1131        buffer: Entity<Buffer>,
 1132        project: Option<Entity<Project>>,
 1133        window: &mut Window,
 1134        cx: &mut Context<Self>,
 1135    ) -> Self {
 1136        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1137        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        show_excerpt_controls: bool,
 1144        window: &mut Window,
 1145        cx: &mut Context<Self>,
 1146    ) -> Self {
 1147        Self::new(
 1148            EditorMode::Full,
 1149            buffer,
 1150            project,
 1151            show_excerpt_controls,
 1152            window,
 1153            cx,
 1154        )
 1155    }
 1156
 1157    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1158        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1159        let mut clone = Self::new(
 1160            self.mode,
 1161            self.buffer.clone(),
 1162            self.project.clone(),
 1163            show_excerpt_controls,
 1164            window,
 1165            cx,
 1166        );
 1167        self.display_map.update(cx, |display_map, cx| {
 1168            let snapshot = display_map.snapshot(cx);
 1169            clone.display_map.update(cx, |display_map, cx| {
 1170                display_map.set_state(&snapshot, cx);
 1171            });
 1172        });
 1173        clone.selections.clone_state(&self.selections);
 1174        clone.scroll_manager.clone_state(&self.scroll_manager);
 1175        clone.searchable = self.searchable;
 1176        clone
 1177    }
 1178
 1179    pub fn new(
 1180        mode: EditorMode,
 1181        buffer: Entity<MultiBuffer>,
 1182        project: Option<Entity<Project>>,
 1183        show_excerpt_controls: bool,
 1184        window: &mut Window,
 1185        cx: &mut Context<Self>,
 1186    ) -> Self {
 1187        let style = window.text_style();
 1188        let font_size = style.font_size.to_pixels(window.rem_size());
 1189        let editor = cx.entity().downgrade();
 1190        let fold_placeholder = FoldPlaceholder {
 1191            constrain_width: true,
 1192            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1193                let editor = editor.clone();
 1194                div()
 1195                    .id(fold_id)
 1196                    .bg(cx.theme().colors().ghost_element_background)
 1197                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1198                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1199                    .rounded_sm()
 1200                    .size_full()
 1201                    .cursor_pointer()
 1202                    .child("")
 1203                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1204                    .on_click(move |_, _window, cx| {
 1205                        editor
 1206                            .update(cx, |editor, cx| {
 1207                                editor.unfold_ranges(
 1208                                    &[fold_range.start..fold_range.end],
 1209                                    true,
 1210                                    false,
 1211                                    cx,
 1212                                );
 1213                                cx.stop_propagation();
 1214                            })
 1215                            .ok();
 1216                    })
 1217                    .into_any()
 1218            }),
 1219            merge_adjacent: true,
 1220            ..Default::default()
 1221        };
 1222        let display_map = cx.new(|cx| {
 1223            DisplayMap::new(
 1224                buffer.clone(),
 1225                style.font(),
 1226                font_size,
 1227                None,
 1228                show_excerpt_controls,
 1229                FILE_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1232                fold_placeholder,
 1233                cx,
 1234            )
 1235        });
 1236
 1237        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1238
 1239        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1240
 1241        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1242            .then(|| language_settings::SoftWrap::None);
 1243
 1244        let mut project_subscriptions = Vec::new();
 1245        if mode == EditorMode::Full {
 1246            if let Some(project) = project.as_ref() {
 1247                if buffer.read(cx).is_singleton() {
 1248                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1249                        cx.emit(EditorEvent::TitleChanged);
 1250                    }));
 1251                }
 1252                project_subscriptions.push(cx.subscribe_in(
 1253                    project,
 1254                    window,
 1255                    |editor, _, event, window, cx| {
 1256                        if let project::Event::RefreshInlayHints = event {
 1257                            editor
 1258                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1259                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1260                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1261                                let focus_handle = editor.focus_handle(cx);
 1262                                if focus_handle.is_focused(window) {
 1263                                    let snapshot = buffer.read(cx).snapshot();
 1264                                    for (range, snippet) in snippet_edits {
 1265                                        let editor_range =
 1266                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1267                                        editor
 1268                                            .insert_snippet(
 1269                                                &[editor_range],
 1270                                                snippet.clone(),
 1271                                                window,
 1272                                                cx,
 1273                                            )
 1274                                            .ok();
 1275                                    }
 1276                                }
 1277                            }
 1278                        }
 1279                    },
 1280                ));
 1281                if let Some(task_inventory) = project
 1282                    .read(cx)
 1283                    .task_store()
 1284                    .read(cx)
 1285                    .task_inventory()
 1286                    .cloned()
 1287                {
 1288                    project_subscriptions.push(cx.observe_in(
 1289                        &task_inventory,
 1290                        window,
 1291                        |editor, _, window, cx| {
 1292                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1293                        },
 1294                    ));
 1295                }
 1296            }
 1297        }
 1298
 1299        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1300
 1301        let inlay_hint_settings =
 1302            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1303        let focus_handle = cx.focus_handle();
 1304        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1305            .detach();
 1306        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1307            .detach();
 1308        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1309            .detach();
 1310        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1311            .detach();
 1312
 1313        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1314            Some(false)
 1315        } else {
 1316            None
 1317        };
 1318
 1319        let mut code_action_providers = Vec::new();
 1320        if let Some(project) = project.clone() {
 1321            get_uncommitted_diff_for_buffer(
 1322                &project,
 1323                buffer.read(cx).all_buffers(),
 1324                buffer.clone(),
 1325                cx,
 1326            );
 1327            code_action_providers.push(Rc::new(project) as Rc<_>);
 1328        }
 1329
 1330        let mut this = Self {
 1331            focus_handle,
 1332            show_cursor_when_unfocused: false,
 1333            last_focused_descendant: None,
 1334            buffer: buffer.clone(),
 1335            display_map: display_map.clone(),
 1336            selections,
 1337            scroll_manager: ScrollManager::new(cx),
 1338            columnar_selection_tail: None,
 1339            add_selections_state: None,
 1340            select_next_state: None,
 1341            select_prev_state: None,
 1342            selection_history: Default::default(),
 1343            autoclose_regions: Default::default(),
 1344            snippet_stack: Default::default(),
 1345            select_larger_syntax_node_stack: Vec::new(),
 1346            ime_transaction: Default::default(),
 1347            active_diagnostics: None,
 1348            soft_wrap_mode_override,
 1349            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1350            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1351            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1352            project,
 1353            blink_manager: blink_manager.clone(),
 1354            show_local_selections: true,
 1355            show_scrollbars: true,
 1356            mode,
 1357            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1358            show_gutter: mode == EditorMode::Full,
 1359            show_line_numbers: None,
 1360            use_relative_line_numbers: None,
 1361            show_git_diff_gutter: None,
 1362            show_code_actions: None,
 1363            show_runnables: None,
 1364            show_wrap_guides: None,
 1365            show_indent_guides,
 1366            placeholder_text: None,
 1367            highlight_order: 0,
 1368            highlighted_rows: HashMap::default(),
 1369            background_highlights: Default::default(),
 1370            gutter_highlights: TreeMap::default(),
 1371            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1372            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1373            nav_history: None,
 1374            context_menu: RefCell::new(None),
 1375            mouse_context_menu: None,
 1376            completion_tasks: Default::default(),
 1377            signature_help_state: SignatureHelpState::default(),
 1378            auto_signature_help: None,
 1379            find_all_references_task_sources: Vec::new(),
 1380            next_completion_id: 0,
 1381            next_inlay_id: 0,
 1382            code_action_providers,
 1383            available_code_actions: Default::default(),
 1384            code_actions_task: Default::default(),
 1385            document_highlights_task: Default::default(),
 1386            linked_editing_range_task: Default::default(),
 1387            pending_rename: Default::default(),
 1388            searchable: true,
 1389            cursor_shape: EditorSettings::get_global(cx)
 1390                .cursor_shape
 1391                .unwrap_or_default(),
 1392            current_line_highlight: None,
 1393            autoindent_mode: Some(AutoindentMode::EachLine),
 1394            collapse_matches: false,
 1395            workspace: None,
 1396            input_enabled: true,
 1397            use_modal_editing: mode == EditorMode::Full,
 1398            read_only: false,
 1399            use_autoclose: true,
 1400            use_auto_surround: true,
 1401            auto_replace_emoji_shortcode: false,
 1402            leader_peer_id: None,
 1403            remote_id: None,
 1404            hover_state: Default::default(),
 1405            pending_mouse_down: None,
 1406            hovered_link_state: Default::default(),
 1407            edit_prediction_provider: None,
 1408            active_inline_completion: None,
 1409            stale_inline_completion_in_menu: None,
 1410            edit_prediction_preview: EditPredictionPreview::Inactive,
 1411            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1412
 1413            gutter_hovered: false,
 1414            pixel_position_of_newest_cursor: None,
 1415            last_bounds: None,
 1416            last_position_map: None,
 1417            expect_bounds_change: None,
 1418            gutter_dimensions: GutterDimensions::default(),
 1419            style: None,
 1420            show_cursor_names: false,
 1421            hovered_cursors: Default::default(),
 1422            next_editor_action_id: EditorActionId::default(),
 1423            editor_actions: Rc::default(),
 1424            inline_completions_hidden_for_vim_mode: false,
 1425            show_inline_completions_override: None,
 1426            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1427            edit_prediction_settings: EditPredictionSettings::Disabled,
 1428            edit_prediction_cursor_on_leading_whitespace: false,
 1429            edit_prediction_requires_modifier_in_leading_space: true,
 1430            custom_context_menu: None,
 1431            show_git_blame_gutter: false,
 1432            show_git_blame_inline: false,
 1433            distinguish_unstaged_diff_hunks: false,
 1434            show_selection_menu: None,
 1435            show_git_blame_inline_delay_task: None,
 1436            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1437            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1438                .session
 1439                .restore_unsaved_buffers,
 1440            blame: None,
 1441            blame_subscription: None,
 1442            tasks: Default::default(),
 1443            _subscriptions: vec![
 1444                cx.observe(&buffer, Self::on_buffer_changed),
 1445                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1446                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1447                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1448                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1449                cx.observe_window_activation(window, |editor, window, cx| {
 1450                    let active = window.is_window_active();
 1451                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1452                        if active {
 1453                            blink_manager.enable(cx);
 1454                        } else {
 1455                            blink_manager.disable(cx);
 1456                        }
 1457                    });
 1458                }),
 1459            ],
 1460            tasks_update_task: None,
 1461            linked_edit_ranges: Default::default(),
 1462            in_project_search: false,
 1463            previous_search_ranges: None,
 1464            breadcrumb_header: None,
 1465            focused_block: None,
 1466            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1467            addons: HashMap::default(),
 1468            registered_buffers: HashMap::default(),
 1469            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1470            selection_mark_mode: false,
 1471            toggle_fold_multiple_buffers: Task::ready(()),
 1472            text_style_refinement: None,
 1473        };
 1474        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1475        this._subscriptions.extend(project_subscriptions);
 1476
 1477        this.end_selection(window, cx);
 1478        this.scroll_manager.show_scrollbar(window, cx);
 1479
 1480        if mode == EditorMode::Full {
 1481            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1482            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1483
 1484            if this.git_blame_inline_enabled {
 1485                this.git_blame_inline_enabled = true;
 1486                this.start_git_blame_inline(false, window, cx);
 1487            }
 1488
 1489            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1490                if let Some(project) = this.project.as_ref() {
 1491                    let lsp_store = project.read(cx).lsp_store();
 1492                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1493                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1494                    });
 1495                    this.registered_buffers
 1496                        .insert(buffer.read(cx).remote_id(), handle);
 1497                }
 1498            }
 1499        }
 1500
 1501        this.report_editor_event("Editor Opened", None, cx);
 1502        this
 1503    }
 1504
 1505    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1506        self.mouse_context_menu
 1507            .as_ref()
 1508            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1509    }
 1510
 1511    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1512        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1513    }
 1514
 1515    fn key_context_internal(
 1516        &self,
 1517        has_active_edit_prediction: bool,
 1518        window: &Window,
 1519        cx: &App,
 1520    ) -> KeyContext {
 1521        let mut key_context = KeyContext::new_with_defaults();
 1522        key_context.add("Editor");
 1523        let mode = match self.mode {
 1524            EditorMode::SingleLine { .. } => "single_line",
 1525            EditorMode::AutoHeight { .. } => "auto_height",
 1526            EditorMode::Full => "full",
 1527        };
 1528
 1529        if EditorSettings::jupyter_enabled(cx) {
 1530            key_context.add("jupyter");
 1531        }
 1532
 1533        key_context.set("mode", mode);
 1534        if self.pending_rename.is_some() {
 1535            key_context.add("renaming");
 1536        }
 1537
 1538        match self.context_menu.borrow().as_ref() {
 1539            Some(CodeContextMenu::Completions(_)) => {
 1540                key_context.add("menu");
 1541                key_context.add("showing_completions");
 1542            }
 1543            Some(CodeContextMenu::CodeActions(_)) => {
 1544                key_context.add("menu");
 1545                key_context.add("showing_code_actions")
 1546            }
 1547            None => {}
 1548        }
 1549
 1550        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1551        if !self.focus_handle(cx).contains_focused(window, cx)
 1552            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1553        {
 1554            for addon in self.addons.values() {
 1555                addon.extend_key_context(&mut key_context, cx)
 1556            }
 1557        }
 1558
 1559        if let Some(extension) = self
 1560            .buffer
 1561            .read(cx)
 1562            .as_singleton()
 1563            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1564        {
 1565            key_context.set("extension", extension.to_string());
 1566        }
 1567
 1568        if has_active_edit_prediction {
 1569            if self.edit_prediction_in_conflict() {
 1570                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1571            } else {
 1572                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1573                key_context.add("copilot_suggestion");
 1574            }
 1575        }
 1576
 1577        if self.selection_mark_mode {
 1578            key_context.add("selection_mode");
 1579        }
 1580
 1581        key_context
 1582    }
 1583
 1584    pub fn edit_prediction_in_conflict(&self) -> bool {
 1585        if !self.show_edit_predictions_in_menu() {
 1586            return false;
 1587        }
 1588
 1589        let showing_completions = self
 1590            .context_menu
 1591            .borrow()
 1592            .as_ref()
 1593            .map_or(false, |context| {
 1594                matches!(context, CodeContextMenu::Completions(_))
 1595            });
 1596
 1597        showing_completions
 1598            || self.edit_prediction_requires_modifier()
 1599            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1600            // bindings to insert tab characters.
 1601            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1602    }
 1603
 1604    pub fn accept_edit_prediction_keybind(
 1605        &self,
 1606        window: &Window,
 1607        cx: &App,
 1608    ) -> AcceptEditPredictionBinding {
 1609        let key_context = self.key_context_internal(true, window, cx);
 1610        let in_conflict = self.edit_prediction_in_conflict();
 1611
 1612        AcceptEditPredictionBinding(
 1613            window
 1614                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1615                .into_iter()
 1616                .filter(|binding| {
 1617                    !in_conflict
 1618                        || binding
 1619                            .keystrokes()
 1620                            .first()
 1621                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1622                })
 1623                .rev()
 1624                .min_by_key(|binding| {
 1625                    binding
 1626                        .keystrokes()
 1627                        .first()
 1628                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1629                }),
 1630        )
 1631    }
 1632
 1633    pub fn new_file(
 1634        workspace: &mut Workspace,
 1635        _: &workspace::NewFile,
 1636        window: &mut Window,
 1637        cx: &mut Context<Workspace>,
 1638    ) {
 1639        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1640            "Failed to create buffer",
 1641            window,
 1642            cx,
 1643            |e, _, _| match e.error_code() {
 1644                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1645                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1646                e.error_tag("required").unwrap_or("the latest version")
 1647            )),
 1648                _ => None,
 1649            },
 1650        );
 1651    }
 1652
 1653    pub fn new_in_workspace(
 1654        workspace: &mut Workspace,
 1655        window: &mut Window,
 1656        cx: &mut Context<Workspace>,
 1657    ) -> Task<Result<Entity<Editor>>> {
 1658        let project = workspace.project().clone();
 1659        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1660
 1661        cx.spawn_in(window, |workspace, mut cx| async move {
 1662            let buffer = create.await?;
 1663            workspace.update_in(&mut cx, |workspace, window, cx| {
 1664                let editor =
 1665                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1666                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1667                editor
 1668            })
 1669        })
 1670    }
 1671
 1672    fn new_file_vertical(
 1673        workspace: &mut Workspace,
 1674        _: &workspace::NewFileSplitVertical,
 1675        window: &mut Window,
 1676        cx: &mut Context<Workspace>,
 1677    ) {
 1678        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1679    }
 1680
 1681    fn new_file_horizontal(
 1682        workspace: &mut Workspace,
 1683        _: &workspace::NewFileSplitHorizontal,
 1684        window: &mut Window,
 1685        cx: &mut Context<Workspace>,
 1686    ) {
 1687        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1688    }
 1689
 1690    fn new_file_in_direction(
 1691        workspace: &mut Workspace,
 1692        direction: SplitDirection,
 1693        window: &mut Window,
 1694        cx: &mut Context<Workspace>,
 1695    ) {
 1696        let project = workspace.project().clone();
 1697        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1698
 1699        cx.spawn_in(window, |workspace, mut cx| async move {
 1700            let buffer = create.await?;
 1701            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1702                workspace.split_item(
 1703                    direction,
 1704                    Box::new(
 1705                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1706                    ),
 1707                    window,
 1708                    cx,
 1709                )
 1710            })?;
 1711            anyhow::Ok(())
 1712        })
 1713        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1714            match e.error_code() {
 1715                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1716                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1717                e.error_tag("required").unwrap_or("the latest version")
 1718            )),
 1719                _ => None,
 1720            }
 1721        });
 1722    }
 1723
 1724    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1725        self.leader_peer_id
 1726    }
 1727
 1728    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1729        &self.buffer
 1730    }
 1731
 1732    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1733        self.workspace.as_ref()?.0.upgrade()
 1734    }
 1735
 1736    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1737        self.buffer().read(cx).title(cx)
 1738    }
 1739
 1740    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1741        let git_blame_gutter_max_author_length = self
 1742            .render_git_blame_gutter(cx)
 1743            .then(|| {
 1744                if let Some(blame) = self.blame.as_ref() {
 1745                    let max_author_length =
 1746                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1747                    Some(max_author_length)
 1748                } else {
 1749                    None
 1750                }
 1751            })
 1752            .flatten();
 1753
 1754        EditorSnapshot {
 1755            mode: self.mode,
 1756            show_gutter: self.show_gutter,
 1757            show_line_numbers: self.show_line_numbers,
 1758            show_git_diff_gutter: self.show_git_diff_gutter,
 1759            show_code_actions: self.show_code_actions,
 1760            show_runnables: self.show_runnables,
 1761            git_blame_gutter_max_author_length,
 1762            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1763            scroll_anchor: self.scroll_manager.anchor(),
 1764            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1765            placeholder_text: self.placeholder_text.clone(),
 1766            is_focused: self.focus_handle.is_focused(window),
 1767            current_line_highlight: self
 1768                .current_line_highlight
 1769                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1770            gutter_hovered: self.gutter_hovered,
 1771        }
 1772    }
 1773
 1774    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1775        self.buffer.read(cx).language_at(point, cx)
 1776    }
 1777
 1778    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1779        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1780    }
 1781
 1782    pub fn active_excerpt(
 1783        &self,
 1784        cx: &App,
 1785    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1786        self.buffer
 1787            .read(cx)
 1788            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1789    }
 1790
 1791    pub fn mode(&self) -> EditorMode {
 1792        self.mode
 1793    }
 1794
 1795    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1796        self.collaboration_hub.as_deref()
 1797    }
 1798
 1799    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1800        self.collaboration_hub = Some(hub);
 1801    }
 1802
 1803    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1804        self.in_project_search = in_project_search;
 1805    }
 1806
 1807    pub fn set_custom_context_menu(
 1808        &mut self,
 1809        f: impl 'static
 1810            + Fn(
 1811                &mut Self,
 1812                DisplayPoint,
 1813                &mut Window,
 1814                &mut Context<Self>,
 1815            ) -> Option<Entity<ui::ContextMenu>>,
 1816    ) {
 1817        self.custom_context_menu = Some(Box::new(f))
 1818    }
 1819
 1820    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1821        self.completion_provider = provider;
 1822    }
 1823
 1824    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1825        self.semantics_provider.clone()
 1826    }
 1827
 1828    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1829        self.semantics_provider = provider;
 1830    }
 1831
 1832    pub fn set_edit_prediction_provider<T>(
 1833        &mut self,
 1834        provider: Option<Entity<T>>,
 1835        window: &mut Window,
 1836        cx: &mut Context<Self>,
 1837    ) where
 1838        T: EditPredictionProvider,
 1839    {
 1840        self.edit_prediction_provider =
 1841            provider.map(|provider| RegisteredInlineCompletionProvider {
 1842                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1843                    if this.focus_handle.is_focused(window) {
 1844                        this.update_visible_inline_completion(window, cx);
 1845                    }
 1846                }),
 1847                provider: Arc::new(provider),
 1848            });
 1849        self.refresh_inline_completion(false, false, window, cx);
 1850    }
 1851
 1852    pub fn placeholder_text(&self) -> Option<&str> {
 1853        self.placeholder_text.as_deref()
 1854    }
 1855
 1856    pub fn set_placeholder_text(
 1857        &mut self,
 1858        placeholder_text: impl Into<Arc<str>>,
 1859        cx: &mut Context<Self>,
 1860    ) {
 1861        let placeholder_text = Some(placeholder_text.into());
 1862        if self.placeholder_text != placeholder_text {
 1863            self.placeholder_text = placeholder_text;
 1864            cx.notify();
 1865        }
 1866    }
 1867
 1868    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1869        self.cursor_shape = cursor_shape;
 1870
 1871        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1872        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1873
 1874        cx.notify();
 1875    }
 1876
 1877    pub fn set_current_line_highlight(
 1878        &mut self,
 1879        current_line_highlight: Option<CurrentLineHighlight>,
 1880    ) {
 1881        self.current_line_highlight = current_line_highlight;
 1882    }
 1883
 1884    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1885        self.collapse_matches = collapse_matches;
 1886    }
 1887
 1888    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1889        let buffers = self.buffer.read(cx).all_buffers();
 1890        let Some(lsp_store) = self.lsp_store(cx) else {
 1891            return;
 1892        };
 1893        lsp_store.update(cx, |lsp_store, cx| {
 1894            for buffer in buffers {
 1895                self.registered_buffers
 1896                    .entry(buffer.read(cx).remote_id())
 1897                    .or_insert_with(|| {
 1898                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1899                    });
 1900            }
 1901        })
 1902    }
 1903
 1904    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1905        if self.collapse_matches {
 1906            return range.start..range.start;
 1907        }
 1908        range.clone()
 1909    }
 1910
 1911    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1912        if self.display_map.read(cx).clip_at_line_ends != clip {
 1913            self.display_map
 1914                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1915        }
 1916    }
 1917
 1918    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1919        self.input_enabled = input_enabled;
 1920    }
 1921
 1922    pub fn set_inline_completions_hidden_for_vim_mode(
 1923        &mut self,
 1924        hidden: bool,
 1925        window: &mut Window,
 1926        cx: &mut Context<Self>,
 1927    ) {
 1928        if hidden != self.inline_completions_hidden_for_vim_mode {
 1929            self.inline_completions_hidden_for_vim_mode = hidden;
 1930            if hidden {
 1931                self.update_visible_inline_completion(window, cx);
 1932            } else {
 1933                self.refresh_inline_completion(true, false, window, cx);
 1934            }
 1935        }
 1936    }
 1937
 1938    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1939        self.menu_inline_completions_policy = value;
 1940    }
 1941
 1942    pub fn set_autoindent(&mut self, autoindent: bool) {
 1943        if autoindent {
 1944            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1945        } else {
 1946            self.autoindent_mode = None;
 1947        }
 1948    }
 1949
 1950    pub fn read_only(&self, cx: &App) -> bool {
 1951        self.read_only || self.buffer.read(cx).read_only()
 1952    }
 1953
 1954    pub fn set_read_only(&mut self, read_only: bool) {
 1955        self.read_only = read_only;
 1956    }
 1957
 1958    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1959        self.use_autoclose = autoclose;
 1960    }
 1961
 1962    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1963        self.use_auto_surround = auto_surround;
 1964    }
 1965
 1966    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1967        self.auto_replace_emoji_shortcode = auto_replace;
 1968    }
 1969
 1970    pub fn toggle_inline_completions(
 1971        &mut self,
 1972        _: &ToggleEditPrediction,
 1973        window: &mut Window,
 1974        cx: &mut Context<Self>,
 1975    ) {
 1976        if self.show_inline_completions_override.is_some() {
 1977            self.set_show_edit_predictions(None, window, cx);
 1978        } else {
 1979            let show_edit_predictions = !self.edit_predictions_enabled();
 1980            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1981        }
 1982    }
 1983
 1984    pub fn set_show_edit_predictions(
 1985        &mut self,
 1986        show_edit_predictions: Option<bool>,
 1987        window: &mut Window,
 1988        cx: &mut Context<Self>,
 1989    ) {
 1990        self.show_inline_completions_override = show_edit_predictions;
 1991        self.refresh_inline_completion(false, true, window, cx);
 1992    }
 1993
 1994    fn inline_completions_disabled_in_scope(
 1995        &self,
 1996        buffer: &Entity<Buffer>,
 1997        buffer_position: language::Anchor,
 1998        cx: &App,
 1999    ) -> bool {
 2000        let snapshot = buffer.read(cx).snapshot();
 2001        let settings = snapshot.settings_at(buffer_position, cx);
 2002
 2003        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2004            return false;
 2005        };
 2006
 2007        scope.override_name().map_or(false, |scope_name| {
 2008            settings
 2009                .edit_predictions_disabled_in
 2010                .iter()
 2011                .any(|s| s == scope_name)
 2012        })
 2013    }
 2014
 2015    pub fn set_use_modal_editing(&mut self, to: bool) {
 2016        self.use_modal_editing = to;
 2017    }
 2018
 2019    pub fn use_modal_editing(&self) -> bool {
 2020        self.use_modal_editing
 2021    }
 2022
 2023    fn selections_did_change(
 2024        &mut self,
 2025        local: bool,
 2026        old_cursor_position: &Anchor,
 2027        show_completions: bool,
 2028        window: &mut Window,
 2029        cx: &mut Context<Self>,
 2030    ) {
 2031        window.invalidate_character_coordinates();
 2032
 2033        // Copy selections to primary selection buffer
 2034        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2035        if local {
 2036            let selections = self.selections.all::<usize>(cx);
 2037            let buffer_handle = self.buffer.read(cx).read(cx);
 2038
 2039            let mut text = String::new();
 2040            for (index, selection) in selections.iter().enumerate() {
 2041                let text_for_selection = buffer_handle
 2042                    .text_for_range(selection.start..selection.end)
 2043                    .collect::<String>();
 2044
 2045                text.push_str(&text_for_selection);
 2046                if index != selections.len() - 1 {
 2047                    text.push('\n');
 2048                }
 2049            }
 2050
 2051            if !text.is_empty() {
 2052                cx.write_to_primary(ClipboardItem::new_string(text));
 2053            }
 2054        }
 2055
 2056        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2057            self.buffer.update(cx, |buffer, cx| {
 2058                buffer.set_active_selections(
 2059                    &self.selections.disjoint_anchors(),
 2060                    self.selections.line_mode,
 2061                    self.cursor_shape,
 2062                    cx,
 2063                )
 2064            });
 2065        }
 2066        let display_map = self
 2067            .display_map
 2068            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2069        let buffer = &display_map.buffer_snapshot;
 2070        self.add_selections_state = None;
 2071        self.select_next_state = None;
 2072        self.select_prev_state = None;
 2073        self.select_larger_syntax_node_stack.clear();
 2074        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2075        self.snippet_stack
 2076            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2077        self.take_rename(false, window, cx);
 2078
 2079        let new_cursor_position = self.selections.newest_anchor().head();
 2080
 2081        self.push_to_nav_history(
 2082            *old_cursor_position,
 2083            Some(new_cursor_position.to_point(buffer)),
 2084            cx,
 2085        );
 2086
 2087        if local {
 2088            let new_cursor_position = self.selections.newest_anchor().head();
 2089            let mut context_menu = self.context_menu.borrow_mut();
 2090            let completion_menu = match context_menu.as_ref() {
 2091                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2092                _ => {
 2093                    *context_menu = None;
 2094                    None
 2095                }
 2096            };
 2097            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2098                if !self.registered_buffers.contains_key(&buffer_id) {
 2099                    if let Some(lsp_store) = self.lsp_store(cx) {
 2100                        lsp_store.update(cx, |lsp_store, cx| {
 2101                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2102                                return;
 2103                            };
 2104                            self.registered_buffers.insert(
 2105                                buffer_id,
 2106                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2107                            );
 2108                        })
 2109                    }
 2110                }
 2111            }
 2112
 2113            if let Some(completion_menu) = completion_menu {
 2114                let cursor_position = new_cursor_position.to_offset(buffer);
 2115                let (word_range, kind) =
 2116                    buffer.surrounding_word(completion_menu.initial_position, true);
 2117                if kind == Some(CharKind::Word)
 2118                    && word_range.to_inclusive().contains(&cursor_position)
 2119                {
 2120                    let mut completion_menu = completion_menu.clone();
 2121                    drop(context_menu);
 2122
 2123                    let query = Self::completion_query(buffer, cursor_position);
 2124                    cx.spawn(move |this, mut cx| async move {
 2125                        completion_menu
 2126                            .filter(query.as_deref(), cx.background_executor().clone())
 2127                            .await;
 2128
 2129                        this.update(&mut cx, |this, cx| {
 2130                            let mut context_menu = this.context_menu.borrow_mut();
 2131                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2132                            else {
 2133                                return;
 2134                            };
 2135
 2136                            if menu.id > completion_menu.id {
 2137                                return;
 2138                            }
 2139
 2140                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2141                            drop(context_menu);
 2142                            cx.notify();
 2143                        })
 2144                    })
 2145                    .detach();
 2146
 2147                    if show_completions {
 2148                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2149                    }
 2150                } else {
 2151                    drop(context_menu);
 2152                    self.hide_context_menu(window, cx);
 2153                }
 2154            } else {
 2155                drop(context_menu);
 2156            }
 2157
 2158            hide_hover(self, cx);
 2159
 2160            if old_cursor_position.to_display_point(&display_map).row()
 2161                != new_cursor_position.to_display_point(&display_map).row()
 2162            {
 2163                self.available_code_actions.take();
 2164            }
 2165            self.refresh_code_actions(window, cx);
 2166            self.refresh_document_highlights(cx);
 2167            refresh_matching_bracket_highlights(self, window, cx);
 2168            self.update_visible_inline_completion(window, cx);
 2169            self.edit_prediction_requires_modifier_in_leading_space = true;
 2170            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2171            if self.git_blame_inline_enabled {
 2172                self.start_inline_blame_timer(window, cx);
 2173            }
 2174        }
 2175
 2176        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2177        cx.emit(EditorEvent::SelectionsChanged { local });
 2178
 2179        if self.selections.disjoint_anchors().len() == 1 {
 2180            cx.emit(SearchEvent::ActiveMatchChanged)
 2181        }
 2182        cx.notify();
 2183    }
 2184
 2185    pub fn change_selections<R>(
 2186        &mut self,
 2187        autoscroll: Option<Autoscroll>,
 2188        window: &mut Window,
 2189        cx: &mut Context<Self>,
 2190        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2191    ) -> R {
 2192        self.change_selections_inner(autoscroll, true, window, cx, change)
 2193    }
 2194
 2195    pub fn change_selections_inner<R>(
 2196        &mut self,
 2197        autoscroll: Option<Autoscroll>,
 2198        request_completions: bool,
 2199        window: &mut Window,
 2200        cx: &mut Context<Self>,
 2201        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2202    ) -> R {
 2203        let old_cursor_position = self.selections.newest_anchor().head();
 2204        self.push_to_selection_history();
 2205
 2206        let (changed, result) = self.selections.change_with(cx, change);
 2207
 2208        if changed {
 2209            if let Some(autoscroll) = autoscroll {
 2210                self.request_autoscroll(autoscroll, cx);
 2211            }
 2212            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2213
 2214            if self.should_open_signature_help_automatically(
 2215                &old_cursor_position,
 2216                self.signature_help_state.backspace_pressed(),
 2217                cx,
 2218            ) {
 2219                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2220            }
 2221            self.signature_help_state.set_backspace_pressed(false);
 2222        }
 2223
 2224        result
 2225    }
 2226
 2227    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2228    where
 2229        I: IntoIterator<Item = (Range<S>, T)>,
 2230        S: ToOffset,
 2231        T: Into<Arc<str>>,
 2232    {
 2233        if self.read_only(cx) {
 2234            return;
 2235        }
 2236
 2237        self.buffer
 2238            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2239    }
 2240
 2241    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2242    where
 2243        I: IntoIterator<Item = (Range<S>, T)>,
 2244        S: ToOffset,
 2245        T: Into<Arc<str>>,
 2246    {
 2247        if self.read_only(cx) {
 2248            return;
 2249        }
 2250
 2251        self.buffer.update(cx, |buffer, cx| {
 2252            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2253        });
 2254    }
 2255
 2256    pub fn edit_with_block_indent<I, S, T>(
 2257        &mut self,
 2258        edits: I,
 2259        original_indent_columns: Vec<u32>,
 2260        cx: &mut Context<Self>,
 2261    ) where
 2262        I: IntoIterator<Item = (Range<S>, T)>,
 2263        S: ToOffset,
 2264        T: Into<Arc<str>>,
 2265    {
 2266        if self.read_only(cx) {
 2267            return;
 2268        }
 2269
 2270        self.buffer.update(cx, |buffer, cx| {
 2271            buffer.edit(
 2272                edits,
 2273                Some(AutoindentMode::Block {
 2274                    original_indent_columns,
 2275                }),
 2276                cx,
 2277            )
 2278        });
 2279    }
 2280
 2281    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2282        self.hide_context_menu(window, cx);
 2283
 2284        match phase {
 2285            SelectPhase::Begin {
 2286                position,
 2287                add,
 2288                click_count,
 2289            } => self.begin_selection(position, add, click_count, window, cx),
 2290            SelectPhase::BeginColumnar {
 2291                position,
 2292                goal_column,
 2293                reset,
 2294            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2295            SelectPhase::Extend {
 2296                position,
 2297                click_count,
 2298            } => self.extend_selection(position, click_count, window, cx),
 2299            SelectPhase::Update {
 2300                position,
 2301                goal_column,
 2302                scroll_delta,
 2303            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2304            SelectPhase::End => self.end_selection(window, cx),
 2305        }
 2306    }
 2307
 2308    fn extend_selection(
 2309        &mut self,
 2310        position: DisplayPoint,
 2311        click_count: usize,
 2312        window: &mut Window,
 2313        cx: &mut Context<Self>,
 2314    ) {
 2315        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2316        let tail = self.selections.newest::<usize>(cx).tail();
 2317        self.begin_selection(position, false, click_count, window, cx);
 2318
 2319        let position = position.to_offset(&display_map, Bias::Left);
 2320        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2321
 2322        let mut pending_selection = self
 2323            .selections
 2324            .pending_anchor()
 2325            .expect("extend_selection not called with pending selection");
 2326        if position >= tail {
 2327            pending_selection.start = tail_anchor;
 2328        } else {
 2329            pending_selection.end = tail_anchor;
 2330            pending_selection.reversed = true;
 2331        }
 2332
 2333        let mut pending_mode = self.selections.pending_mode().unwrap();
 2334        match &mut pending_mode {
 2335            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2336            _ => {}
 2337        }
 2338
 2339        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2340            s.set_pending(pending_selection, pending_mode)
 2341        });
 2342    }
 2343
 2344    fn begin_selection(
 2345        &mut self,
 2346        position: DisplayPoint,
 2347        add: bool,
 2348        click_count: usize,
 2349        window: &mut Window,
 2350        cx: &mut Context<Self>,
 2351    ) {
 2352        if !self.focus_handle.is_focused(window) {
 2353            self.last_focused_descendant = None;
 2354            window.focus(&self.focus_handle);
 2355        }
 2356
 2357        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2358        let buffer = &display_map.buffer_snapshot;
 2359        let newest_selection = self.selections.newest_anchor().clone();
 2360        let position = display_map.clip_point(position, Bias::Left);
 2361
 2362        let start;
 2363        let end;
 2364        let mode;
 2365        let mut auto_scroll;
 2366        match click_count {
 2367            1 => {
 2368                start = buffer.anchor_before(position.to_point(&display_map));
 2369                end = start;
 2370                mode = SelectMode::Character;
 2371                auto_scroll = true;
 2372            }
 2373            2 => {
 2374                let range = movement::surrounding_word(&display_map, position);
 2375                start = buffer.anchor_before(range.start.to_point(&display_map));
 2376                end = buffer.anchor_before(range.end.to_point(&display_map));
 2377                mode = SelectMode::Word(start..end);
 2378                auto_scroll = true;
 2379            }
 2380            3 => {
 2381                let position = display_map
 2382                    .clip_point(position, Bias::Left)
 2383                    .to_point(&display_map);
 2384                let line_start = display_map.prev_line_boundary(position).0;
 2385                let next_line_start = buffer.clip_point(
 2386                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2387                    Bias::Left,
 2388                );
 2389                start = buffer.anchor_before(line_start);
 2390                end = buffer.anchor_before(next_line_start);
 2391                mode = SelectMode::Line(start..end);
 2392                auto_scroll = true;
 2393            }
 2394            _ => {
 2395                start = buffer.anchor_before(0);
 2396                end = buffer.anchor_before(buffer.len());
 2397                mode = SelectMode::All;
 2398                auto_scroll = false;
 2399            }
 2400        }
 2401        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2402
 2403        let point_to_delete: Option<usize> = {
 2404            let selected_points: Vec<Selection<Point>> =
 2405                self.selections.disjoint_in_range(start..end, cx);
 2406
 2407            if !add || click_count > 1 {
 2408                None
 2409            } else if !selected_points.is_empty() {
 2410                Some(selected_points[0].id)
 2411            } else {
 2412                let clicked_point_already_selected =
 2413                    self.selections.disjoint.iter().find(|selection| {
 2414                        selection.start.to_point(buffer) == start.to_point(buffer)
 2415                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2416                    });
 2417
 2418                clicked_point_already_selected.map(|selection| selection.id)
 2419            }
 2420        };
 2421
 2422        let selections_count = self.selections.count();
 2423
 2424        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2425            if let Some(point_to_delete) = point_to_delete {
 2426                s.delete(point_to_delete);
 2427
 2428                if selections_count == 1 {
 2429                    s.set_pending_anchor_range(start..end, mode);
 2430                }
 2431            } else {
 2432                if !add {
 2433                    s.clear_disjoint();
 2434                } else if click_count > 1 {
 2435                    s.delete(newest_selection.id)
 2436                }
 2437
 2438                s.set_pending_anchor_range(start..end, mode);
 2439            }
 2440        });
 2441    }
 2442
 2443    fn begin_columnar_selection(
 2444        &mut self,
 2445        position: DisplayPoint,
 2446        goal_column: u32,
 2447        reset: bool,
 2448        window: &mut Window,
 2449        cx: &mut Context<Self>,
 2450    ) {
 2451        if !self.focus_handle.is_focused(window) {
 2452            self.last_focused_descendant = None;
 2453            window.focus(&self.focus_handle);
 2454        }
 2455
 2456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2457
 2458        if reset {
 2459            let pointer_position = display_map
 2460                .buffer_snapshot
 2461                .anchor_before(position.to_point(&display_map));
 2462
 2463            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2464                s.clear_disjoint();
 2465                s.set_pending_anchor_range(
 2466                    pointer_position..pointer_position,
 2467                    SelectMode::Character,
 2468                );
 2469            });
 2470        }
 2471
 2472        let tail = self.selections.newest::<Point>(cx).tail();
 2473        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2474
 2475        if !reset {
 2476            self.select_columns(
 2477                tail.to_display_point(&display_map),
 2478                position,
 2479                goal_column,
 2480                &display_map,
 2481                window,
 2482                cx,
 2483            );
 2484        }
 2485    }
 2486
 2487    fn update_selection(
 2488        &mut self,
 2489        position: DisplayPoint,
 2490        goal_column: u32,
 2491        scroll_delta: gpui::Point<f32>,
 2492        window: &mut Window,
 2493        cx: &mut Context<Self>,
 2494    ) {
 2495        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2496
 2497        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2498            let tail = tail.to_display_point(&display_map);
 2499            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2500        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2501            let buffer = self.buffer.read(cx).snapshot(cx);
 2502            let head;
 2503            let tail;
 2504            let mode = self.selections.pending_mode().unwrap();
 2505            match &mode {
 2506                SelectMode::Character => {
 2507                    head = position.to_point(&display_map);
 2508                    tail = pending.tail().to_point(&buffer);
 2509                }
 2510                SelectMode::Word(original_range) => {
 2511                    let original_display_range = original_range.start.to_display_point(&display_map)
 2512                        ..original_range.end.to_display_point(&display_map);
 2513                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2514                        ..original_display_range.end.to_point(&display_map);
 2515                    if movement::is_inside_word(&display_map, position)
 2516                        || original_display_range.contains(&position)
 2517                    {
 2518                        let word_range = movement::surrounding_word(&display_map, position);
 2519                        if word_range.start < original_display_range.start {
 2520                            head = word_range.start.to_point(&display_map);
 2521                        } else {
 2522                            head = word_range.end.to_point(&display_map);
 2523                        }
 2524                    } else {
 2525                        head = position.to_point(&display_map);
 2526                    }
 2527
 2528                    if head <= original_buffer_range.start {
 2529                        tail = original_buffer_range.end;
 2530                    } else {
 2531                        tail = original_buffer_range.start;
 2532                    }
 2533                }
 2534                SelectMode::Line(original_range) => {
 2535                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2536
 2537                    let position = display_map
 2538                        .clip_point(position, Bias::Left)
 2539                        .to_point(&display_map);
 2540                    let line_start = display_map.prev_line_boundary(position).0;
 2541                    let next_line_start = buffer.clip_point(
 2542                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2543                        Bias::Left,
 2544                    );
 2545
 2546                    if line_start < original_range.start {
 2547                        head = line_start
 2548                    } else {
 2549                        head = next_line_start
 2550                    }
 2551
 2552                    if head <= original_range.start {
 2553                        tail = original_range.end;
 2554                    } else {
 2555                        tail = original_range.start;
 2556                    }
 2557                }
 2558                SelectMode::All => {
 2559                    return;
 2560                }
 2561            };
 2562
 2563            if head < tail {
 2564                pending.start = buffer.anchor_before(head);
 2565                pending.end = buffer.anchor_before(tail);
 2566                pending.reversed = true;
 2567            } else {
 2568                pending.start = buffer.anchor_before(tail);
 2569                pending.end = buffer.anchor_before(head);
 2570                pending.reversed = false;
 2571            }
 2572
 2573            self.change_selections(None, window, cx, |s| {
 2574                s.set_pending(pending, mode);
 2575            });
 2576        } else {
 2577            log::error!("update_selection dispatched with no pending selection");
 2578            return;
 2579        }
 2580
 2581        self.apply_scroll_delta(scroll_delta, window, cx);
 2582        cx.notify();
 2583    }
 2584
 2585    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2586        self.columnar_selection_tail.take();
 2587        if self.selections.pending_anchor().is_some() {
 2588            let selections = self.selections.all::<usize>(cx);
 2589            self.change_selections(None, window, cx, |s| {
 2590                s.select(selections);
 2591                s.clear_pending();
 2592            });
 2593        }
 2594    }
 2595
 2596    fn select_columns(
 2597        &mut self,
 2598        tail: DisplayPoint,
 2599        head: DisplayPoint,
 2600        goal_column: u32,
 2601        display_map: &DisplaySnapshot,
 2602        window: &mut Window,
 2603        cx: &mut Context<Self>,
 2604    ) {
 2605        let start_row = cmp::min(tail.row(), head.row());
 2606        let end_row = cmp::max(tail.row(), head.row());
 2607        let start_column = cmp::min(tail.column(), goal_column);
 2608        let end_column = cmp::max(tail.column(), goal_column);
 2609        let reversed = start_column < tail.column();
 2610
 2611        let selection_ranges = (start_row.0..=end_row.0)
 2612            .map(DisplayRow)
 2613            .filter_map(|row| {
 2614                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2615                    let start = display_map
 2616                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2617                        .to_point(display_map);
 2618                    let end = display_map
 2619                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2620                        .to_point(display_map);
 2621                    if reversed {
 2622                        Some(end..start)
 2623                    } else {
 2624                        Some(start..end)
 2625                    }
 2626                } else {
 2627                    None
 2628                }
 2629            })
 2630            .collect::<Vec<_>>();
 2631
 2632        self.change_selections(None, window, cx, |s| {
 2633            s.select_ranges(selection_ranges);
 2634        });
 2635        cx.notify();
 2636    }
 2637
 2638    pub fn has_pending_nonempty_selection(&self) -> bool {
 2639        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2640            Some(Selection { start, end, .. }) => start != end,
 2641            None => false,
 2642        };
 2643
 2644        pending_nonempty_selection
 2645            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2646    }
 2647
 2648    pub fn has_pending_selection(&self) -> bool {
 2649        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2650    }
 2651
 2652    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2653        self.selection_mark_mode = false;
 2654
 2655        if self.clear_expanded_diff_hunks(cx) {
 2656            cx.notify();
 2657            return;
 2658        }
 2659        if self.dismiss_menus_and_popups(true, window, cx) {
 2660            return;
 2661        }
 2662
 2663        if self.mode == EditorMode::Full
 2664            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2665        {
 2666            return;
 2667        }
 2668
 2669        cx.propagate();
 2670    }
 2671
 2672    pub fn dismiss_menus_and_popups(
 2673        &mut self,
 2674        is_user_requested: bool,
 2675        window: &mut Window,
 2676        cx: &mut Context<Self>,
 2677    ) -> bool {
 2678        if self.take_rename(false, window, cx).is_some() {
 2679            return true;
 2680        }
 2681
 2682        if hide_hover(self, cx) {
 2683            return true;
 2684        }
 2685
 2686        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2687            return true;
 2688        }
 2689
 2690        if self.hide_context_menu(window, cx).is_some() {
 2691            return true;
 2692        }
 2693
 2694        if self.mouse_context_menu.take().is_some() {
 2695            return true;
 2696        }
 2697
 2698        if is_user_requested && self.discard_inline_completion(true, cx) {
 2699            return true;
 2700        }
 2701
 2702        if self.snippet_stack.pop().is_some() {
 2703            return true;
 2704        }
 2705
 2706        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2707            self.dismiss_diagnostics(cx);
 2708            return true;
 2709        }
 2710
 2711        false
 2712    }
 2713
 2714    fn linked_editing_ranges_for(
 2715        &self,
 2716        selection: Range<text::Anchor>,
 2717        cx: &App,
 2718    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2719        if self.linked_edit_ranges.is_empty() {
 2720            return None;
 2721        }
 2722        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2723            selection.end.buffer_id.and_then(|end_buffer_id| {
 2724                if selection.start.buffer_id != Some(end_buffer_id) {
 2725                    return None;
 2726                }
 2727                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2728                let snapshot = buffer.read(cx).snapshot();
 2729                self.linked_edit_ranges
 2730                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2731                    .map(|ranges| (ranges, snapshot, buffer))
 2732            })?;
 2733        use text::ToOffset as TO;
 2734        // find offset from the start of current range to current cursor position
 2735        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2736
 2737        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2738        let start_difference = start_offset - start_byte_offset;
 2739        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2740        let end_difference = end_offset - start_byte_offset;
 2741        // Current range has associated linked ranges.
 2742        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2743        for range in linked_ranges.iter() {
 2744            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2745            let end_offset = start_offset + end_difference;
 2746            let start_offset = start_offset + start_difference;
 2747            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2748                continue;
 2749            }
 2750            if self.selections.disjoint_anchor_ranges().any(|s| {
 2751                if s.start.buffer_id != selection.start.buffer_id
 2752                    || s.end.buffer_id != selection.end.buffer_id
 2753                {
 2754                    return false;
 2755                }
 2756                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2757                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2758            }) {
 2759                continue;
 2760            }
 2761            let start = buffer_snapshot.anchor_after(start_offset);
 2762            let end = buffer_snapshot.anchor_after(end_offset);
 2763            linked_edits
 2764                .entry(buffer.clone())
 2765                .or_default()
 2766                .push(start..end);
 2767        }
 2768        Some(linked_edits)
 2769    }
 2770
 2771    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2772        let text: Arc<str> = text.into();
 2773
 2774        if self.read_only(cx) {
 2775            return;
 2776        }
 2777
 2778        let selections = self.selections.all_adjusted(cx);
 2779        let mut bracket_inserted = false;
 2780        let mut edits = Vec::new();
 2781        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2782        let mut new_selections = Vec::with_capacity(selections.len());
 2783        let mut new_autoclose_regions = Vec::new();
 2784        let snapshot = self.buffer.read(cx).read(cx);
 2785
 2786        for (selection, autoclose_region) in
 2787            self.selections_with_autoclose_regions(selections, &snapshot)
 2788        {
 2789            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2790                // Determine if the inserted text matches the opening or closing
 2791                // bracket of any of this language's bracket pairs.
 2792                let mut bracket_pair = None;
 2793                let mut is_bracket_pair_start = false;
 2794                let mut is_bracket_pair_end = false;
 2795                if !text.is_empty() {
 2796                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2797                    //  and they are removing the character that triggered IME popup.
 2798                    for (pair, enabled) in scope.brackets() {
 2799                        if !pair.close && !pair.surround {
 2800                            continue;
 2801                        }
 2802
 2803                        if enabled && pair.start.ends_with(text.as_ref()) {
 2804                            let prefix_len = pair.start.len() - text.len();
 2805                            let preceding_text_matches_prefix = prefix_len == 0
 2806                                || (selection.start.column >= (prefix_len as u32)
 2807                                    && snapshot.contains_str_at(
 2808                                        Point::new(
 2809                                            selection.start.row,
 2810                                            selection.start.column - (prefix_len as u32),
 2811                                        ),
 2812                                        &pair.start[..prefix_len],
 2813                                    ));
 2814                            if preceding_text_matches_prefix {
 2815                                bracket_pair = Some(pair.clone());
 2816                                is_bracket_pair_start = true;
 2817                                break;
 2818                            }
 2819                        }
 2820                        if pair.end.as_str() == text.as_ref() {
 2821                            bracket_pair = Some(pair.clone());
 2822                            is_bracket_pair_end = true;
 2823                            break;
 2824                        }
 2825                    }
 2826                }
 2827
 2828                if let Some(bracket_pair) = bracket_pair {
 2829                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2830                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2831                    let auto_surround =
 2832                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2833                    if selection.is_empty() {
 2834                        if is_bracket_pair_start {
 2835                            // If the inserted text is a suffix of an opening bracket and the
 2836                            // selection is preceded by the rest of the opening bracket, then
 2837                            // insert the closing bracket.
 2838                            let following_text_allows_autoclose = snapshot
 2839                                .chars_at(selection.start)
 2840                                .next()
 2841                                .map_or(true, |c| scope.should_autoclose_before(c));
 2842
 2843                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2844                                && bracket_pair.start.len() == 1
 2845                            {
 2846                                let target = bracket_pair.start.chars().next().unwrap();
 2847                                let current_line_count = snapshot
 2848                                    .reversed_chars_at(selection.start)
 2849                                    .take_while(|&c| c != '\n')
 2850                                    .filter(|&c| c == target)
 2851                                    .count();
 2852                                current_line_count % 2 == 1
 2853                            } else {
 2854                                false
 2855                            };
 2856
 2857                            if autoclose
 2858                                && bracket_pair.close
 2859                                && following_text_allows_autoclose
 2860                                && !is_closing_quote
 2861                            {
 2862                                let anchor = snapshot.anchor_before(selection.end);
 2863                                new_selections.push((selection.map(|_| anchor), text.len()));
 2864                                new_autoclose_regions.push((
 2865                                    anchor,
 2866                                    text.len(),
 2867                                    selection.id,
 2868                                    bracket_pair.clone(),
 2869                                ));
 2870                                edits.push((
 2871                                    selection.range(),
 2872                                    format!("{}{}", text, bracket_pair.end).into(),
 2873                                ));
 2874                                bracket_inserted = true;
 2875                                continue;
 2876                            }
 2877                        }
 2878
 2879                        if let Some(region) = autoclose_region {
 2880                            // If the selection is followed by an auto-inserted closing bracket,
 2881                            // then don't insert that closing bracket again; just move the selection
 2882                            // past the closing bracket.
 2883                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2884                                && text.as_ref() == region.pair.end.as_str();
 2885                            if should_skip {
 2886                                let anchor = snapshot.anchor_after(selection.end);
 2887                                new_selections
 2888                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2889                                continue;
 2890                            }
 2891                        }
 2892
 2893                        let always_treat_brackets_as_autoclosed = snapshot
 2894                            .settings_at(selection.start, cx)
 2895                            .always_treat_brackets_as_autoclosed;
 2896                        if always_treat_brackets_as_autoclosed
 2897                            && is_bracket_pair_end
 2898                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2899                        {
 2900                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2901                            // and the inserted text is a closing bracket and the selection is followed
 2902                            // by the closing bracket then move the selection past the closing bracket.
 2903                            let anchor = snapshot.anchor_after(selection.end);
 2904                            new_selections.push((selection.map(|_| anchor), text.len()));
 2905                            continue;
 2906                        }
 2907                    }
 2908                    // If an opening bracket is 1 character long and is typed while
 2909                    // text is selected, then surround that text with the bracket pair.
 2910                    else if auto_surround
 2911                        && bracket_pair.surround
 2912                        && is_bracket_pair_start
 2913                        && bracket_pair.start.chars().count() == 1
 2914                    {
 2915                        edits.push((selection.start..selection.start, text.clone()));
 2916                        edits.push((
 2917                            selection.end..selection.end,
 2918                            bracket_pair.end.as_str().into(),
 2919                        ));
 2920                        bracket_inserted = true;
 2921                        new_selections.push((
 2922                            Selection {
 2923                                id: selection.id,
 2924                                start: snapshot.anchor_after(selection.start),
 2925                                end: snapshot.anchor_before(selection.end),
 2926                                reversed: selection.reversed,
 2927                                goal: selection.goal,
 2928                            },
 2929                            0,
 2930                        ));
 2931                        continue;
 2932                    }
 2933                }
 2934            }
 2935
 2936            if self.auto_replace_emoji_shortcode
 2937                && selection.is_empty()
 2938                && text.as_ref().ends_with(':')
 2939            {
 2940                if let Some(possible_emoji_short_code) =
 2941                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2942                {
 2943                    if !possible_emoji_short_code.is_empty() {
 2944                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2945                            let emoji_shortcode_start = Point::new(
 2946                                selection.start.row,
 2947                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2948                            );
 2949
 2950                            // Remove shortcode from buffer
 2951                            edits.push((
 2952                                emoji_shortcode_start..selection.start,
 2953                                "".to_string().into(),
 2954                            ));
 2955                            new_selections.push((
 2956                                Selection {
 2957                                    id: selection.id,
 2958                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2959                                    end: snapshot.anchor_before(selection.start),
 2960                                    reversed: selection.reversed,
 2961                                    goal: selection.goal,
 2962                                },
 2963                                0,
 2964                            ));
 2965
 2966                            // Insert emoji
 2967                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2968                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2969                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2970
 2971                            continue;
 2972                        }
 2973                    }
 2974                }
 2975            }
 2976
 2977            // If not handling any auto-close operation, then just replace the selected
 2978            // text with the given input and move the selection to the end of the
 2979            // newly inserted text.
 2980            let anchor = snapshot.anchor_after(selection.end);
 2981            if !self.linked_edit_ranges.is_empty() {
 2982                let start_anchor = snapshot.anchor_before(selection.start);
 2983
 2984                let is_word_char = text.chars().next().map_or(true, |char| {
 2985                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2986                    classifier.is_word(char)
 2987                });
 2988
 2989                if is_word_char {
 2990                    if let Some(ranges) = self
 2991                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2992                    {
 2993                        for (buffer, edits) in ranges {
 2994                            linked_edits
 2995                                .entry(buffer.clone())
 2996                                .or_default()
 2997                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2998                        }
 2999                    }
 3000                }
 3001            }
 3002
 3003            new_selections.push((selection.map(|_| anchor), 0));
 3004            edits.push((selection.start..selection.end, text.clone()));
 3005        }
 3006
 3007        drop(snapshot);
 3008
 3009        self.transact(window, cx, |this, window, cx| {
 3010            this.buffer.update(cx, |buffer, cx| {
 3011                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3012            });
 3013            for (buffer, edits) in linked_edits {
 3014                buffer.update(cx, |buffer, cx| {
 3015                    let snapshot = buffer.snapshot();
 3016                    let edits = edits
 3017                        .into_iter()
 3018                        .map(|(range, text)| {
 3019                            use text::ToPoint as TP;
 3020                            let end_point = TP::to_point(&range.end, &snapshot);
 3021                            let start_point = TP::to_point(&range.start, &snapshot);
 3022                            (start_point..end_point, text)
 3023                        })
 3024                        .sorted_by_key(|(range, _)| range.start)
 3025                        .collect::<Vec<_>>();
 3026                    buffer.edit(edits, None, cx);
 3027                })
 3028            }
 3029            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3030            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3031            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3032            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3033                .zip(new_selection_deltas)
 3034                .map(|(selection, delta)| Selection {
 3035                    id: selection.id,
 3036                    start: selection.start + delta,
 3037                    end: selection.end + delta,
 3038                    reversed: selection.reversed,
 3039                    goal: SelectionGoal::None,
 3040                })
 3041                .collect::<Vec<_>>();
 3042
 3043            let mut i = 0;
 3044            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3045                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3046                let start = map.buffer_snapshot.anchor_before(position);
 3047                let end = map.buffer_snapshot.anchor_after(position);
 3048                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3049                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3050                        Ordering::Less => i += 1,
 3051                        Ordering::Greater => break,
 3052                        Ordering::Equal => {
 3053                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3054                                Ordering::Less => i += 1,
 3055                                Ordering::Equal => break,
 3056                                Ordering::Greater => break,
 3057                            }
 3058                        }
 3059                    }
 3060                }
 3061                this.autoclose_regions.insert(
 3062                    i,
 3063                    AutocloseRegion {
 3064                        selection_id,
 3065                        range: start..end,
 3066                        pair,
 3067                    },
 3068                );
 3069            }
 3070
 3071            let had_active_inline_completion = this.has_active_inline_completion();
 3072            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3073                s.select(new_selections)
 3074            });
 3075
 3076            if !bracket_inserted {
 3077                if let Some(on_type_format_task) =
 3078                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3079                {
 3080                    on_type_format_task.detach_and_log_err(cx);
 3081                }
 3082            }
 3083
 3084            let editor_settings = EditorSettings::get_global(cx);
 3085            if bracket_inserted
 3086                && (editor_settings.auto_signature_help
 3087                    || editor_settings.show_signature_help_after_edits)
 3088            {
 3089                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3090            }
 3091
 3092            let trigger_in_words =
 3093                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3094            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3095            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3096            this.refresh_inline_completion(true, false, window, cx);
 3097        });
 3098    }
 3099
 3100    fn find_possible_emoji_shortcode_at_position(
 3101        snapshot: &MultiBufferSnapshot,
 3102        position: Point,
 3103    ) -> Option<String> {
 3104        let mut chars = Vec::new();
 3105        let mut found_colon = false;
 3106        for char in snapshot.reversed_chars_at(position).take(100) {
 3107            // Found a possible emoji shortcode in the middle of the buffer
 3108            if found_colon {
 3109                if char.is_whitespace() {
 3110                    chars.reverse();
 3111                    return Some(chars.iter().collect());
 3112                }
 3113                // If the previous character is not a whitespace, we are in the middle of a word
 3114                // and we only want to complete the shortcode if the word is made up of other emojis
 3115                let mut containing_word = String::new();
 3116                for ch in snapshot
 3117                    .reversed_chars_at(position)
 3118                    .skip(chars.len() + 1)
 3119                    .take(100)
 3120                {
 3121                    if ch.is_whitespace() {
 3122                        break;
 3123                    }
 3124                    containing_word.push(ch);
 3125                }
 3126                let containing_word = containing_word.chars().rev().collect::<String>();
 3127                if util::word_consists_of_emojis(containing_word.as_str()) {
 3128                    chars.reverse();
 3129                    return Some(chars.iter().collect());
 3130                }
 3131            }
 3132
 3133            if char.is_whitespace() || !char.is_ascii() {
 3134                return None;
 3135            }
 3136            if char == ':' {
 3137                found_colon = true;
 3138            } else {
 3139                chars.push(char);
 3140            }
 3141        }
 3142        // Found a possible emoji shortcode at the beginning of the buffer
 3143        chars.reverse();
 3144        Some(chars.iter().collect())
 3145    }
 3146
 3147    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3148        self.transact(window, cx, |this, window, cx| {
 3149            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3150                let selections = this.selections.all::<usize>(cx);
 3151                let multi_buffer = this.buffer.read(cx);
 3152                let buffer = multi_buffer.snapshot(cx);
 3153                selections
 3154                    .iter()
 3155                    .map(|selection| {
 3156                        let start_point = selection.start.to_point(&buffer);
 3157                        let mut indent =
 3158                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3159                        indent.len = cmp::min(indent.len, start_point.column);
 3160                        let start = selection.start;
 3161                        let end = selection.end;
 3162                        let selection_is_empty = start == end;
 3163                        let language_scope = buffer.language_scope_at(start);
 3164                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3165                            &language_scope
 3166                        {
 3167                            let leading_whitespace_len = buffer
 3168                                .reversed_chars_at(start)
 3169                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3170                                .map(|c| c.len_utf8())
 3171                                .sum::<usize>();
 3172
 3173                            let trailing_whitespace_len = buffer
 3174                                .chars_at(end)
 3175                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3176                                .map(|c| c.len_utf8())
 3177                                .sum::<usize>();
 3178
 3179                            let insert_extra_newline =
 3180                                language.brackets().any(|(pair, enabled)| {
 3181                                    let pair_start = pair.start.trim_end();
 3182                                    let pair_end = pair.end.trim_start();
 3183
 3184                                    enabled
 3185                                        && pair.newline
 3186                                        && buffer.contains_str_at(
 3187                                            end + trailing_whitespace_len,
 3188                                            pair_end,
 3189                                        )
 3190                                        && buffer.contains_str_at(
 3191                                            (start - leading_whitespace_len)
 3192                                                .saturating_sub(pair_start.len()),
 3193                                            pair_start,
 3194                                        )
 3195                                });
 3196
 3197                            // Comment extension on newline is allowed only for cursor selections
 3198                            let comment_delimiter = maybe!({
 3199                                if !selection_is_empty {
 3200                                    return None;
 3201                                }
 3202
 3203                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3204                                    return None;
 3205                                }
 3206
 3207                                let delimiters = language.line_comment_prefixes();
 3208                                let max_len_of_delimiter =
 3209                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3210                                let (snapshot, range) =
 3211                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3212
 3213                                let mut index_of_first_non_whitespace = 0;
 3214                                let comment_candidate = snapshot
 3215                                    .chars_for_range(range)
 3216                                    .skip_while(|c| {
 3217                                        let should_skip = c.is_whitespace();
 3218                                        if should_skip {
 3219                                            index_of_first_non_whitespace += 1;
 3220                                        }
 3221                                        should_skip
 3222                                    })
 3223                                    .take(max_len_of_delimiter)
 3224                                    .collect::<String>();
 3225                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3226                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3227                                })?;
 3228                                let cursor_is_placed_after_comment_marker =
 3229                                    index_of_first_non_whitespace + comment_prefix.len()
 3230                                        <= start_point.column as usize;
 3231                                if cursor_is_placed_after_comment_marker {
 3232                                    Some(comment_prefix.clone())
 3233                                } else {
 3234                                    None
 3235                                }
 3236                            });
 3237                            (comment_delimiter, insert_extra_newline)
 3238                        } else {
 3239                            (None, false)
 3240                        };
 3241
 3242                        let capacity_for_delimiter = comment_delimiter
 3243                            .as_deref()
 3244                            .map(str::len)
 3245                            .unwrap_or_default();
 3246                        let mut new_text =
 3247                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3248                        new_text.push('\n');
 3249                        new_text.extend(indent.chars());
 3250                        if let Some(delimiter) = &comment_delimiter {
 3251                            new_text.push_str(delimiter);
 3252                        }
 3253                        if insert_extra_newline {
 3254                            new_text = new_text.repeat(2);
 3255                        }
 3256
 3257                        let anchor = buffer.anchor_after(end);
 3258                        let new_selection = selection.map(|_| anchor);
 3259                        (
 3260                            (start..end, new_text),
 3261                            (insert_extra_newline, new_selection),
 3262                        )
 3263                    })
 3264                    .unzip()
 3265            };
 3266
 3267            this.edit_with_autoindent(edits, cx);
 3268            let buffer = this.buffer.read(cx).snapshot(cx);
 3269            let new_selections = selection_fixup_info
 3270                .into_iter()
 3271                .map(|(extra_newline_inserted, new_selection)| {
 3272                    let mut cursor = new_selection.end.to_point(&buffer);
 3273                    if extra_newline_inserted {
 3274                        cursor.row -= 1;
 3275                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3276                    }
 3277                    new_selection.map(|_| cursor)
 3278                })
 3279                .collect();
 3280
 3281            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3282                s.select(new_selections)
 3283            });
 3284            this.refresh_inline_completion(true, false, window, cx);
 3285        });
 3286    }
 3287
 3288    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3289        let buffer = self.buffer.read(cx);
 3290        let snapshot = buffer.snapshot(cx);
 3291
 3292        let mut edits = Vec::new();
 3293        let mut rows = Vec::new();
 3294
 3295        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3296            let cursor = selection.head();
 3297            let row = cursor.row;
 3298
 3299            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3300
 3301            let newline = "\n".to_string();
 3302            edits.push((start_of_line..start_of_line, newline));
 3303
 3304            rows.push(row + rows_inserted as u32);
 3305        }
 3306
 3307        self.transact(window, cx, |editor, window, cx| {
 3308            editor.edit(edits, cx);
 3309
 3310            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3311                let mut index = 0;
 3312                s.move_cursors_with(|map, _, _| {
 3313                    let row = rows[index];
 3314                    index += 1;
 3315
 3316                    let point = Point::new(row, 0);
 3317                    let boundary = map.next_line_boundary(point).1;
 3318                    let clipped = map.clip_point(boundary, Bias::Left);
 3319
 3320                    (clipped, SelectionGoal::None)
 3321                });
 3322            });
 3323
 3324            let mut indent_edits = Vec::new();
 3325            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3326            for row in rows {
 3327                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3328                for (row, indent) in indents {
 3329                    if indent.len == 0 {
 3330                        continue;
 3331                    }
 3332
 3333                    let text = match indent.kind {
 3334                        IndentKind::Space => " ".repeat(indent.len as usize),
 3335                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3336                    };
 3337                    let point = Point::new(row.0, 0);
 3338                    indent_edits.push((point..point, text));
 3339                }
 3340            }
 3341            editor.edit(indent_edits, cx);
 3342        });
 3343    }
 3344
 3345    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3346        let buffer = self.buffer.read(cx);
 3347        let snapshot = buffer.snapshot(cx);
 3348
 3349        let mut edits = Vec::new();
 3350        let mut rows = Vec::new();
 3351        let mut rows_inserted = 0;
 3352
 3353        for selection in self.selections.all_adjusted(cx) {
 3354            let cursor = selection.head();
 3355            let row = cursor.row;
 3356
 3357            let point = Point::new(row + 1, 0);
 3358            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3359
 3360            let newline = "\n".to_string();
 3361            edits.push((start_of_line..start_of_line, newline));
 3362
 3363            rows_inserted += 1;
 3364            rows.push(row + rows_inserted);
 3365        }
 3366
 3367        self.transact(window, cx, |editor, window, cx| {
 3368            editor.edit(edits, cx);
 3369
 3370            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3371                let mut index = 0;
 3372                s.move_cursors_with(|map, _, _| {
 3373                    let row = rows[index];
 3374                    index += 1;
 3375
 3376                    let point = Point::new(row, 0);
 3377                    let boundary = map.next_line_boundary(point).1;
 3378                    let clipped = map.clip_point(boundary, Bias::Left);
 3379
 3380                    (clipped, SelectionGoal::None)
 3381                });
 3382            });
 3383
 3384            let mut indent_edits = Vec::new();
 3385            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3386            for row in rows {
 3387                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3388                for (row, indent) in indents {
 3389                    if indent.len == 0 {
 3390                        continue;
 3391                    }
 3392
 3393                    let text = match indent.kind {
 3394                        IndentKind::Space => " ".repeat(indent.len as usize),
 3395                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3396                    };
 3397                    let point = Point::new(row.0, 0);
 3398                    indent_edits.push((point..point, text));
 3399                }
 3400            }
 3401            editor.edit(indent_edits, cx);
 3402        });
 3403    }
 3404
 3405    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3406        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3407            original_indent_columns: Vec::new(),
 3408        });
 3409        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3410    }
 3411
 3412    fn insert_with_autoindent_mode(
 3413        &mut self,
 3414        text: &str,
 3415        autoindent_mode: Option<AutoindentMode>,
 3416        window: &mut Window,
 3417        cx: &mut Context<Self>,
 3418    ) {
 3419        if self.read_only(cx) {
 3420            return;
 3421        }
 3422
 3423        let text: Arc<str> = text.into();
 3424        self.transact(window, cx, |this, window, cx| {
 3425            let old_selections = this.selections.all_adjusted(cx);
 3426            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3427                let anchors = {
 3428                    let snapshot = buffer.read(cx);
 3429                    old_selections
 3430                        .iter()
 3431                        .map(|s| {
 3432                            let anchor = snapshot.anchor_after(s.head());
 3433                            s.map(|_| anchor)
 3434                        })
 3435                        .collect::<Vec<_>>()
 3436                };
 3437                buffer.edit(
 3438                    old_selections
 3439                        .iter()
 3440                        .map(|s| (s.start..s.end, text.clone())),
 3441                    autoindent_mode,
 3442                    cx,
 3443                );
 3444                anchors
 3445            });
 3446
 3447            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3448                s.select_anchors(selection_anchors);
 3449            });
 3450
 3451            cx.notify();
 3452        });
 3453    }
 3454
 3455    fn trigger_completion_on_input(
 3456        &mut self,
 3457        text: &str,
 3458        trigger_in_words: bool,
 3459        window: &mut Window,
 3460        cx: &mut Context<Self>,
 3461    ) {
 3462        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3463            self.show_completions(
 3464                &ShowCompletions {
 3465                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3466                },
 3467                window,
 3468                cx,
 3469            );
 3470        } else {
 3471            self.hide_context_menu(window, cx);
 3472        }
 3473    }
 3474
 3475    fn is_completion_trigger(
 3476        &self,
 3477        text: &str,
 3478        trigger_in_words: bool,
 3479        cx: &mut Context<Self>,
 3480    ) -> bool {
 3481        let position = self.selections.newest_anchor().head();
 3482        let multibuffer = self.buffer.read(cx);
 3483        let Some(buffer) = position
 3484            .buffer_id
 3485            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3486        else {
 3487            return false;
 3488        };
 3489
 3490        if let Some(completion_provider) = &self.completion_provider {
 3491            completion_provider.is_completion_trigger(
 3492                &buffer,
 3493                position.text_anchor,
 3494                text,
 3495                trigger_in_words,
 3496                cx,
 3497            )
 3498        } else {
 3499            false
 3500        }
 3501    }
 3502
 3503    /// If any empty selections is touching the start of its innermost containing autoclose
 3504    /// region, expand it to select the brackets.
 3505    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3506        let selections = self.selections.all::<usize>(cx);
 3507        let buffer = self.buffer.read(cx).read(cx);
 3508        let new_selections = self
 3509            .selections_with_autoclose_regions(selections, &buffer)
 3510            .map(|(mut selection, region)| {
 3511                if !selection.is_empty() {
 3512                    return selection;
 3513                }
 3514
 3515                if let Some(region) = region {
 3516                    let mut range = region.range.to_offset(&buffer);
 3517                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3518                        range.start -= region.pair.start.len();
 3519                        if buffer.contains_str_at(range.start, &region.pair.start)
 3520                            && buffer.contains_str_at(range.end, &region.pair.end)
 3521                        {
 3522                            range.end += region.pair.end.len();
 3523                            selection.start = range.start;
 3524                            selection.end = range.end;
 3525
 3526                            return selection;
 3527                        }
 3528                    }
 3529                }
 3530
 3531                let always_treat_brackets_as_autoclosed = buffer
 3532                    .settings_at(selection.start, cx)
 3533                    .always_treat_brackets_as_autoclosed;
 3534
 3535                if !always_treat_brackets_as_autoclosed {
 3536                    return selection;
 3537                }
 3538
 3539                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3540                    for (pair, enabled) in scope.brackets() {
 3541                        if !enabled || !pair.close {
 3542                            continue;
 3543                        }
 3544
 3545                        if buffer.contains_str_at(selection.start, &pair.end) {
 3546                            let pair_start_len = pair.start.len();
 3547                            if buffer.contains_str_at(
 3548                                selection.start.saturating_sub(pair_start_len),
 3549                                &pair.start,
 3550                            ) {
 3551                                selection.start -= pair_start_len;
 3552                                selection.end += pair.end.len();
 3553
 3554                                return selection;
 3555                            }
 3556                        }
 3557                    }
 3558                }
 3559
 3560                selection
 3561            })
 3562            .collect();
 3563
 3564        drop(buffer);
 3565        self.change_selections(None, window, cx, |selections| {
 3566            selections.select(new_selections)
 3567        });
 3568    }
 3569
 3570    /// Iterate the given selections, and for each one, find the smallest surrounding
 3571    /// autoclose region. This uses the ordering of the selections and the autoclose
 3572    /// regions to avoid repeated comparisons.
 3573    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3574        &'a self,
 3575        selections: impl IntoIterator<Item = Selection<D>>,
 3576        buffer: &'a MultiBufferSnapshot,
 3577    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3578        let mut i = 0;
 3579        let mut regions = self.autoclose_regions.as_slice();
 3580        selections.into_iter().map(move |selection| {
 3581            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3582
 3583            let mut enclosing = None;
 3584            while let Some(pair_state) = regions.get(i) {
 3585                if pair_state.range.end.to_offset(buffer) < range.start {
 3586                    regions = &regions[i + 1..];
 3587                    i = 0;
 3588                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3589                    break;
 3590                } else {
 3591                    if pair_state.selection_id == selection.id {
 3592                        enclosing = Some(pair_state);
 3593                    }
 3594                    i += 1;
 3595                }
 3596            }
 3597
 3598            (selection, enclosing)
 3599        })
 3600    }
 3601
 3602    /// Remove any autoclose regions that no longer contain their selection.
 3603    fn invalidate_autoclose_regions(
 3604        &mut self,
 3605        mut selections: &[Selection<Anchor>],
 3606        buffer: &MultiBufferSnapshot,
 3607    ) {
 3608        self.autoclose_regions.retain(|state| {
 3609            let mut i = 0;
 3610            while let Some(selection) = selections.get(i) {
 3611                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3612                    selections = &selections[1..];
 3613                    continue;
 3614                }
 3615                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3616                    break;
 3617                }
 3618                if selection.id == state.selection_id {
 3619                    return true;
 3620                } else {
 3621                    i += 1;
 3622                }
 3623            }
 3624            false
 3625        });
 3626    }
 3627
 3628    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3629        let offset = position.to_offset(buffer);
 3630        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3631        if offset > word_range.start && kind == Some(CharKind::Word) {
 3632            Some(
 3633                buffer
 3634                    .text_for_range(word_range.start..offset)
 3635                    .collect::<String>(),
 3636            )
 3637        } else {
 3638            None
 3639        }
 3640    }
 3641
 3642    pub fn toggle_inlay_hints(
 3643        &mut self,
 3644        _: &ToggleInlayHints,
 3645        _: &mut Window,
 3646        cx: &mut Context<Self>,
 3647    ) {
 3648        self.refresh_inlay_hints(
 3649            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3650            cx,
 3651        );
 3652    }
 3653
 3654    pub fn inlay_hints_enabled(&self) -> bool {
 3655        self.inlay_hint_cache.enabled
 3656    }
 3657
 3658    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3659        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3660            return;
 3661        }
 3662
 3663        let reason_description = reason.description();
 3664        let ignore_debounce = matches!(
 3665            reason,
 3666            InlayHintRefreshReason::SettingsChange(_)
 3667                | InlayHintRefreshReason::Toggle(_)
 3668                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3669        );
 3670        let (invalidate_cache, required_languages) = match reason {
 3671            InlayHintRefreshReason::Toggle(enabled) => {
 3672                self.inlay_hint_cache.enabled = enabled;
 3673                if enabled {
 3674                    (InvalidationStrategy::RefreshRequested, None)
 3675                } else {
 3676                    self.inlay_hint_cache.clear();
 3677                    self.splice_inlays(
 3678                        &self
 3679                            .visible_inlay_hints(cx)
 3680                            .iter()
 3681                            .map(|inlay| inlay.id)
 3682                            .collect::<Vec<InlayId>>(),
 3683                        Vec::new(),
 3684                        cx,
 3685                    );
 3686                    return;
 3687                }
 3688            }
 3689            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3690                match self.inlay_hint_cache.update_settings(
 3691                    &self.buffer,
 3692                    new_settings,
 3693                    self.visible_inlay_hints(cx),
 3694                    cx,
 3695                ) {
 3696                    ControlFlow::Break(Some(InlaySplice {
 3697                        to_remove,
 3698                        to_insert,
 3699                    })) => {
 3700                        self.splice_inlays(&to_remove, to_insert, cx);
 3701                        return;
 3702                    }
 3703                    ControlFlow::Break(None) => return,
 3704                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3705                }
 3706            }
 3707            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3708                if let Some(InlaySplice {
 3709                    to_remove,
 3710                    to_insert,
 3711                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3712                {
 3713                    self.splice_inlays(&to_remove, to_insert, cx);
 3714                }
 3715                return;
 3716            }
 3717            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3718            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3719                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3720            }
 3721            InlayHintRefreshReason::RefreshRequested => {
 3722                (InvalidationStrategy::RefreshRequested, None)
 3723            }
 3724        };
 3725
 3726        if let Some(InlaySplice {
 3727            to_remove,
 3728            to_insert,
 3729        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3730            reason_description,
 3731            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3732            invalidate_cache,
 3733            ignore_debounce,
 3734            cx,
 3735        ) {
 3736            self.splice_inlays(&to_remove, to_insert, cx);
 3737        }
 3738    }
 3739
 3740    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3741        self.display_map
 3742            .read(cx)
 3743            .current_inlays()
 3744            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3745            .cloned()
 3746            .collect()
 3747    }
 3748
 3749    pub fn excerpts_for_inlay_hints_query(
 3750        &self,
 3751        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3752        cx: &mut Context<Editor>,
 3753    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3754        let Some(project) = self.project.as_ref() else {
 3755            return HashMap::default();
 3756        };
 3757        let project = project.read(cx);
 3758        let multi_buffer = self.buffer().read(cx);
 3759        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3760        let multi_buffer_visible_start = self
 3761            .scroll_manager
 3762            .anchor()
 3763            .anchor
 3764            .to_point(&multi_buffer_snapshot);
 3765        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3766            multi_buffer_visible_start
 3767                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3768            Bias::Left,
 3769        );
 3770        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3771        multi_buffer_snapshot
 3772            .range_to_buffer_ranges(multi_buffer_visible_range)
 3773            .into_iter()
 3774            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3775            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3776                let buffer_file = project::File::from_dyn(buffer.file())?;
 3777                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3778                let worktree_entry = buffer_worktree
 3779                    .read(cx)
 3780                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3781                if worktree_entry.is_ignored {
 3782                    return None;
 3783                }
 3784
 3785                let language = buffer.language()?;
 3786                if let Some(restrict_to_languages) = restrict_to_languages {
 3787                    if !restrict_to_languages.contains(language) {
 3788                        return None;
 3789                    }
 3790                }
 3791                Some((
 3792                    excerpt_id,
 3793                    (
 3794                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3795                        buffer.version().clone(),
 3796                        excerpt_visible_range,
 3797                    ),
 3798                ))
 3799            })
 3800            .collect()
 3801    }
 3802
 3803    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3804        TextLayoutDetails {
 3805            text_system: window.text_system().clone(),
 3806            editor_style: self.style.clone().unwrap(),
 3807            rem_size: window.rem_size(),
 3808            scroll_anchor: self.scroll_manager.anchor(),
 3809            visible_rows: self.visible_line_count(),
 3810            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3811        }
 3812    }
 3813
 3814    pub fn splice_inlays(
 3815        &self,
 3816        to_remove: &[InlayId],
 3817        to_insert: Vec<Inlay>,
 3818        cx: &mut Context<Self>,
 3819    ) {
 3820        self.display_map.update(cx, |display_map, cx| {
 3821            display_map.splice_inlays(to_remove, to_insert, cx)
 3822        });
 3823        cx.notify();
 3824    }
 3825
 3826    fn trigger_on_type_formatting(
 3827        &self,
 3828        input: String,
 3829        window: &mut Window,
 3830        cx: &mut Context<Self>,
 3831    ) -> Option<Task<Result<()>>> {
 3832        if input.len() != 1 {
 3833            return None;
 3834        }
 3835
 3836        let project = self.project.as_ref()?;
 3837        let position = self.selections.newest_anchor().head();
 3838        let (buffer, buffer_position) = self
 3839            .buffer
 3840            .read(cx)
 3841            .text_anchor_for_position(position, cx)?;
 3842
 3843        let settings = language_settings::language_settings(
 3844            buffer
 3845                .read(cx)
 3846                .language_at(buffer_position)
 3847                .map(|l| l.name()),
 3848            buffer.read(cx).file(),
 3849            cx,
 3850        );
 3851        if !settings.use_on_type_format {
 3852            return None;
 3853        }
 3854
 3855        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3856        // hence we do LSP request & edit on host side only — add formats to host's history.
 3857        let push_to_lsp_host_history = true;
 3858        // If this is not the host, append its history with new edits.
 3859        let push_to_client_history = project.read(cx).is_via_collab();
 3860
 3861        let on_type_formatting = project.update(cx, |project, cx| {
 3862            project.on_type_format(
 3863                buffer.clone(),
 3864                buffer_position,
 3865                input,
 3866                push_to_lsp_host_history,
 3867                cx,
 3868            )
 3869        });
 3870        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3871            if let Some(transaction) = on_type_formatting.await? {
 3872                if push_to_client_history {
 3873                    buffer
 3874                        .update(&mut cx, |buffer, _| {
 3875                            buffer.push_transaction(transaction, Instant::now());
 3876                        })
 3877                        .ok();
 3878                }
 3879                editor.update(&mut cx, |editor, cx| {
 3880                    editor.refresh_document_highlights(cx);
 3881                })?;
 3882            }
 3883            Ok(())
 3884        }))
 3885    }
 3886
 3887    pub fn show_completions(
 3888        &mut self,
 3889        options: &ShowCompletions,
 3890        window: &mut Window,
 3891        cx: &mut Context<Self>,
 3892    ) {
 3893        if self.pending_rename.is_some() {
 3894            return;
 3895        }
 3896
 3897        let Some(provider) = self.completion_provider.as_ref() else {
 3898            return;
 3899        };
 3900
 3901        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3902            return;
 3903        }
 3904
 3905        let position = self.selections.newest_anchor().head();
 3906        if position.diff_base_anchor.is_some() {
 3907            return;
 3908        }
 3909        let (buffer, buffer_position) =
 3910            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3911                output
 3912            } else {
 3913                return;
 3914            };
 3915        let show_completion_documentation = buffer
 3916            .read(cx)
 3917            .snapshot()
 3918            .settings_at(buffer_position, cx)
 3919            .show_completion_documentation;
 3920
 3921        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3922
 3923        let trigger_kind = match &options.trigger {
 3924            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3925                CompletionTriggerKind::TRIGGER_CHARACTER
 3926            }
 3927            _ => CompletionTriggerKind::INVOKED,
 3928        };
 3929        let completion_context = CompletionContext {
 3930            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3931                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3932                    Some(String::from(trigger))
 3933                } else {
 3934                    None
 3935                }
 3936            }),
 3937            trigger_kind,
 3938        };
 3939        let completions =
 3940            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3941        let sort_completions = provider.sort_completions();
 3942
 3943        let id = post_inc(&mut self.next_completion_id);
 3944        let task = cx.spawn_in(window, |editor, mut cx| {
 3945            async move {
 3946                editor.update(&mut cx, |this, _| {
 3947                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3948                })?;
 3949                let completions = completions.await.log_err();
 3950                let menu = if let Some(completions) = completions {
 3951                    let mut menu = CompletionsMenu::new(
 3952                        id,
 3953                        sort_completions,
 3954                        show_completion_documentation,
 3955                        position,
 3956                        buffer.clone(),
 3957                        completions.into(),
 3958                    );
 3959
 3960                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3961                        .await;
 3962
 3963                    menu.visible().then_some(menu)
 3964                } else {
 3965                    None
 3966                };
 3967
 3968                editor.update_in(&mut cx, |editor, window, cx| {
 3969                    match editor.context_menu.borrow().as_ref() {
 3970                        None => {}
 3971                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3972                            if prev_menu.id > id {
 3973                                return;
 3974                            }
 3975                        }
 3976                        _ => return,
 3977                    }
 3978
 3979                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3980                        let mut menu = menu.unwrap();
 3981                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3982
 3983                        *editor.context_menu.borrow_mut() =
 3984                            Some(CodeContextMenu::Completions(menu));
 3985
 3986                        if editor.show_edit_predictions_in_menu() {
 3987                            editor.update_visible_inline_completion(window, cx);
 3988                        } else {
 3989                            editor.discard_inline_completion(false, cx);
 3990                        }
 3991
 3992                        cx.notify();
 3993                    } else if editor.completion_tasks.len() <= 1 {
 3994                        // If there are no more completion tasks and the last menu was
 3995                        // empty, we should hide it.
 3996                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3997                        // If it was already hidden and we don't show inline
 3998                        // completions in the menu, we should also show the
 3999                        // inline-completion when available.
 4000                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4001                            editor.update_visible_inline_completion(window, cx);
 4002                        }
 4003                    }
 4004                })?;
 4005
 4006                Ok::<_, anyhow::Error>(())
 4007            }
 4008            .log_err()
 4009        });
 4010
 4011        self.completion_tasks.push((id, task));
 4012    }
 4013
 4014    pub fn confirm_completion(
 4015        &mut self,
 4016        action: &ConfirmCompletion,
 4017        window: &mut Window,
 4018        cx: &mut Context<Self>,
 4019    ) -> Option<Task<Result<()>>> {
 4020        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4021    }
 4022
 4023    pub fn compose_completion(
 4024        &mut self,
 4025        action: &ComposeCompletion,
 4026        window: &mut Window,
 4027        cx: &mut Context<Self>,
 4028    ) -> Option<Task<Result<()>>> {
 4029        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4030    }
 4031
 4032    fn do_completion(
 4033        &mut self,
 4034        item_ix: Option<usize>,
 4035        intent: CompletionIntent,
 4036        window: &mut Window,
 4037        cx: &mut Context<Editor>,
 4038    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4039        use language::ToOffset as _;
 4040
 4041        let completions_menu =
 4042            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4043                menu
 4044            } else {
 4045                return None;
 4046            };
 4047
 4048        let entries = completions_menu.entries.borrow();
 4049        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4050        if self.show_edit_predictions_in_menu() {
 4051            self.discard_inline_completion(true, cx);
 4052        }
 4053        let candidate_id = mat.candidate_id;
 4054        drop(entries);
 4055
 4056        let buffer_handle = completions_menu.buffer;
 4057        let completion = completions_menu
 4058            .completions
 4059            .borrow()
 4060            .get(candidate_id)?
 4061            .clone();
 4062        cx.stop_propagation();
 4063
 4064        let snippet;
 4065        let text;
 4066
 4067        if completion.is_snippet() {
 4068            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4069            text = snippet.as_ref().unwrap().text.clone();
 4070        } else {
 4071            snippet = None;
 4072            text = completion.new_text.clone();
 4073        };
 4074        let selections = self.selections.all::<usize>(cx);
 4075        let buffer = buffer_handle.read(cx);
 4076        let old_range = completion.old_range.to_offset(buffer);
 4077        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4078
 4079        let newest_selection = self.selections.newest_anchor();
 4080        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4081            return None;
 4082        }
 4083
 4084        let lookbehind = newest_selection
 4085            .start
 4086            .text_anchor
 4087            .to_offset(buffer)
 4088            .saturating_sub(old_range.start);
 4089        let lookahead = old_range
 4090            .end
 4091            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4092        let mut common_prefix_len = old_text
 4093            .bytes()
 4094            .zip(text.bytes())
 4095            .take_while(|(a, b)| a == b)
 4096            .count();
 4097
 4098        let snapshot = self.buffer.read(cx).snapshot(cx);
 4099        let mut range_to_replace: Option<Range<isize>> = None;
 4100        let mut ranges = Vec::new();
 4101        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4102        for selection in &selections {
 4103            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4104                let start = selection.start.saturating_sub(lookbehind);
 4105                let end = selection.end + lookahead;
 4106                if selection.id == newest_selection.id {
 4107                    range_to_replace = Some(
 4108                        ((start + common_prefix_len) as isize - selection.start as isize)
 4109                            ..(end as isize - selection.start as isize),
 4110                    );
 4111                }
 4112                ranges.push(start + common_prefix_len..end);
 4113            } else {
 4114                common_prefix_len = 0;
 4115                ranges.clear();
 4116                ranges.extend(selections.iter().map(|s| {
 4117                    if s.id == newest_selection.id {
 4118                        range_to_replace = Some(
 4119                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4120                                - selection.start as isize
 4121                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4122                                    - selection.start as isize,
 4123                        );
 4124                        old_range.clone()
 4125                    } else {
 4126                        s.start..s.end
 4127                    }
 4128                }));
 4129                break;
 4130            }
 4131            if !self.linked_edit_ranges.is_empty() {
 4132                let start_anchor = snapshot.anchor_before(selection.head());
 4133                let end_anchor = snapshot.anchor_after(selection.tail());
 4134                if let Some(ranges) = self
 4135                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4136                {
 4137                    for (buffer, edits) in ranges {
 4138                        linked_edits.entry(buffer.clone()).or_default().extend(
 4139                            edits
 4140                                .into_iter()
 4141                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4142                        );
 4143                    }
 4144                }
 4145            }
 4146        }
 4147        let text = &text[common_prefix_len..];
 4148
 4149        cx.emit(EditorEvent::InputHandled {
 4150            utf16_range_to_replace: range_to_replace,
 4151            text: text.into(),
 4152        });
 4153
 4154        self.transact(window, cx, |this, window, cx| {
 4155            if let Some(mut snippet) = snippet {
 4156                snippet.text = text.to_string();
 4157                for tabstop in snippet
 4158                    .tabstops
 4159                    .iter_mut()
 4160                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4161                {
 4162                    tabstop.start -= common_prefix_len as isize;
 4163                    tabstop.end -= common_prefix_len as isize;
 4164                }
 4165
 4166                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4167            } else {
 4168                this.buffer.update(cx, |buffer, cx| {
 4169                    buffer.edit(
 4170                        ranges.iter().map(|range| (range.clone(), text)),
 4171                        this.autoindent_mode.clone(),
 4172                        cx,
 4173                    );
 4174                });
 4175            }
 4176            for (buffer, edits) in linked_edits {
 4177                buffer.update(cx, |buffer, cx| {
 4178                    let snapshot = buffer.snapshot();
 4179                    let edits = edits
 4180                        .into_iter()
 4181                        .map(|(range, text)| {
 4182                            use text::ToPoint as TP;
 4183                            let end_point = TP::to_point(&range.end, &snapshot);
 4184                            let start_point = TP::to_point(&range.start, &snapshot);
 4185                            (start_point..end_point, text)
 4186                        })
 4187                        .sorted_by_key(|(range, _)| range.start)
 4188                        .collect::<Vec<_>>();
 4189                    buffer.edit(edits, None, cx);
 4190                })
 4191            }
 4192
 4193            this.refresh_inline_completion(true, false, window, cx);
 4194        });
 4195
 4196        let show_new_completions_on_confirm = completion
 4197            .confirm
 4198            .as_ref()
 4199            .map_or(false, |confirm| confirm(intent, window, cx));
 4200        if show_new_completions_on_confirm {
 4201            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4202        }
 4203
 4204        let provider = self.completion_provider.as_ref()?;
 4205        drop(completion);
 4206        let apply_edits = provider.apply_additional_edits_for_completion(
 4207            buffer_handle,
 4208            completions_menu.completions.clone(),
 4209            candidate_id,
 4210            true,
 4211            cx,
 4212        );
 4213
 4214        let editor_settings = EditorSettings::get_global(cx);
 4215        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4216            // After the code completion is finished, users often want to know what signatures are needed.
 4217            // so we should automatically call signature_help
 4218            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4219        }
 4220
 4221        Some(cx.foreground_executor().spawn(async move {
 4222            apply_edits.await?;
 4223            Ok(())
 4224        }))
 4225    }
 4226
 4227    pub fn toggle_code_actions(
 4228        &mut self,
 4229        action: &ToggleCodeActions,
 4230        window: &mut Window,
 4231        cx: &mut Context<Self>,
 4232    ) {
 4233        let mut context_menu = self.context_menu.borrow_mut();
 4234        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4235            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4236                // Toggle if we're selecting the same one
 4237                *context_menu = None;
 4238                cx.notify();
 4239                return;
 4240            } else {
 4241                // Otherwise, clear it and start a new one
 4242                *context_menu = None;
 4243                cx.notify();
 4244            }
 4245        }
 4246        drop(context_menu);
 4247        let snapshot = self.snapshot(window, cx);
 4248        let deployed_from_indicator = action.deployed_from_indicator;
 4249        let mut task = self.code_actions_task.take();
 4250        let action = action.clone();
 4251        cx.spawn_in(window, |editor, mut cx| async move {
 4252            while let Some(prev_task) = task {
 4253                prev_task.await.log_err();
 4254                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4255            }
 4256
 4257            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4258                if editor.focus_handle.is_focused(window) {
 4259                    let multibuffer_point = action
 4260                        .deployed_from_indicator
 4261                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4262                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4263                    let (buffer, buffer_row) = snapshot
 4264                        .buffer_snapshot
 4265                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4266                        .and_then(|(buffer_snapshot, range)| {
 4267                            editor
 4268                                .buffer
 4269                                .read(cx)
 4270                                .buffer(buffer_snapshot.remote_id())
 4271                                .map(|buffer| (buffer, range.start.row))
 4272                        })?;
 4273                    let (_, code_actions) = editor
 4274                        .available_code_actions
 4275                        .clone()
 4276                        .and_then(|(location, code_actions)| {
 4277                            let snapshot = location.buffer.read(cx).snapshot();
 4278                            let point_range = location.range.to_point(&snapshot);
 4279                            let point_range = point_range.start.row..=point_range.end.row;
 4280                            if point_range.contains(&buffer_row) {
 4281                                Some((location, code_actions))
 4282                            } else {
 4283                                None
 4284                            }
 4285                        })
 4286                        .unzip();
 4287                    let buffer_id = buffer.read(cx).remote_id();
 4288                    let tasks = editor
 4289                        .tasks
 4290                        .get(&(buffer_id, buffer_row))
 4291                        .map(|t| Arc::new(t.to_owned()));
 4292                    if tasks.is_none() && code_actions.is_none() {
 4293                        return None;
 4294                    }
 4295
 4296                    editor.completion_tasks.clear();
 4297                    editor.discard_inline_completion(false, cx);
 4298                    let task_context =
 4299                        tasks
 4300                            .as_ref()
 4301                            .zip(editor.project.clone())
 4302                            .map(|(tasks, project)| {
 4303                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4304                            });
 4305
 4306                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4307                        let task_context = match task_context {
 4308                            Some(task_context) => task_context.await,
 4309                            None => None,
 4310                        };
 4311                        let resolved_tasks =
 4312                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4313                                Rc::new(ResolvedTasks {
 4314                                    templates: tasks.resolve(&task_context).collect(),
 4315                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4316                                        multibuffer_point.row,
 4317                                        tasks.column,
 4318                                    )),
 4319                                })
 4320                            });
 4321                        let spawn_straight_away = resolved_tasks
 4322                            .as_ref()
 4323                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4324                            && code_actions
 4325                                .as_ref()
 4326                                .map_or(true, |actions| actions.is_empty());
 4327                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4328                            *editor.context_menu.borrow_mut() =
 4329                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4330                                    buffer,
 4331                                    actions: CodeActionContents {
 4332                                        tasks: resolved_tasks,
 4333                                        actions: code_actions,
 4334                                    },
 4335                                    selected_item: Default::default(),
 4336                                    scroll_handle: UniformListScrollHandle::default(),
 4337                                    deployed_from_indicator,
 4338                                }));
 4339                            if spawn_straight_away {
 4340                                if let Some(task) = editor.confirm_code_action(
 4341                                    &ConfirmCodeAction { item_ix: Some(0) },
 4342                                    window,
 4343                                    cx,
 4344                                ) {
 4345                                    cx.notify();
 4346                                    return task;
 4347                                }
 4348                            }
 4349                            cx.notify();
 4350                            Task::ready(Ok(()))
 4351                        }) {
 4352                            task.await
 4353                        } else {
 4354                            Ok(())
 4355                        }
 4356                    }))
 4357                } else {
 4358                    Some(Task::ready(Ok(())))
 4359                }
 4360            })?;
 4361            if let Some(task) = spawned_test_task {
 4362                task.await?;
 4363            }
 4364
 4365            Ok::<_, anyhow::Error>(())
 4366        })
 4367        .detach_and_log_err(cx);
 4368    }
 4369
 4370    pub fn confirm_code_action(
 4371        &mut self,
 4372        action: &ConfirmCodeAction,
 4373        window: &mut Window,
 4374        cx: &mut Context<Self>,
 4375    ) -> Option<Task<Result<()>>> {
 4376        let actions_menu =
 4377            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4378                menu
 4379            } else {
 4380                return None;
 4381            };
 4382        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4383        let action = actions_menu.actions.get(action_ix)?;
 4384        let title = action.label();
 4385        let buffer = actions_menu.buffer;
 4386        let workspace = self.workspace()?;
 4387
 4388        match action {
 4389            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4390                workspace.update(cx, |workspace, cx| {
 4391                    workspace::tasks::schedule_resolved_task(
 4392                        workspace,
 4393                        task_source_kind,
 4394                        resolved_task,
 4395                        false,
 4396                        cx,
 4397                    );
 4398
 4399                    Some(Task::ready(Ok(())))
 4400                })
 4401            }
 4402            CodeActionsItem::CodeAction {
 4403                excerpt_id,
 4404                action,
 4405                provider,
 4406            } => {
 4407                let apply_code_action =
 4408                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4409                let workspace = workspace.downgrade();
 4410                Some(cx.spawn_in(window, |editor, cx| async move {
 4411                    let project_transaction = apply_code_action.await?;
 4412                    Self::open_project_transaction(
 4413                        &editor,
 4414                        workspace,
 4415                        project_transaction,
 4416                        title,
 4417                        cx,
 4418                    )
 4419                    .await
 4420                }))
 4421            }
 4422        }
 4423    }
 4424
 4425    pub async fn open_project_transaction(
 4426        this: &WeakEntity<Editor>,
 4427        workspace: WeakEntity<Workspace>,
 4428        transaction: ProjectTransaction,
 4429        title: String,
 4430        mut cx: AsyncWindowContext,
 4431    ) -> Result<()> {
 4432        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4433        cx.update(|_, cx| {
 4434            entries.sort_unstable_by_key(|(buffer, _)| {
 4435                buffer.read(cx).file().map(|f| f.path().clone())
 4436            });
 4437        })?;
 4438
 4439        // If the project transaction's edits are all contained within this editor, then
 4440        // avoid opening a new editor to display them.
 4441
 4442        if let Some((buffer, transaction)) = entries.first() {
 4443            if entries.len() == 1 {
 4444                let excerpt = this.update(&mut cx, |editor, cx| {
 4445                    editor
 4446                        .buffer()
 4447                        .read(cx)
 4448                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4449                })?;
 4450                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4451                    if excerpted_buffer == *buffer {
 4452                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4453                            let excerpt_range = excerpt_range.to_offset(buffer);
 4454                            buffer
 4455                                .edited_ranges_for_transaction::<usize>(transaction)
 4456                                .all(|range| {
 4457                                    excerpt_range.start <= range.start
 4458                                        && excerpt_range.end >= range.end
 4459                                })
 4460                        })?;
 4461
 4462                        if all_edits_within_excerpt {
 4463                            return Ok(());
 4464                        }
 4465                    }
 4466                }
 4467            }
 4468        } else {
 4469            return Ok(());
 4470        }
 4471
 4472        let mut ranges_to_highlight = Vec::new();
 4473        let excerpt_buffer = cx.new(|cx| {
 4474            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4475            for (buffer_handle, transaction) in &entries {
 4476                let buffer = buffer_handle.read(cx);
 4477                ranges_to_highlight.extend(
 4478                    multibuffer.push_excerpts_with_context_lines(
 4479                        buffer_handle.clone(),
 4480                        buffer
 4481                            .edited_ranges_for_transaction::<usize>(transaction)
 4482                            .collect(),
 4483                        DEFAULT_MULTIBUFFER_CONTEXT,
 4484                        cx,
 4485                    ),
 4486                );
 4487            }
 4488            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4489            multibuffer
 4490        })?;
 4491
 4492        workspace.update_in(&mut cx, |workspace, window, cx| {
 4493            let project = workspace.project().clone();
 4494            let editor = cx
 4495                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4496            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4497            editor.update(cx, |editor, cx| {
 4498                editor.highlight_background::<Self>(
 4499                    &ranges_to_highlight,
 4500                    |theme| theme.editor_highlighted_line_background,
 4501                    cx,
 4502                );
 4503            });
 4504        })?;
 4505
 4506        Ok(())
 4507    }
 4508
 4509    pub fn clear_code_action_providers(&mut self) {
 4510        self.code_action_providers.clear();
 4511        self.available_code_actions.take();
 4512    }
 4513
 4514    pub fn add_code_action_provider(
 4515        &mut self,
 4516        provider: Rc<dyn CodeActionProvider>,
 4517        window: &mut Window,
 4518        cx: &mut Context<Self>,
 4519    ) {
 4520        if self
 4521            .code_action_providers
 4522            .iter()
 4523            .any(|existing_provider| existing_provider.id() == provider.id())
 4524        {
 4525            return;
 4526        }
 4527
 4528        self.code_action_providers.push(provider);
 4529        self.refresh_code_actions(window, cx);
 4530    }
 4531
 4532    pub fn remove_code_action_provider(
 4533        &mut self,
 4534        id: Arc<str>,
 4535        window: &mut Window,
 4536        cx: &mut Context<Self>,
 4537    ) {
 4538        self.code_action_providers
 4539            .retain(|provider| provider.id() != id);
 4540        self.refresh_code_actions(window, cx);
 4541    }
 4542
 4543    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4544        let buffer = self.buffer.read(cx);
 4545        let newest_selection = self.selections.newest_anchor().clone();
 4546        if newest_selection.head().diff_base_anchor.is_some() {
 4547            return None;
 4548        }
 4549        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4550        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4551        if start_buffer != end_buffer {
 4552            return None;
 4553        }
 4554
 4555        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4556            cx.background_executor()
 4557                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4558                .await;
 4559
 4560            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4561                let providers = this.code_action_providers.clone();
 4562                let tasks = this
 4563                    .code_action_providers
 4564                    .iter()
 4565                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4566                    .collect::<Vec<_>>();
 4567                (providers, tasks)
 4568            })?;
 4569
 4570            let mut actions = Vec::new();
 4571            for (provider, provider_actions) in
 4572                providers.into_iter().zip(future::join_all(tasks).await)
 4573            {
 4574                if let Some(provider_actions) = provider_actions.log_err() {
 4575                    actions.extend(provider_actions.into_iter().map(|action| {
 4576                        AvailableCodeAction {
 4577                            excerpt_id: newest_selection.start.excerpt_id,
 4578                            action,
 4579                            provider: provider.clone(),
 4580                        }
 4581                    }));
 4582                }
 4583            }
 4584
 4585            this.update(&mut cx, |this, cx| {
 4586                this.available_code_actions = if actions.is_empty() {
 4587                    None
 4588                } else {
 4589                    Some((
 4590                        Location {
 4591                            buffer: start_buffer,
 4592                            range: start..end,
 4593                        },
 4594                        actions.into(),
 4595                    ))
 4596                };
 4597                cx.notify();
 4598            })
 4599        }));
 4600        None
 4601    }
 4602
 4603    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4604        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4605            self.show_git_blame_inline = false;
 4606
 4607            self.show_git_blame_inline_delay_task =
 4608                Some(cx.spawn_in(window, |this, mut cx| async move {
 4609                    cx.background_executor().timer(delay).await;
 4610
 4611                    this.update(&mut cx, |this, cx| {
 4612                        this.show_git_blame_inline = true;
 4613                        cx.notify();
 4614                    })
 4615                    .log_err();
 4616                }));
 4617        }
 4618    }
 4619
 4620    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4621        if self.pending_rename.is_some() {
 4622            return None;
 4623        }
 4624
 4625        let provider = self.semantics_provider.clone()?;
 4626        let buffer = self.buffer.read(cx);
 4627        let newest_selection = self.selections.newest_anchor().clone();
 4628        let cursor_position = newest_selection.head();
 4629        let (cursor_buffer, cursor_buffer_position) =
 4630            buffer.text_anchor_for_position(cursor_position, cx)?;
 4631        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4632        if cursor_buffer != tail_buffer {
 4633            return None;
 4634        }
 4635        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4636        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4637            cx.background_executor()
 4638                .timer(Duration::from_millis(debounce))
 4639                .await;
 4640
 4641            let highlights = if let Some(highlights) = cx
 4642                .update(|cx| {
 4643                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4644                })
 4645                .ok()
 4646                .flatten()
 4647            {
 4648                highlights.await.log_err()
 4649            } else {
 4650                None
 4651            };
 4652
 4653            if let Some(highlights) = highlights {
 4654                this.update(&mut cx, |this, cx| {
 4655                    if this.pending_rename.is_some() {
 4656                        return;
 4657                    }
 4658
 4659                    let buffer_id = cursor_position.buffer_id;
 4660                    let buffer = this.buffer.read(cx);
 4661                    if !buffer
 4662                        .text_anchor_for_position(cursor_position, cx)
 4663                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4664                    {
 4665                        return;
 4666                    }
 4667
 4668                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4669                    let mut write_ranges = Vec::new();
 4670                    let mut read_ranges = Vec::new();
 4671                    for highlight in highlights {
 4672                        for (excerpt_id, excerpt_range) in
 4673                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4674                        {
 4675                            let start = highlight
 4676                                .range
 4677                                .start
 4678                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4679                            let end = highlight
 4680                                .range
 4681                                .end
 4682                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4683                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4684                                continue;
 4685                            }
 4686
 4687                            let range = Anchor {
 4688                                buffer_id,
 4689                                excerpt_id,
 4690                                text_anchor: start,
 4691                                diff_base_anchor: None,
 4692                            }..Anchor {
 4693                                buffer_id,
 4694                                excerpt_id,
 4695                                text_anchor: end,
 4696                                diff_base_anchor: None,
 4697                            };
 4698                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4699                                write_ranges.push(range);
 4700                            } else {
 4701                                read_ranges.push(range);
 4702                            }
 4703                        }
 4704                    }
 4705
 4706                    this.highlight_background::<DocumentHighlightRead>(
 4707                        &read_ranges,
 4708                        |theme| theme.editor_document_highlight_read_background,
 4709                        cx,
 4710                    );
 4711                    this.highlight_background::<DocumentHighlightWrite>(
 4712                        &write_ranges,
 4713                        |theme| theme.editor_document_highlight_write_background,
 4714                        cx,
 4715                    );
 4716                    cx.notify();
 4717                })
 4718                .log_err();
 4719            }
 4720        }));
 4721        None
 4722    }
 4723
 4724    pub fn refresh_inline_completion(
 4725        &mut self,
 4726        debounce: bool,
 4727        user_requested: bool,
 4728        window: &mut Window,
 4729        cx: &mut Context<Self>,
 4730    ) -> Option<()> {
 4731        let provider = self.edit_prediction_provider()?;
 4732        let cursor = self.selections.newest_anchor().head();
 4733        let (buffer, cursor_buffer_position) =
 4734            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4735
 4736        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4737            self.discard_inline_completion(false, cx);
 4738            return None;
 4739        }
 4740
 4741        if !user_requested
 4742            && (!self.should_show_edit_predictions()
 4743                || !self.is_focused(window)
 4744                || buffer.read(cx).is_empty())
 4745        {
 4746            self.discard_inline_completion(false, cx);
 4747            return None;
 4748        }
 4749
 4750        self.update_visible_inline_completion(window, cx);
 4751        provider.refresh(
 4752            self.project.clone(),
 4753            buffer,
 4754            cursor_buffer_position,
 4755            debounce,
 4756            cx,
 4757        );
 4758        Some(())
 4759    }
 4760
 4761    fn show_edit_predictions_in_menu(&self) -> bool {
 4762        match self.edit_prediction_settings {
 4763            EditPredictionSettings::Disabled => false,
 4764            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4765        }
 4766    }
 4767
 4768    pub fn edit_predictions_enabled(&self) -> bool {
 4769        match self.edit_prediction_settings {
 4770            EditPredictionSettings::Disabled => false,
 4771            EditPredictionSettings::Enabled { .. } => true,
 4772        }
 4773    }
 4774
 4775    fn edit_prediction_requires_modifier(&self) -> bool {
 4776        match self.edit_prediction_settings {
 4777            EditPredictionSettings::Disabled => false,
 4778            EditPredictionSettings::Enabled {
 4779                preview_requires_modifier,
 4780                ..
 4781            } => preview_requires_modifier,
 4782        }
 4783    }
 4784
 4785    fn edit_prediction_settings_at_position(
 4786        &self,
 4787        buffer: &Entity<Buffer>,
 4788        buffer_position: language::Anchor,
 4789        cx: &App,
 4790    ) -> EditPredictionSettings {
 4791        if self.mode != EditorMode::Full
 4792            || !self.show_inline_completions_override.unwrap_or(true)
 4793            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4794        {
 4795            return EditPredictionSettings::Disabled;
 4796        }
 4797
 4798        let buffer = buffer.read(cx);
 4799
 4800        let file = buffer.file();
 4801
 4802        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4803            return EditPredictionSettings::Disabled;
 4804        };
 4805
 4806        let by_provider = matches!(
 4807            self.menu_inline_completions_policy,
 4808            MenuInlineCompletionsPolicy::ByProvider
 4809        );
 4810
 4811        let show_in_menu = by_provider
 4812            && self
 4813                .edit_prediction_provider
 4814                .as_ref()
 4815                .map_or(false, |provider| {
 4816                    provider.provider.show_completions_in_menu()
 4817                });
 4818
 4819        let preview_requires_modifier =
 4820            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4821
 4822        EditPredictionSettings::Enabled {
 4823            show_in_menu,
 4824            preview_requires_modifier,
 4825        }
 4826    }
 4827
 4828    fn should_show_edit_predictions(&self) -> bool {
 4829        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4830    }
 4831
 4832    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4833        matches!(
 4834            self.edit_prediction_preview,
 4835            EditPredictionPreview::Active { .. }
 4836        )
 4837    }
 4838
 4839    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4840        let cursor = self.selections.newest_anchor().head();
 4841        if let Some((buffer, cursor_position)) =
 4842            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4843        {
 4844            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4845        } else {
 4846            false
 4847        }
 4848    }
 4849
 4850    fn inline_completions_enabled_in_buffer(
 4851        &self,
 4852        buffer: &Entity<Buffer>,
 4853        buffer_position: language::Anchor,
 4854        cx: &App,
 4855    ) -> bool {
 4856        maybe!({
 4857            let provider = self.edit_prediction_provider()?;
 4858            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4859                return Some(false);
 4860            }
 4861            let buffer = buffer.read(cx);
 4862            let Some(file) = buffer.file() else {
 4863                return Some(true);
 4864            };
 4865            let settings = all_language_settings(Some(file), cx);
 4866            Some(settings.inline_completions_enabled_for_path(file.path()))
 4867        })
 4868        .unwrap_or(false)
 4869    }
 4870
 4871    fn cycle_inline_completion(
 4872        &mut self,
 4873        direction: Direction,
 4874        window: &mut Window,
 4875        cx: &mut Context<Self>,
 4876    ) -> Option<()> {
 4877        let provider = self.edit_prediction_provider()?;
 4878        let cursor = self.selections.newest_anchor().head();
 4879        let (buffer, cursor_buffer_position) =
 4880            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4881        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4882            return None;
 4883        }
 4884
 4885        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4886        self.update_visible_inline_completion(window, cx);
 4887
 4888        Some(())
 4889    }
 4890
 4891    pub fn show_inline_completion(
 4892        &mut self,
 4893        _: &ShowEditPrediction,
 4894        window: &mut Window,
 4895        cx: &mut Context<Self>,
 4896    ) {
 4897        if !self.has_active_inline_completion() {
 4898            self.refresh_inline_completion(false, true, window, cx);
 4899            return;
 4900        }
 4901
 4902        self.update_visible_inline_completion(window, cx);
 4903    }
 4904
 4905    pub fn display_cursor_names(
 4906        &mut self,
 4907        _: &DisplayCursorNames,
 4908        window: &mut Window,
 4909        cx: &mut Context<Self>,
 4910    ) {
 4911        self.show_cursor_names(window, cx);
 4912    }
 4913
 4914    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4915        self.show_cursor_names = true;
 4916        cx.notify();
 4917        cx.spawn_in(window, |this, mut cx| async move {
 4918            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4919            this.update(&mut cx, |this, cx| {
 4920                this.show_cursor_names = false;
 4921                cx.notify()
 4922            })
 4923            .ok()
 4924        })
 4925        .detach();
 4926    }
 4927
 4928    pub fn next_edit_prediction(
 4929        &mut self,
 4930        _: &NextEditPrediction,
 4931        window: &mut Window,
 4932        cx: &mut Context<Self>,
 4933    ) {
 4934        if self.has_active_inline_completion() {
 4935            self.cycle_inline_completion(Direction::Next, window, cx);
 4936        } else {
 4937            let is_copilot_disabled = self
 4938                .refresh_inline_completion(false, true, window, cx)
 4939                .is_none();
 4940            if is_copilot_disabled {
 4941                cx.propagate();
 4942            }
 4943        }
 4944    }
 4945
 4946    pub fn previous_edit_prediction(
 4947        &mut self,
 4948        _: &PreviousEditPrediction,
 4949        window: &mut Window,
 4950        cx: &mut Context<Self>,
 4951    ) {
 4952        if self.has_active_inline_completion() {
 4953            self.cycle_inline_completion(Direction::Prev, window, cx);
 4954        } else {
 4955            let is_copilot_disabled = self
 4956                .refresh_inline_completion(false, true, window, cx)
 4957                .is_none();
 4958            if is_copilot_disabled {
 4959                cx.propagate();
 4960            }
 4961        }
 4962    }
 4963
 4964    pub fn accept_edit_prediction(
 4965        &mut self,
 4966        _: &AcceptEditPrediction,
 4967        window: &mut Window,
 4968        cx: &mut Context<Self>,
 4969    ) {
 4970        if self.show_edit_predictions_in_menu() {
 4971            self.hide_context_menu(window, cx);
 4972        }
 4973
 4974        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4975            return;
 4976        };
 4977
 4978        self.report_inline_completion_event(
 4979            active_inline_completion.completion_id.clone(),
 4980            true,
 4981            cx,
 4982        );
 4983
 4984        match &active_inline_completion.completion {
 4985            InlineCompletion::Move { target, .. } => {
 4986                let target = *target;
 4987
 4988                if let Some(position_map) = &self.last_position_map {
 4989                    if position_map
 4990                        .visible_row_range
 4991                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4992                        || !self.edit_prediction_requires_modifier()
 4993                    {
 4994                        // Note that this is also done in vim's handler of the Tab action.
 4995                        self.change_selections(
 4996                            Some(Autoscroll::newest()),
 4997                            window,
 4998                            cx,
 4999                            |selections| {
 5000                                selections.select_anchor_ranges([target..target]);
 5001                            },
 5002                        );
 5003                        self.clear_row_highlights::<EditPredictionPreview>();
 5004
 5005                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5006                            previous_scroll_position: None,
 5007                        };
 5008                    } else {
 5009                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5010                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5011                        };
 5012                        self.highlight_rows::<EditPredictionPreview>(
 5013                            target..target,
 5014                            cx.theme().colors().editor_highlighted_line_background,
 5015                            true,
 5016                            cx,
 5017                        );
 5018                        self.request_autoscroll(Autoscroll::fit(), cx);
 5019                    }
 5020                }
 5021            }
 5022            InlineCompletion::Edit { edits, .. } => {
 5023                if let Some(provider) = self.edit_prediction_provider() {
 5024                    provider.accept(cx);
 5025                }
 5026
 5027                let snapshot = self.buffer.read(cx).snapshot(cx);
 5028                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5029
 5030                self.buffer.update(cx, |buffer, cx| {
 5031                    buffer.edit(edits.iter().cloned(), None, cx)
 5032                });
 5033
 5034                self.change_selections(None, window, cx, |s| {
 5035                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5036                });
 5037
 5038                self.update_visible_inline_completion(window, cx);
 5039                if self.active_inline_completion.is_none() {
 5040                    self.refresh_inline_completion(true, true, window, cx);
 5041                }
 5042
 5043                cx.notify();
 5044            }
 5045        }
 5046
 5047        self.edit_prediction_requires_modifier_in_leading_space = false;
 5048    }
 5049
 5050    pub fn accept_partial_inline_completion(
 5051        &mut self,
 5052        _: &AcceptPartialEditPrediction,
 5053        window: &mut Window,
 5054        cx: &mut Context<Self>,
 5055    ) {
 5056        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5057            return;
 5058        };
 5059        if self.selections.count() != 1 {
 5060            return;
 5061        }
 5062
 5063        self.report_inline_completion_event(
 5064            active_inline_completion.completion_id.clone(),
 5065            true,
 5066            cx,
 5067        );
 5068
 5069        match &active_inline_completion.completion {
 5070            InlineCompletion::Move { target, .. } => {
 5071                let target = *target;
 5072                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5073                    selections.select_anchor_ranges([target..target]);
 5074                });
 5075            }
 5076            InlineCompletion::Edit { edits, .. } => {
 5077                // Find an insertion that starts at the cursor position.
 5078                let snapshot = self.buffer.read(cx).snapshot(cx);
 5079                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5080                let insertion = edits.iter().find_map(|(range, text)| {
 5081                    let range = range.to_offset(&snapshot);
 5082                    if range.is_empty() && range.start == cursor_offset {
 5083                        Some(text)
 5084                    } else {
 5085                        None
 5086                    }
 5087                });
 5088
 5089                if let Some(text) = insertion {
 5090                    let mut partial_completion = text
 5091                        .chars()
 5092                        .by_ref()
 5093                        .take_while(|c| c.is_alphabetic())
 5094                        .collect::<String>();
 5095                    if partial_completion.is_empty() {
 5096                        partial_completion = text
 5097                            .chars()
 5098                            .by_ref()
 5099                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5100                            .collect::<String>();
 5101                    }
 5102
 5103                    cx.emit(EditorEvent::InputHandled {
 5104                        utf16_range_to_replace: None,
 5105                        text: partial_completion.clone().into(),
 5106                    });
 5107
 5108                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5109
 5110                    self.refresh_inline_completion(true, true, window, cx);
 5111                    cx.notify();
 5112                } else {
 5113                    self.accept_edit_prediction(&Default::default(), window, cx);
 5114                }
 5115            }
 5116        }
 5117    }
 5118
 5119    fn discard_inline_completion(
 5120        &mut self,
 5121        should_report_inline_completion_event: bool,
 5122        cx: &mut Context<Self>,
 5123    ) -> bool {
 5124        if should_report_inline_completion_event {
 5125            let completion_id = self
 5126                .active_inline_completion
 5127                .as_ref()
 5128                .and_then(|active_completion| active_completion.completion_id.clone());
 5129
 5130            self.report_inline_completion_event(completion_id, false, cx);
 5131        }
 5132
 5133        if let Some(provider) = self.edit_prediction_provider() {
 5134            provider.discard(cx);
 5135        }
 5136
 5137        self.take_active_inline_completion(cx)
 5138    }
 5139
 5140    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5141        let Some(provider) = self.edit_prediction_provider() else {
 5142            return;
 5143        };
 5144
 5145        let Some((_, buffer, _)) = self
 5146            .buffer
 5147            .read(cx)
 5148            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5149        else {
 5150            return;
 5151        };
 5152
 5153        let extension = buffer
 5154            .read(cx)
 5155            .file()
 5156            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5157
 5158        let event_type = match accepted {
 5159            true => "Edit Prediction Accepted",
 5160            false => "Edit Prediction Discarded",
 5161        };
 5162        telemetry::event!(
 5163            event_type,
 5164            provider = provider.name(),
 5165            prediction_id = id,
 5166            suggestion_accepted = accepted,
 5167            file_extension = extension,
 5168        );
 5169    }
 5170
 5171    pub fn has_active_inline_completion(&self) -> bool {
 5172        self.active_inline_completion.is_some()
 5173    }
 5174
 5175    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5176        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5177            return false;
 5178        };
 5179
 5180        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5181        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5182        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5183        true
 5184    }
 5185
 5186    /// Returns true when we're displaying the edit prediction popover below the cursor
 5187    /// like we are not previewing and the LSP autocomplete menu is visible
 5188    /// or we are in `when_holding_modifier` mode.
 5189    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5190        if self.edit_prediction_preview_is_active()
 5191            || !self.show_edit_predictions_in_menu()
 5192            || !self.edit_predictions_enabled()
 5193        {
 5194            return false;
 5195        }
 5196
 5197        if self.has_visible_completions_menu() {
 5198            return true;
 5199        }
 5200
 5201        has_completion && self.edit_prediction_requires_modifier()
 5202    }
 5203
 5204    fn handle_modifiers_changed(
 5205        &mut self,
 5206        modifiers: Modifiers,
 5207        position_map: &PositionMap,
 5208        window: &mut Window,
 5209        cx: &mut Context<Self>,
 5210    ) {
 5211        if self.show_edit_predictions_in_menu() {
 5212            self.update_edit_prediction_preview(&modifiers, window, cx);
 5213        }
 5214
 5215        let mouse_position = window.mouse_position();
 5216        if !position_map.text_hitbox.is_hovered(window) {
 5217            return;
 5218        }
 5219
 5220        self.update_hovered_link(
 5221            position_map.point_for_position(mouse_position),
 5222            &position_map.snapshot,
 5223            modifiers,
 5224            window,
 5225            cx,
 5226        )
 5227    }
 5228
 5229    fn update_edit_prediction_preview(
 5230        &mut self,
 5231        modifiers: &Modifiers,
 5232        window: &mut Window,
 5233        cx: &mut Context<Self>,
 5234    ) {
 5235        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5236        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5237            return;
 5238        };
 5239
 5240        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5241            if matches!(
 5242                self.edit_prediction_preview,
 5243                EditPredictionPreview::Inactive
 5244            ) {
 5245                self.edit_prediction_preview = EditPredictionPreview::Active {
 5246                    previous_scroll_position: None,
 5247                };
 5248
 5249                self.update_visible_inline_completion(window, cx);
 5250                cx.notify();
 5251            }
 5252        } else if let EditPredictionPreview::Active {
 5253            previous_scroll_position,
 5254        } = self.edit_prediction_preview
 5255        {
 5256            if let (Some(previous_scroll_position), Some(position_map)) =
 5257                (previous_scroll_position, self.last_position_map.as_ref())
 5258            {
 5259                self.set_scroll_position(
 5260                    previous_scroll_position
 5261                        .scroll_position(&position_map.snapshot.display_snapshot),
 5262                    window,
 5263                    cx,
 5264                );
 5265            }
 5266
 5267            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5268            self.clear_row_highlights::<EditPredictionPreview>();
 5269            self.update_visible_inline_completion(window, cx);
 5270            cx.notify();
 5271        }
 5272    }
 5273
 5274    fn update_visible_inline_completion(
 5275        &mut self,
 5276        _window: &mut Window,
 5277        cx: &mut Context<Self>,
 5278    ) -> Option<()> {
 5279        let selection = self.selections.newest_anchor();
 5280        let cursor = selection.head();
 5281        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5282        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5283        let excerpt_id = cursor.excerpt_id;
 5284
 5285        let show_in_menu = self.show_edit_predictions_in_menu();
 5286        let completions_menu_has_precedence = !show_in_menu
 5287            && (self.context_menu.borrow().is_some()
 5288                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5289
 5290        if completions_menu_has_precedence
 5291            || !offset_selection.is_empty()
 5292            || self
 5293                .active_inline_completion
 5294                .as_ref()
 5295                .map_or(false, |completion| {
 5296                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5297                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5298                    !invalidation_range.contains(&offset_selection.head())
 5299                })
 5300        {
 5301            self.discard_inline_completion(false, cx);
 5302            return None;
 5303        }
 5304
 5305        self.take_active_inline_completion(cx);
 5306        let Some(provider) = self.edit_prediction_provider() else {
 5307            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5308            return None;
 5309        };
 5310
 5311        let (buffer, cursor_buffer_position) =
 5312            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5313
 5314        self.edit_prediction_settings =
 5315            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5316
 5317        if !self.edit_prediction_settings.is_enabled() {
 5318            self.discard_inline_completion(false, cx);
 5319            return None;
 5320        }
 5321
 5322        self.edit_prediction_cursor_on_leading_whitespace =
 5323            multibuffer.is_line_whitespace_upto(cursor);
 5324
 5325        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5326        let edits = inline_completion
 5327            .edits
 5328            .into_iter()
 5329            .flat_map(|(range, new_text)| {
 5330                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5331                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5332                Some((start..end, new_text))
 5333            })
 5334            .collect::<Vec<_>>();
 5335        if edits.is_empty() {
 5336            return None;
 5337        }
 5338
 5339        let first_edit_start = edits.first().unwrap().0.start;
 5340        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5341        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5342
 5343        let last_edit_end = edits.last().unwrap().0.end;
 5344        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5345        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5346
 5347        let cursor_row = cursor.to_point(&multibuffer).row;
 5348
 5349        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5350
 5351        let mut inlay_ids = Vec::new();
 5352        let invalidation_row_range;
 5353        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5354            Some(cursor_row..edit_end_row)
 5355        } else if cursor_row > edit_end_row {
 5356            Some(edit_start_row..cursor_row)
 5357        } else {
 5358            None
 5359        };
 5360        let is_move =
 5361            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5362        let completion = if is_move {
 5363            invalidation_row_range =
 5364                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5365            let target = first_edit_start;
 5366            InlineCompletion::Move { target, snapshot }
 5367        } else {
 5368            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5369                && !self.inline_completions_hidden_for_vim_mode;
 5370
 5371            if show_completions_in_buffer {
 5372                if edits
 5373                    .iter()
 5374                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5375                {
 5376                    let mut inlays = Vec::new();
 5377                    for (range, new_text) in &edits {
 5378                        let inlay = Inlay::inline_completion(
 5379                            post_inc(&mut self.next_inlay_id),
 5380                            range.start,
 5381                            new_text.as_str(),
 5382                        );
 5383                        inlay_ids.push(inlay.id);
 5384                        inlays.push(inlay);
 5385                    }
 5386
 5387                    self.splice_inlays(&[], inlays, cx);
 5388                } else {
 5389                    let background_color = cx.theme().status().deleted_background;
 5390                    self.highlight_text::<InlineCompletionHighlight>(
 5391                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5392                        HighlightStyle {
 5393                            background_color: Some(background_color),
 5394                            ..Default::default()
 5395                        },
 5396                        cx,
 5397                    );
 5398                }
 5399            }
 5400
 5401            invalidation_row_range = edit_start_row..edit_end_row;
 5402
 5403            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5404                if provider.show_tab_accept_marker() {
 5405                    EditDisplayMode::TabAccept
 5406                } else {
 5407                    EditDisplayMode::Inline
 5408                }
 5409            } else {
 5410                EditDisplayMode::DiffPopover
 5411            };
 5412
 5413            InlineCompletion::Edit {
 5414                edits,
 5415                edit_preview: inline_completion.edit_preview,
 5416                display_mode,
 5417                snapshot,
 5418            }
 5419        };
 5420
 5421        let invalidation_range = multibuffer
 5422            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5423            ..multibuffer.anchor_after(Point::new(
 5424                invalidation_row_range.end,
 5425                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5426            ));
 5427
 5428        self.stale_inline_completion_in_menu = None;
 5429        self.active_inline_completion = Some(InlineCompletionState {
 5430            inlay_ids,
 5431            completion,
 5432            completion_id: inline_completion.id,
 5433            invalidation_range,
 5434        });
 5435
 5436        cx.notify();
 5437
 5438        Some(())
 5439    }
 5440
 5441    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5442        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5443    }
 5444
 5445    fn render_code_actions_indicator(
 5446        &self,
 5447        _style: &EditorStyle,
 5448        row: DisplayRow,
 5449        is_active: bool,
 5450        cx: &mut Context<Self>,
 5451    ) -> Option<IconButton> {
 5452        if self.available_code_actions.is_some() {
 5453            Some(
 5454                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5455                    .shape(ui::IconButtonShape::Square)
 5456                    .icon_size(IconSize::XSmall)
 5457                    .icon_color(Color::Muted)
 5458                    .toggle_state(is_active)
 5459                    .tooltip({
 5460                        let focus_handle = self.focus_handle.clone();
 5461                        move |window, cx| {
 5462                            Tooltip::for_action_in(
 5463                                "Toggle Code Actions",
 5464                                &ToggleCodeActions {
 5465                                    deployed_from_indicator: None,
 5466                                },
 5467                                &focus_handle,
 5468                                window,
 5469                                cx,
 5470                            )
 5471                        }
 5472                    })
 5473                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5474                        window.focus(&editor.focus_handle(cx));
 5475                        editor.toggle_code_actions(
 5476                            &ToggleCodeActions {
 5477                                deployed_from_indicator: Some(row),
 5478                            },
 5479                            window,
 5480                            cx,
 5481                        );
 5482                    })),
 5483            )
 5484        } else {
 5485            None
 5486        }
 5487    }
 5488
 5489    fn clear_tasks(&mut self) {
 5490        self.tasks.clear()
 5491    }
 5492
 5493    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5494        if self.tasks.insert(key, value).is_some() {
 5495            // This case should hopefully be rare, but just in case...
 5496            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5497        }
 5498    }
 5499
 5500    fn build_tasks_context(
 5501        project: &Entity<Project>,
 5502        buffer: &Entity<Buffer>,
 5503        buffer_row: u32,
 5504        tasks: &Arc<RunnableTasks>,
 5505        cx: &mut Context<Self>,
 5506    ) -> Task<Option<task::TaskContext>> {
 5507        let position = Point::new(buffer_row, tasks.column);
 5508        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5509        let location = Location {
 5510            buffer: buffer.clone(),
 5511            range: range_start..range_start,
 5512        };
 5513        // Fill in the environmental variables from the tree-sitter captures
 5514        let mut captured_task_variables = TaskVariables::default();
 5515        for (capture_name, value) in tasks.extra_variables.clone() {
 5516            captured_task_variables.insert(
 5517                task::VariableName::Custom(capture_name.into()),
 5518                value.clone(),
 5519            );
 5520        }
 5521        project.update(cx, |project, cx| {
 5522            project.task_store().update(cx, |task_store, cx| {
 5523                task_store.task_context_for_location(captured_task_variables, location, cx)
 5524            })
 5525        })
 5526    }
 5527
 5528    pub fn spawn_nearest_task(
 5529        &mut self,
 5530        action: &SpawnNearestTask,
 5531        window: &mut Window,
 5532        cx: &mut Context<Self>,
 5533    ) {
 5534        let Some((workspace, _)) = self.workspace.clone() else {
 5535            return;
 5536        };
 5537        let Some(project) = self.project.clone() else {
 5538            return;
 5539        };
 5540
 5541        // Try to find a closest, enclosing node using tree-sitter that has a
 5542        // task
 5543        let Some((buffer, buffer_row, tasks)) = self
 5544            .find_enclosing_node_task(cx)
 5545            // Or find the task that's closest in row-distance.
 5546            .or_else(|| self.find_closest_task(cx))
 5547        else {
 5548            return;
 5549        };
 5550
 5551        let reveal_strategy = action.reveal;
 5552        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5553        cx.spawn_in(window, |_, mut cx| async move {
 5554            let context = task_context.await?;
 5555            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5556
 5557            let resolved = resolved_task.resolved.as_mut()?;
 5558            resolved.reveal = reveal_strategy;
 5559
 5560            workspace
 5561                .update(&mut cx, |workspace, cx| {
 5562                    workspace::tasks::schedule_resolved_task(
 5563                        workspace,
 5564                        task_source_kind,
 5565                        resolved_task,
 5566                        false,
 5567                        cx,
 5568                    );
 5569                })
 5570                .ok()
 5571        })
 5572        .detach();
 5573    }
 5574
 5575    fn find_closest_task(
 5576        &mut self,
 5577        cx: &mut Context<Self>,
 5578    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5579        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5580
 5581        let ((buffer_id, row), tasks) = self
 5582            .tasks
 5583            .iter()
 5584            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5585
 5586        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5587        let tasks = Arc::new(tasks.to_owned());
 5588        Some((buffer, *row, tasks))
 5589    }
 5590
 5591    fn find_enclosing_node_task(
 5592        &mut self,
 5593        cx: &mut Context<Self>,
 5594    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5595        let snapshot = self.buffer.read(cx).snapshot(cx);
 5596        let offset = self.selections.newest::<usize>(cx).head();
 5597        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5598        let buffer_id = excerpt.buffer().remote_id();
 5599
 5600        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5601        let mut cursor = layer.node().walk();
 5602
 5603        while cursor.goto_first_child_for_byte(offset).is_some() {
 5604            if cursor.node().end_byte() == offset {
 5605                cursor.goto_next_sibling();
 5606            }
 5607        }
 5608
 5609        // Ascend to the smallest ancestor that contains the range and has a task.
 5610        loop {
 5611            let node = cursor.node();
 5612            let node_range = node.byte_range();
 5613            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5614
 5615            // Check if this node contains our offset
 5616            if node_range.start <= offset && node_range.end >= offset {
 5617                // If it contains offset, check for task
 5618                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5619                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5620                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5621                }
 5622            }
 5623
 5624            if !cursor.goto_parent() {
 5625                break;
 5626            }
 5627        }
 5628        None
 5629    }
 5630
 5631    fn render_run_indicator(
 5632        &self,
 5633        _style: &EditorStyle,
 5634        is_active: bool,
 5635        row: DisplayRow,
 5636        cx: &mut Context<Self>,
 5637    ) -> IconButton {
 5638        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5639            .shape(ui::IconButtonShape::Square)
 5640            .icon_size(IconSize::XSmall)
 5641            .icon_color(Color::Muted)
 5642            .toggle_state(is_active)
 5643            .on_click(cx.listener(move |editor, _e, window, cx| {
 5644                window.focus(&editor.focus_handle(cx));
 5645                editor.toggle_code_actions(
 5646                    &ToggleCodeActions {
 5647                        deployed_from_indicator: Some(row),
 5648                    },
 5649                    window,
 5650                    cx,
 5651                );
 5652            }))
 5653    }
 5654
 5655    pub fn context_menu_visible(&self) -> bool {
 5656        !self.edit_prediction_preview_is_active()
 5657            && self
 5658                .context_menu
 5659                .borrow()
 5660                .as_ref()
 5661                .map_or(false, |menu| menu.visible())
 5662    }
 5663
 5664    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5665        self.context_menu
 5666            .borrow()
 5667            .as_ref()
 5668            .map(|menu| menu.origin())
 5669    }
 5670
 5671    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5672        px(30.)
 5673    }
 5674
 5675    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5676        if self.read_only(cx) {
 5677            cx.theme().players().read_only()
 5678        } else {
 5679            self.style.as_ref().unwrap().local_player
 5680        }
 5681    }
 5682
 5683    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5684        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5685        let accept_keystroke = accept_binding.keystroke()?;
 5686
 5687        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5688
 5689        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5690            Color::Accent
 5691        } else {
 5692            Color::Muted
 5693        };
 5694
 5695        h_flex()
 5696            .px_0p5()
 5697            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5698            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5699            .text_size(TextSize::XSmall.rems(cx))
 5700            .child(h_flex().children(ui::render_modifiers(
 5701                &accept_keystroke.modifiers,
 5702                PlatformStyle::platform(),
 5703                Some(modifiers_color),
 5704                Some(IconSize::XSmall.rems().into()),
 5705                true,
 5706            )))
 5707            .when(is_platform_style_mac, |parent| {
 5708                parent.child(accept_keystroke.key.clone())
 5709            })
 5710            .when(!is_platform_style_mac, |parent| {
 5711                parent.child(
 5712                    Key::new(
 5713                        util::capitalize(&accept_keystroke.key),
 5714                        Some(Color::Default),
 5715                    )
 5716                    .size(Some(IconSize::XSmall.rems().into())),
 5717                )
 5718            })
 5719            .into()
 5720    }
 5721
 5722    fn render_edit_prediction_line_popover(
 5723        &self,
 5724        label: impl Into<SharedString>,
 5725        icon: Option<IconName>,
 5726        window: &mut Window,
 5727        cx: &App,
 5728    ) -> Option<Div> {
 5729        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5730
 5731        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5732
 5733        let result = h_flex()
 5734            .gap_1()
 5735            .border_1()
 5736            .rounded_lg()
 5737            .shadow_sm()
 5738            .bg(bg_color)
 5739            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5740            .py_0p5()
 5741            .pl_1()
 5742            .pr(padding_right)
 5743            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5744            .child(Label::new(label).size(LabelSize::Small))
 5745            .when_some(icon, |element, icon| {
 5746                element.child(
 5747                    div()
 5748                        .mt(px(1.5))
 5749                        .child(Icon::new(icon).size(IconSize::Small)),
 5750                )
 5751            });
 5752
 5753        Some(result)
 5754    }
 5755
 5756    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5757        let accent_color = cx.theme().colors().text_accent;
 5758        let editor_bg_color = cx.theme().colors().editor_background;
 5759        editor_bg_color.blend(accent_color.opacity(0.1))
 5760    }
 5761
 5762    #[allow(clippy::too_many_arguments)]
 5763    fn render_edit_prediction_cursor_popover(
 5764        &self,
 5765        min_width: Pixels,
 5766        max_width: Pixels,
 5767        cursor_point: Point,
 5768        style: &EditorStyle,
 5769        accept_keystroke: &gpui::Keystroke,
 5770        _window: &Window,
 5771        cx: &mut Context<Editor>,
 5772    ) -> Option<AnyElement> {
 5773        let provider = self.edit_prediction_provider.as_ref()?;
 5774
 5775        if provider.provider.needs_terms_acceptance(cx) {
 5776            return Some(
 5777                h_flex()
 5778                    .min_w(min_width)
 5779                    .flex_1()
 5780                    .px_2()
 5781                    .py_1()
 5782                    .gap_3()
 5783                    .elevation_2(cx)
 5784                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5785                    .id("accept-terms")
 5786                    .cursor_pointer()
 5787                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5788                    .on_click(cx.listener(|this, _event, window, cx| {
 5789                        cx.stop_propagation();
 5790                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5791                        window.dispatch_action(
 5792                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5793                            cx,
 5794                        );
 5795                    }))
 5796                    .child(
 5797                        h_flex()
 5798                            .flex_1()
 5799                            .gap_2()
 5800                            .child(Icon::new(IconName::ZedPredict))
 5801                            .child(Label::new("Accept Terms of Service"))
 5802                            .child(div().w_full())
 5803                            .child(
 5804                                Icon::new(IconName::ArrowUpRight)
 5805                                    .color(Color::Muted)
 5806                                    .size(IconSize::Small),
 5807                            )
 5808                            .into_any_element(),
 5809                    )
 5810                    .into_any(),
 5811            );
 5812        }
 5813
 5814        let is_refreshing = provider.provider.is_refreshing(cx);
 5815
 5816        fn pending_completion_container() -> Div {
 5817            h_flex()
 5818                .h_full()
 5819                .flex_1()
 5820                .gap_2()
 5821                .child(Icon::new(IconName::ZedPredict))
 5822        }
 5823
 5824        let completion = match &self.active_inline_completion {
 5825            Some(completion) => match &completion.completion {
 5826                InlineCompletion::Move {
 5827                    target, snapshot, ..
 5828                } if !self.has_visible_completions_menu() => {
 5829                    use text::ToPoint as _;
 5830
 5831                    return Some(
 5832                        h_flex()
 5833                            .px_2()
 5834                            .py_1()
 5835                            .elevation_2(cx)
 5836                            .border_color(cx.theme().colors().border)
 5837                            .rounded_tl(px(0.))
 5838                            .gap_2()
 5839                            .child(
 5840                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5841                                    Icon::new(IconName::ZedPredictDown)
 5842                                } else {
 5843                                    Icon::new(IconName::ZedPredictUp)
 5844                                },
 5845                            )
 5846                            .child(Label::new("Hold").size(LabelSize::Small))
 5847                            .child(h_flex().children(ui::render_modifiers(
 5848                                &accept_keystroke.modifiers,
 5849                                PlatformStyle::platform(),
 5850                                Some(Color::Default),
 5851                                Some(IconSize::Small.rems().into()),
 5852                                false,
 5853                            )))
 5854                            .into_any(),
 5855                    );
 5856                }
 5857                _ => self.render_edit_prediction_cursor_popover_preview(
 5858                    completion,
 5859                    cursor_point,
 5860                    style,
 5861                    cx,
 5862                )?,
 5863            },
 5864
 5865            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5866                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5867                    stale_completion,
 5868                    cursor_point,
 5869                    style,
 5870                    cx,
 5871                )?,
 5872
 5873                None => {
 5874                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5875                }
 5876            },
 5877
 5878            None => pending_completion_container().child(Label::new("No Prediction")),
 5879        };
 5880
 5881        let completion = if is_refreshing {
 5882            completion
 5883                .with_animation(
 5884                    "loading-completion",
 5885                    Animation::new(Duration::from_secs(2))
 5886                        .repeat()
 5887                        .with_easing(pulsating_between(0.4, 0.8)),
 5888                    |label, delta| label.opacity(delta),
 5889                )
 5890                .into_any_element()
 5891        } else {
 5892            completion.into_any_element()
 5893        };
 5894
 5895        let has_completion = self.active_inline_completion.is_some();
 5896
 5897        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5898        Some(
 5899            h_flex()
 5900                .min_w(min_width)
 5901                .max_w(max_width)
 5902                .flex_1()
 5903                .elevation_2(cx)
 5904                .border_color(cx.theme().colors().border)
 5905                .child(
 5906                    div()
 5907                        .flex_1()
 5908                        .py_1()
 5909                        .px_2()
 5910                        .overflow_hidden()
 5911                        .child(completion),
 5912                )
 5913                .child(
 5914                    h_flex()
 5915                        .h_full()
 5916                        .border_l_1()
 5917                        .rounded_r_lg()
 5918                        .border_color(cx.theme().colors().border)
 5919                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5920                        .gap_1()
 5921                        .py_1()
 5922                        .px_2()
 5923                        .child(
 5924                            h_flex()
 5925                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5926                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5927                                .child(h_flex().children(ui::render_modifiers(
 5928                                    &accept_keystroke.modifiers,
 5929                                    PlatformStyle::platform(),
 5930                                    Some(if !has_completion {
 5931                                        Color::Muted
 5932                                    } else {
 5933                                        Color::Default
 5934                                    }),
 5935                                    None,
 5936                                    false,
 5937                                ))),
 5938                        )
 5939                        .child(Label::new("Preview").into_any_element())
 5940                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5941                )
 5942                .into_any(),
 5943        )
 5944    }
 5945
 5946    fn render_edit_prediction_cursor_popover_preview(
 5947        &self,
 5948        completion: &InlineCompletionState,
 5949        cursor_point: Point,
 5950        style: &EditorStyle,
 5951        cx: &mut Context<Editor>,
 5952    ) -> Option<Div> {
 5953        use text::ToPoint as _;
 5954
 5955        fn render_relative_row_jump(
 5956            prefix: impl Into<String>,
 5957            current_row: u32,
 5958            target_row: u32,
 5959        ) -> Div {
 5960            let (row_diff, arrow) = if target_row < current_row {
 5961                (current_row - target_row, IconName::ArrowUp)
 5962            } else {
 5963                (target_row - current_row, IconName::ArrowDown)
 5964            };
 5965
 5966            h_flex()
 5967                .child(
 5968                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5969                        .color(Color::Muted)
 5970                        .size(LabelSize::Small),
 5971                )
 5972                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5973        }
 5974
 5975        match &completion.completion {
 5976            InlineCompletion::Move {
 5977                target, snapshot, ..
 5978            } => Some(
 5979                h_flex()
 5980                    .px_2()
 5981                    .gap_2()
 5982                    .flex_1()
 5983                    .child(
 5984                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5985                            Icon::new(IconName::ZedPredictDown)
 5986                        } else {
 5987                            Icon::new(IconName::ZedPredictUp)
 5988                        },
 5989                    )
 5990                    .child(Label::new("Jump to Edit")),
 5991            ),
 5992
 5993            InlineCompletion::Edit {
 5994                edits,
 5995                edit_preview,
 5996                snapshot,
 5997                display_mode: _,
 5998            } => {
 5999                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6000
 6001                let highlighted_edits = crate::inline_completion_edit_text(
 6002                    &snapshot,
 6003                    &edits,
 6004                    edit_preview.as_ref()?,
 6005                    true,
 6006                    cx,
 6007                );
 6008
 6009                let len_total = highlighted_edits.text.len();
 6010                let first_line = &highlighted_edits.text
 6011                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 6012                let first_line_len = first_line.len();
 6013
 6014                let first_highlight_start = highlighted_edits
 6015                    .highlights
 6016                    .first()
 6017                    .map_or(0, |(range, _)| range.start);
 6018                let drop_prefix_len = first_line
 6019                    .char_indices()
 6020                    .find(|(_, c)| !c.is_whitespace())
 6021                    .map_or(first_highlight_start, |(ix, _)| {
 6022                        ix.min(first_highlight_start)
 6023                    });
 6024
 6025                let preview_text = &first_line[drop_prefix_len..];
 6026                let preview_len = preview_text.len();
 6027                let highlights = highlighted_edits
 6028                    .highlights
 6029                    .into_iter()
 6030                    .take_until(|(range, _)| range.start > first_line_len)
 6031                    .map(|(range, style)| {
 6032                        (
 6033                            range.start - drop_prefix_len
 6034                                ..(range.end - drop_prefix_len).min(preview_len),
 6035                            style,
 6036                        )
 6037                    });
 6038
 6039                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6040                    .with_highlights(&style.text, highlights);
 6041
 6042                let preview = h_flex()
 6043                    .gap_1()
 6044                    .min_w_16()
 6045                    .child(styled_text)
 6046                    .when(len_total > first_line_len, |parent| parent.child(""));
 6047
 6048                let left = if first_edit_row != cursor_point.row {
 6049                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6050                        .into_any_element()
 6051                } else {
 6052                    Icon::new(IconName::ZedPredict).into_any_element()
 6053                };
 6054
 6055                Some(
 6056                    h_flex()
 6057                        .h_full()
 6058                        .flex_1()
 6059                        .gap_2()
 6060                        .pr_1()
 6061                        .overflow_x_hidden()
 6062                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6063                        .child(left)
 6064                        .child(preview),
 6065                )
 6066            }
 6067        }
 6068    }
 6069
 6070    fn render_context_menu(
 6071        &self,
 6072        style: &EditorStyle,
 6073        max_height_in_lines: u32,
 6074        y_flipped: bool,
 6075        window: &mut Window,
 6076        cx: &mut Context<Editor>,
 6077    ) -> Option<AnyElement> {
 6078        let menu = self.context_menu.borrow();
 6079        let menu = menu.as_ref()?;
 6080        if !menu.visible() {
 6081            return None;
 6082        };
 6083        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6084    }
 6085
 6086    fn render_context_menu_aside(
 6087        &self,
 6088        style: &EditorStyle,
 6089        max_size: Size<Pixels>,
 6090        cx: &mut Context<Editor>,
 6091    ) -> Option<AnyElement> {
 6092        self.context_menu.borrow().as_ref().and_then(|menu| {
 6093            if menu.visible() {
 6094                menu.render_aside(
 6095                    style,
 6096                    max_size,
 6097                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6098                    cx,
 6099                )
 6100            } else {
 6101                None
 6102            }
 6103        })
 6104    }
 6105
 6106    fn hide_context_menu(
 6107        &mut self,
 6108        window: &mut Window,
 6109        cx: &mut Context<Self>,
 6110    ) -> Option<CodeContextMenu> {
 6111        cx.notify();
 6112        self.completion_tasks.clear();
 6113        let context_menu = self.context_menu.borrow_mut().take();
 6114        self.stale_inline_completion_in_menu.take();
 6115        self.update_visible_inline_completion(window, cx);
 6116        context_menu
 6117    }
 6118
 6119    fn show_snippet_choices(
 6120        &mut self,
 6121        choices: &Vec<String>,
 6122        selection: Range<Anchor>,
 6123        cx: &mut Context<Self>,
 6124    ) {
 6125        if selection.start.buffer_id.is_none() {
 6126            return;
 6127        }
 6128        let buffer_id = selection.start.buffer_id.unwrap();
 6129        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6130        let id = post_inc(&mut self.next_completion_id);
 6131
 6132        if let Some(buffer) = buffer {
 6133            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6134                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6135            ));
 6136        }
 6137    }
 6138
 6139    pub fn insert_snippet(
 6140        &mut self,
 6141        insertion_ranges: &[Range<usize>],
 6142        snippet: Snippet,
 6143        window: &mut Window,
 6144        cx: &mut Context<Self>,
 6145    ) -> Result<()> {
 6146        struct Tabstop<T> {
 6147            is_end_tabstop: bool,
 6148            ranges: Vec<Range<T>>,
 6149            choices: Option<Vec<String>>,
 6150        }
 6151
 6152        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6153            let snippet_text: Arc<str> = snippet.text.clone().into();
 6154            buffer.edit(
 6155                insertion_ranges
 6156                    .iter()
 6157                    .cloned()
 6158                    .map(|range| (range, snippet_text.clone())),
 6159                Some(AutoindentMode::EachLine),
 6160                cx,
 6161            );
 6162
 6163            let snapshot = &*buffer.read(cx);
 6164            let snippet = &snippet;
 6165            snippet
 6166                .tabstops
 6167                .iter()
 6168                .map(|tabstop| {
 6169                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6170                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6171                    });
 6172                    let mut tabstop_ranges = tabstop
 6173                        .ranges
 6174                        .iter()
 6175                        .flat_map(|tabstop_range| {
 6176                            let mut delta = 0_isize;
 6177                            insertion_ranges.iter().map(move |insertion_range| {
 6178                                let insertion_start = insertion_range.start as isize + delta;
 6179                                delta +=
 6180                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6181
 6182                                let start = ((insertion_start + tabstop_range.start) as usize)
 6183                                    .min(snapshot.len());
 6184                                let end = ((insertion_start + tabstop_range.end) as usize)
 6185                                    .min(snapshot.len());
 6186                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6187                            })
 6188                        })
 6189                        .collect::<Vec<_>>();
 6190                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6191
 6192                    Tabstop {
 6193                        is_end_tabstop,
 6194                        ranges: tabstop_ranges,
 6195                        choices: tabstop.choices.clone(),
 6196                    }
 6197                })
 6198                .collect::<Vec<_>>()
 6199        });
 6200        if let Some(tabstop) = tabstops.first() {
 6201            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6202                s.select_ranges(tabstop.ranges.iter().cloned());
 6203            });
 6204
 6205            if let Some(choices) = &tabstop.choices {
 6206                if let Some(selection) = tabstop.ranges.first() {
 6207                    self.show_snippet_choices(choices, selection.clone(), cx)
 6208                }
 6209            }
 6210
 6211            // If we're already at the last tabstop and it's at the end of the snippet,
 6212            // we're done, we don't need to keep the state around.
 6213            if !tabstop.is_end_tabstop {
 6214                let choices = tabstops
 6215                    .iter()
 6216                    .map(|tabstop| tabstop.choices.clone())
 6217                    .collect();
 6218
 6219                let ranges = tabstops
 6220                    .into_iter()
 6221                    .map(|tabstop| tabstop.ranges)
 6222                    .collect::<Vec<_>>();
 6223
 6224                self.snippet_stack.push(SnippetState {
 6225                    active_index: 0,
 6226                    ranges,
 6227                    choices,
 6228                });
 6229            }
 6230
 6231            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6232            if self.autoclose_regions.is_empty() {
 6233                let snapshot = self.buffer.read(cx).snapshot(cx);
 6234                for selection in &mut self.selections.all::<Point>(cx) {
 6235                    let selection_head = selection.head();
 6236                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6237                        continue;
 6238                    };
 6239
 6240                    let mut bracket_pair = None;
 6241                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6242                    let prev_chars = snapshot
 6243                        .reversed_chars_at(selection_head)
 6244                        .collect::<String>();
 6245                    for (pair, enabled) in scope.brackets() {
 6246                        if enabled
 6247                            && pair.close
 6248                            && prev_chars.starts_with(pair.start.as_str())
 6249                            && next_chars.starts_with(pair.end.as_str())
 6250                        {
 6251                            bracket_pair = Some(pair.clone());
 6252                            break;
 6253                        }
 6254                    }
 6255                    if let Some(pair) = bracket_pair {
 6256                        let start = snapshot.anchor_after(selection_head);
 6257                        let end = snapshot.anchor_after(selection_head);
 6258                        self.autoclose_regions.push(AutocloseRegion {
 6259                            selection_id: selection.id,
 6260                            range: start..end,
 6261                            pair,
 6262                        });
 6263                    }
 6264                }
 6265            }
 6266        }
 6267        Ok(())
 6268    }
 6269
 6270    pub fn move_to_next_snippet_tabstop(
 6271        &mut self,
 6272        window: &mut Window,
 6273        cx: &mut Context<Self>,
 6274    ) -> bool {
 6275        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6276    }
 6277
 6278    pub fn move_to_prev_snippet_tabstop(
 6279        &mut self,
 6280        window: &mut Window,
 6281        cx: &mut Context<Self>,
 6282    ) -> bool {
 6283        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6284    }
 6285
 6286    pub fn move_to_snippet_tabstop(
 6287        &mut self,
 6288        bias: Bias,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) -> bool {
 6292        if let Some(mut snippet) = self.snippet_stack.pop() {
 6293            match bias {
 6294                Bias::Left => {
 6295                    if snippet.active_index > 0 {
 6296                        snippet.active_index -= 1;
 6297                    } else {
 6298                        self.snippet_stack.push(snippet);
 6299                        return false;
 6300                    }
 6301                }
 6302                Bias::Right => {
 6303                    if snippet.active_index + 1 < snippet.ranges.len() {
 6304                        snippet.active_index += 1;
 6305                    } else {
 6306                        self.snippet_stack.push(snippet);
 6307                        return false;
 6308                    }
 6309                }
 6310            }
 6311            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6312                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6313                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6314                });
 6315
 6316                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6317                    if let Some(selection) = current_ranges.first() {
 6318                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6319                    }
 6320                }
 6321
 6322                // If snippet state is not at the last tabstop, push it back on the stack
 6323                if snippet.active_index + 1 < snippet.ranges.len() {
 6324                    self.snippet_stack.push(snippet);
 6325                }
 6326                return true;
 6327            }
 6328        }
 6329
 6330        false
 6331    }
 6332
 6333    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6334        self.transact(window, cx, |this, window, cx| {
 6335            this.select_all(&SelectAll, window, cx);
 6336            this.insert("", window, cx);
 6337        });
 6338    }
 6339
 6340    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6341        self.transact(window, cx, |this, window, cx| {
 6342            this.select_autoclose_pair(window, cx);
 6343            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6344            if !this.linked_edit_ranges.is_empty() {
 6345                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6346                let snapshot = this.buffer.read(cx).snapshot(cx);
 6347
 6348                for selection in selections.iter() {
 6349                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6350                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6351                    if selection_start.buffer_id != selection_end.buffer_id {
 6352                        continue;
 6353                    }
 6354                    if let Some(ranges) =
 6355                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6356                    {
 6357                        for (buffer, entries) in ranges {
 6358                            linked_ranges.entry(buffer).or_default().extend(entries);
 6359                        }
 6360                    }
 6361                }
 6362            }
 6363
 6364            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6365            if !this.selections.line_mode {
 6366                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6367                for selection in &mut selections {
 6368                    if selection.is_empty() {
 6369                        let old_head = selection.head();
 6370                        let mut new_head =
 6371                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6372                                .to_point(&display_map);
 6373                        if let Some((buffer, line_buffer_range)) = display_map
 6374                            .buffer_snapshot
 6375                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6376                        {
 6377                            let indent_size =
 6378                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6379                            let indent_len = match indent_size.kind {
 6380                                IndentKind::Space => {
 6381                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6382                                }
 6383                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6384                            };
 6385                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6386                                let indent_len = indent_len.get();
 6387                                new_head = cmp::min(
 6388                                    new_head,
 6389                                    MultiBufferPoint::new(
 6390                                        old_head.row,
 6391                                        ((old_head.column - 1) / indent_len) * indent_len,
 6392                                    ),
 6393                                );
 6394                            }
 6395                        }
 6396
 6397                        selection.set_head(new_head, SelectionGoal::None);
 6398                    }
 6399                }
 6400            }
 6401
 6402            this.signature_help_state.set_backspace_pressed(true);
 6403            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6404                s.select(selections)
 6405            });
 6406            this.insert("", window, cx);
 6407            let empty_str: Arc<str> = Arc::from("");
 6408            for (buffer, edits) in linked_ranges {
 6409                let snapshot = buffer.read(cx).snapshot();
 6410                use text::ToPoint as TP;
 6411
 6412                let edits = edits
 6413                    .into_iter()
 6414                    .map(|range| {
 6415                        let end_point = TP::to_point(&range.end, &snapshot);
 6416                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6417
 6418                        if end_point == start_point {
 6419                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6420                                .saturating_sub(1);
 6421                            start_point =
 6422                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6423                        };
 6424
 6425                        (start_point..end_point, empty_str.clone())
 6426                    })
 6427                    .sorted_by_key(|(range, _)| range.start)
 6428                    .collect::<Vec<_>>();
 6429                buffer.update(cx, |this, cx| {
 6430                    this.edit(edits, None, cx);
 6431                })
 6432            }
 6433            this.refresh_inline_completion(true, false, window, cx);
 6434            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6435        });
 6436    }
 6437
 6438    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6439        self.transact(window, cx, |this, window, cx| {
 6440            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6441                let line_mode = s.line_mode;
 6442                s.move_with(|map, selection| {
 6443                    if selection.is_empty() && !line_mode {
 6444                        let cursor = movement::right(map, selection.head());
 6445                        selection.end = cursor;
 6446                        selection.reversed = true;
 6447                        selection.goal = SelectionGoal::None;
 6448                    }
 6449                })
 6450            });
 6451            this.insert("", window, cx);
 6452            this.refresh_inline_completion(true, false, window, cx);
 6453        });
 6454    }
 6455
 6456    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6457        if self.move_to_prev_snippet_tabstop(window, cx) {
 6458            return;
 6459        }
 6460
 6461        self.outdent(&Outdent, window, cx);
 6462    }
 6463
 6464    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6465        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6466            return;
 6467        }
 6468
 6469        let mut selections = self.selections.all_adjusted(cx);
 6470        let buffer = self.buffer.read(cx);
 6471        let snapshot = buffer.snapshot(cx);
 6472        let rows_iter = selections.iter().map(|s| s.head().row);
 6473        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6474
 6475        let mut edits = Vec::new();
 6476        let mut prev_edited_row = 0;
 6477        let mut row_delta = 0;
 6478        for selection in &mut selections {
 6479            if selection.start.row != prev_edited_row {
 6480                row_delta = 0;
 6481            }
 6482            prev_edited_row = selection.end.row;
 6483
 6484            // If the selection is non-empty, then increase the indentation of the selected lines.
 6485            if !selection.is_empty() {
 6486                row_delta =
 6487                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6488                continue;
 6489            }
 6490
 6491            // If the selection is empty and the cursor is in the leading whitespace before the
 6492            // suggested indentation, then auto-indent the line.
 6493            let cursor = selection.head();
 6494            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6495            if let Some(suggested_indent) =
 6496                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6497            {
 6498                if cursor.column < suggested_indent.len
 6499                    && cursor.column <= current_indent.len
 6500                    && current_indent.len <= suggested_indent.len
 6501                {
 6502                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6503                    selection.end = selection.start;
 6504                    if row_delta == 0 {
 6505                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6506                            cursor.row,
 6507                            current_indent,
 6508                            suggested_indent,
 6509                        ));
 6510                        row_delta = suggested_indent.len - current_indent.len;
 6511                    }
 6512                    continue;
 6513                }
 6514            }
 6515
 6516            // Otherwise, insert a hard or soft tab.
 6517            let settings = buffer.settings_at(cursor, cx);
 6518            let tab_size = if settings.hard_tabs {
 6519                IndentSize::tab()
 6520            } else {
 6521                let tab_size = settings.tab_size.get();
 6522                let char_column = snapshot
 6523                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6524                    .flat_map(str::chars)
 6525                    .count()
 6526                    + row_delta as usize;
 6527                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6528                IndentSize::spaces(chars_to_next_tab_stop)
 6529            };
 6530            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6531            selection.end = selection.start;
 6532            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6533            row_delta += tab_size.len;
 6534        }
 6535
 6536        self.transact(window, cx, |this, window, cx| {
 6537            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6538            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6539                s.select(selections)
 6540            });
 6541            this.refresh_inline_completion(true, false, window, cx);
 6542        });
 6543    }
 6544
 6545    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6546        if self.read_only(cx) {
 6547            return;
 6548        }
 6549        let mut selections = self.selections.all::<Point>(cx);
 6550        let mut prev_edited_row = 0;
 6551        let mut row_delta = 0;
 6552        let mut edits = Vec::new();
 6553        let buffer = self.buffer.read(cx);
 6554        let snapshot = buffer.snapshot(cx);
 6555        for selection in &mut selections {
 6556            if selection.start.row != prev_edited_row {
 6557                row_delta = 0;
 6558            }
 6559            prev_edited_row = selection.end.row;
 6560
 6561            row_delta =
 6562                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6563        }
 6564
 6565        self.transact(window, cx, |this, window, cx| {
 6566            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6567            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6568                s.select(selections)
 6569            });
 6570        });
 6571    }
 6572
 6573    fn indent_selection(
 6574        buffer: &MultiBuffer,
 6575        snapshot: &MultiBufferSnapshot,
 6576        selection: &mut Selection<Point>,
 6577        edits: &mut Vec<(Range<Point>, String)>,
 6578        delta_for_start_row: u32,
 6579        cx: &App,
 6580    ) -> u32 {
 6581        let settings = buffer.settings_at(selection.start, cx);
 6582        let tab_size = settings.tab_size.get();
 6583        let indent_kind = if settings.hard_tabs {
 6584            IndentKind::Tab
 6585        } else {
 6586            IndentKind::Space
 6587        };
 6588        let mut start_row = selection.start.row;
 6589        let mut end_row = selection.end.row + 1;
 6590
 6591        // If a selection ends at the beginning of a line, don't indent
 6592        // that last line.
 6593        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6594            end_row -= 1;
 6595        }
 6596
 6597        // Avoid re-indenting a row that has already been indented by a
 6598        // previous selection, but still update this selection's column
 6599        // to reflect that indentation.
 6600        if delta_for_start_row > 0 {
 6601            start_row += 1;
 6602            selection.start.column += delta_for_start_row;
 6603            if selection.end.row == selection.start.row {
 6604                selection.end.column += delta_for_start_row;
 6605            }
 6606        }
 6607
 6608        let mut delta_for_end_row = 0;
 6609        let has_multiple_rows = start_row + 1 != end_row;
 6610        for row in start_row..end_row {
 6611            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6612            let indent_delta = match (current_indent.kind, indent_kind) {
 6613                (IndentKind::Space, IndentKind::Space) => {
 6614                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6615                    IndentSize::spaces(columns_to_next_tab_stop)
 6616                }
 6617                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6618                (_, IndentKind::Tab) => IndentSize::tab(),
 6619            };
 6620
 6621            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6622                0
 6623            } else {
 6624                selection.start.column
 6625            };
 6626            let row_start = Point::new(row, start);
 6627            edits.push((
 6628                row_start..row_start,
 6629                indent_delta.chars().collect::<String>(),
 6630            ));
 6631
 6632            // Update this selection's endpoints to reflect the indentation.
 6633            if row == selection.start.row {
 6634                selection.start.column += indent_delta.len;
 6635            }
 6636            if row == selection.end.row {
 6637                selection.end.column += indent_delta.len;
 6638                delta_for_end_row = indent_delta.len;
 6639            }
 6640        }
 6641
 6642        if selection.start.row == selection.end.row {
 6643            delta_for_start_row + delta_for_end_row
 6644        } else {
 6645            delta_for_end_row
 6646        }
 6647    }
 6648
 6649    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6650        if self.read_only(cx) {
 6651            return;
 6652        }
 6653        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6654        let selections = self.selections.all::<Point>(cx);
 6655        let mut deletion_ranges = Vec::new();
 6656        let mut last_outdent = None;
 6657        {
 6658            let buffer = self.buffer.read(cx);
 6659            let snapshot = buffer.snapshot(cx);
 6660            for selection in &selections {
 6661                let settings = buffer.settings_at(selection.start, cx);
 6662                let tab_size = settings.tab_size.get();
 6663                let mut rows = selection.spanned_rows(false, &display_map);
 6664
 6665                // Avoid re-outdenting a row that has already been outdented by a
 6666                // previous selection.
 6667                if let Some(last_row) = last_outdent {
 6668                    if last_row == rows.start {
 6669                        rows.start = rows.start.next_row();
 6670                    }
 6671                }
 6672                let has_multiple_rows = rows.len() > 1;
 6673                for row in rows.iter_rows() {
 6674                    let indent_size = snapshot.indent_size_for_line(row);
 6675                    if indent_size.len > 0 {
 6676                        let deletion_len = match indent_size.kind {
 6677                            IndentKind::Space => {
 6678                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6679                                if columns_to_prev_tab_stop == 0 {
 6680                                    tab_size
 6681                                } else {
 6682                                    columns_to_prev_tab_stop
 6683                                }
 6684                            }
 6685                            IndentKind::Tab => 1,
 6686                        };
 6687                        let start = if has_multiple_rows
 6688                            || deletion_len > selection.start.column
 6689                            || indent_size.len < selection.start.column
 6690                        {
 6691                            0
 6692                        } else {
 6693                            selection.start.column - deletion_len
 6694                        };
 6695                        deletion_ranges.push(
 6696                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6697                        );
 6698                        last_outdent = Some(row);
 6699                    }
 6700                }
 6701            }
 6702        }
 6703
 6704        self.transact(window, cx, |this, window, cx| {
 6705            this.buffer.update(cx, |buffer, cx| {
 6706                let empty_str: Arc<str> = Arc::default();
 6707                buffer.edit(
 6708                    deletion_ranges
 6709                        .into_iter()
 6710                        .map(|range| (range, empty_str.clone())),
 6711                    None,
 6712                    cx,
 6713                );
 6714            });
 6715            let selections = this.selections.all::<usize>(cx);
 6716            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6717                s.select(selections)
 6718            });
 6719        });
 6720    }
 6721
 6722    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6723        if self.read_only(cx) {
 6724            return;
 6725        }
 6726        let selections = self
 6727            .selections
 6728            .all::<usize>(cx)
 6729            .into_iter()
 6730            .map(|s| s.range());
 6731
 6732        self.transact(window, cx, |this, window, cx| {
 6733            this.buffer.update(cx, |buffer, cx| {
 6734                buffer.autoindent_ranges(selections, cx);
 6735            });
 6736            let selections = this.selections.all::<usize>(cx);
 6737            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6738                s.select(selections)
 6739            });
 6740        });
 6741    }
 6742
 6743    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6744        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6745        let selections = self.selections.all::<Point>(cx);
 6746
 6747        let mut new_cursors = Vec::new();
 6748        let mut edit_ranges = Vec::new();
 6749        let mut selections = selections.iter().peekable();
 6750        while let Some(selection) = selections.next() {
 6751            let mut rows = selection.spanned_rows(false, &display_map);
 6752            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6753
 6754            // Accumulate contiguous regions of rows that we want to delete.
 6755            while let Some(next_selection) = selections.peek() {
 6756                let next_rows = next_selection.spanned_rows(false, &display_map);
 6757                if next_rows.start <= rows.end {
 6758                    rows.end = next_rows.end;
 6759                    selections.next().unwrap();
 6760                } else {
 6761                    break;
 6762                }
 6763            }
 6764
 6765            let buffer = &display_map.buffer_snapshot;
 6766            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6767            let edit_end;
 6768            let cursor_buffer_row;
 6769            if buffer.max_point().row >= rows.end.0 {
 6770                // If there's a line after the range, delete the \n from the end of the row range
 6771                // and position the cursor on the next line.
 6772                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6773                cursor_buffer_row = rows.end;
 6774            } else {
 6775                // If there isn't a line after the range, delete the \n from the line before the
 6776                // start of the row range and position the cursor there.
 6777                edit_start = edit_start.saturating_sub(1);
 6778                edit_end = buffer.len();
 6779                cursor_buffer_row = rows.start.previous_row();
 6780            }
 6781
 6782            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6783            *cursor.column_mut() =
 6784                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6785
 6786            new_cursors.push((
 6787                selection.id,
 6788                buffer.anchor_after(cursor.to_point(&display_map)),
 6789            ));
 6790            edit_ranges.push(edit_start..edit_end);
 6791        }
 6792
 6793        self.transact(window, cx, |this, window, cx| {
 6794            let buffer = this.buffer.update(cx, |buffer, cx| {
 6795                let empty_str: Arc<str> = Arc::default();
 6796                buffer.edit(
 6797                    edit_ranges
 6798                        .into_iter()
 6799                        .map(|range| (range, empty_str.clone())),
 6800                    None,
 6801                    cx,
 6802                );
 6803                buffer.snapshot(cx)
 6804            });
 6805            let new_selections = new_cursors
 6806                .into_iter()
 6807                .map(|(id, cursor)| {
 6808                    let cursor = cursor.to_point(&buffer);
 6809                    Selection {
 6810                        id,
 6811                        start: cursor,
 6812                        end: cursor,
 6813                        reversed: false,
 6814                        goal: SelectionGoal::None,
 6815                    }
 6816                })
 6817                .collect();
 6818
 6819            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6820                s.select(new_selections);
 6821            });
 6822        });
 6823    }
 6824
 6825    pub fn join_lines_impl(
 6826        &mut self,
 6827        insert_whitespace: bool,
 6828        window: &mut Window,
 6829        cx: &mut Context<Self>,
 6830    ) {
 6831        if self.read_only(cx) {
 6832            return;
 6833        }
 6834        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6835        for selection in self.selections.all::<Point>(cx) {
 6836            let start = MultiBufferRow(selection.start.row);
 6837            // Treat single line selections as if they include the next line. Otherwise this action
 6838            // would do nothing for single line selections individual cursors.
 6839            let end = if selection.start.row == selection.end.row {
 6840                MultiBufferRow(selection.start.row + 1)
 6841            } else {
 6842                MultiBufferRow(selection.end.row)
 6843            };
 6844
 6845            if let Some(last_row_range) = row_ranges.last_mut() {
 6846                if start <= last_row_range.end {
 6847                    last_row_range.end = end;
 6848                    continue;
 6849                }
 6850            }
 6851            row_ranges.push(start..end);
 6852        }
 6853
 6854        let snapshot = self.buffer.read(cx).snapshot(cx);
 6855        let mut cursor_positions = Vec::new();
 6856        for row_range in &row_ranges {
 6857            let anchor = snapshot.anchor_before(Point::new(
 6858                row_range.end.previous_row().0,
 6859                snapshot.line_len(row_range.end.previous_row()),
 6860            ));
 6861            cursor_positions.push(anchor..anchor);
 6862        }
 6863
 6864        self.transact(window, cx, |this, window, cx| {
 6865            for row_range in row_ranges.into_iter().rev() {
 6866                for row in row_range.iter_rows().rev() {
 6867                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6868                    let next_line_row = row.next_row();
 6869                    let indent = snapshot.indent_size_for_line(next_line_row);
 6870                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6871
 6872                    let replace =
 6873                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6874                            " "
 6875                        } else {
 6876                            ""
 6877                        };
 6878
 6879                    this.buffer.update(cx, |buffer, cx| {
 6880                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6881                    });
 6882                }
 6883            }
 6884
 6885            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6886                s.select_anchor_ranges(cursor_positions)
 6887            });
 6888        });
 6889    }
 6890
 6891    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6892        self.join_lines_impl(true, window, cx);
 6893    }
 6894
 6895    pub fn sort_lines_case_sensitive(
 6896        &mut self,
 6897        _: &SortLinesCaseSensitive,
 6898        window: &mut Window,
 6899        cx: &mut Context<Self>,
 6900    ) {
 6901        self.manipulate_lines(window, cx, |lines| lines.sort())
 6902    }
 6903
 6904    pub fn sort_lines_case_insensitive(
 6905        &mut self,
 6906        _: &SortLinesCaseInsensitive,
 6907        window: &mut Window,
 6908        cx: &mut Context<Self>,
 6909    ) {
 6910        self.manipulate_lines(window, cx, |lines| {
 6911            lines.sort_by_key(|line| line.to_lowercase())
 6912        })
 6913    }
 6914
 6915    pub fn unique_lines_case_insensitive(
 6916        &mut self,
 6917        _: &UniqueLinesCaseInsensitive,
 6918        window: &mut Window,
 6919        cx: &mut Context<Self>,
 6920    ) {
 6921        self.manipulate_lines(window, cx, |lines| {
 6922            let mut seen = HashSet::default();
 6923            lines.retain(|line| seen.insert(line.to_lowercase()));
 6924        })
 6925    }
 6926
 6927    pub fn unique_lines_case_sensitive(
 6928        &mut self,
 6929        _: &UniqueLinesCaseSensitive,
 6930        window: &mut Window,
 6931        cx: &mut Context<Self>,
 6932    ) {
 6933        self.manipulate_lines(window, cx, |lines| {
 6934            let mut seen = HashSet::default();
 6935            lines.retain(|line| seen.insert(*line));
 6936        })
 6937    }
 6938
 6939    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6940        let mut revert_changes = HashMap::default();
 6941        let snapshot = self.snapshot(window, cx);
 6942        for hunk in snapshot
 6943            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6944        {
 6945            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6946        }
 6947        if !revert_changes.is_empty() {
 6948            self.transact(window, cx, |editor, window, cx| {
 6949                editor.revert(revert_changes, window, cx);
 6950            });
 6951        }
 6952    }
 6953
 6954    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6955        let Some(project) = self.project.clone() else {
 6956            return;
 6957        };
 6958        self.reload(project, window, cx)
 6959            .detach_and_notify_err(window, cx);
 6960    }
 6961
 6962    pub fn revert_selected_hunks(
 6963        &mut self,
 6964        _: &RevertSelectedHunks,
 6965        window: &mut Window,
 6966        cx: &mut Context<Self>,
 6967    ) {
 6968        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6969        self.revert_hunks_in_ranges(selections, window, cx);
 6970    }
 6971
 6972    fn revert_hunks_in_ranges(
 6973        &mut self,
 6974        ranges: impl Iterator<Item = Range<Point>>,
 6975        window: &mut Window,
 6976        cx: &mut Context<Editor>,
 6977    ) {
 6978        let mut revert_changes = HashMap::default();
 6979        let snapshot = self.snapshot(window, cx);
 6980        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6981            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6982        }
 6983        if !revert_changes.is_empty() {
 6984            self.transact(window, cx, |editor, window, cx| {
 6985                editor.revert(revert_changes, window, cx);
 6986            });
 6987        }
 6988    }
 6989
 6990    pub fn open_active_item_in_terminal(
 6991        &mut self,
 6992        _: &OpenInTerminal,
 6993        window: &mut Window,
 6994        cx: &mut Context<Self>,
 6995    ) {
 6996        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6997            let project_path = buffer.read(cx).project_path(cx)?;
 6998            let project = self.project.as_ref()?.read(cx);
 6999            let entry = project.entry_for_path(&project_path, cx)?;
 7000            let parent = match &entry.canonical_path {
 7001                Some(canonical_path) => canonical_path.to_path_buf(),
 7002                None => project.absolute_path(&project_path, cx)?,
 7003            }
 7004            .parent()?
 7005            .to_path_buf();
 7006            Some(parent)
 7007        }) {
 7008            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7009        }
 7010    }
 7011
 7012    pub fn prepare_revert_change(
 7013        &self,
 7014        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7015        hunk: &MultiBufferDiffHunk,
 7016        cx: &mut App,
 7017    ) -> Option<()> {
 7018        let buffer = self.buffer.read(cx);
 7019        let diff = buffer.diff_for(hunk.buffer_id)?;
 7020        let buffer = buffer.buffer(hunk.buffer_id)?;
 7021        let buffer = buffer.read(cx);
 7022        let original_text = diff
 7023            .read(cx)
 7024            .base_text()
 7025            .as_ref()?
 7026            .as_rope()
 7027            .slice(hunk.diff_base_byte_range.clone());
 7028        let buffer_snapshot = buffer.snapshot();
 7029        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7030        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7031            probe
 7032                .0
 7033                .start
 7034                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7035                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7036        }) {
 7037            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7038            Some(())
 7039        } else {
 7040            None
 7041        }
 7042    }
 7043
 7044    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7045        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7046    }
 7047
 7048    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7049        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7050    }
 7051
 7052    fn manipulate_lines<Fn>(
 7053        &mut self,
 7054        window: &mut Window,
 7055        cx: &mut Context<Self>,
 7056        mut callback: Fn,
 7057    ) where
 7058        Fn: FnMut(&mut Vec<&str>),
 7059    {
 7060        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7061        let buffer = self.buffer.read(cx).snapshot(cx);
 7062
 7063        let mut edits = Vec::new();
 7064
 7065        let selections = self.selections.all::<Point>(cx);
 7066        let mut selections = selections.iter().peekable();
 7067        let mut contiguous_row_selections = Vec::new();
 7068        let mut new_selections = Vec::new();
 7069        let mut added_lines = 0;
 7070        let mut removed_lines = 0;
 7071
 7072        while let Some(selection) = selections.next() {
 7073            let (start_row, end_row) = consume_contiguous_rows(
 7074                &mut contiguous_row_selections,
 7075                selection,
 7076                &display_map,
 7077                &mut selections,
 7078            );
 7079
 7080            let start_point = Point::new(start_row.0, 0);
 7081            let end_point = Point::new(
 7082                end_row.previous_row().0,
 7083                buffer.line_len(end_row.previous_row()),
 7084            );
 7085            let text = buffer
 7086                .text_for_range(start_point..end_point)
 7087                .collect::<String>();
 7088
 7089            let mut lines = text.split('\n').collect_vec();
 7090
 7091            let lines_before = lines.len();
 7092            callback(&mut lines);
 7093            let lines_after = lines.len();
 7094
 7095            edits.push((start_point..end_point, lines.join("\n")));
 7096
 7097            // Selections must change based on added and removed line count
 7098            let start_row =
 7099                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7100            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7101            new_selections.push(Selection {
 7102                id: selection.id,
 7103                start: start_row,
 7104                end: end_row,
 7105                goal: SelectionGoal::None,
 7106                reversed: selection.reversed,
 7107            });
 7108
 7109            if lines_after > lines_before {
 7110                added_lines += lines_after - lines_before;
 7111            } else if lines_before > lines_after {
 7112                removed_lines += lines_before - lines_after;
 7113            }
 7114        }
 7115
 7116        self.transact(window, cx, |this, window, cx| {
 7117            let buffer = this.buffer.update(cx, |buffer, cx| {
 7118                buffer.edit(edits, None, cx);
 7119                buffer.snapshot(cx)
 7120            });
 7121
 7122            // Recalculate offsets on newly edited buffer
 7123            let new_selections = new_selections
 7124                .iter()
 7125                .map(|s| {
 7126                    let start_point = Point::new(s.start.0, 0);
 7127                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7128                    Selection {
 7129                        id: s.id,
 7130                        start: buffer.point_to_offset(start_point),
 7131                        end: buffer.point_to_offset(end_point),
 7132                        goal: s.goal,
 7133                        reversed: s.reversed,
 7134                    }
 7135                })
 7136                .collect();
 7137
 7138            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7139                s.select(new_selections);
 7140            });
 7141
 7142            this.request_autoscroll(Autoscroll::fit(), cx);
 7143        });
 7144    }
 7145
 7146    pub fn convert_to_upper_case(
 7147        &mut self,
 7148        _: &ConvertToUpperCase,
 7149        window: &mut Window,
 7150        cx: &mut Context<Self>,
 7151    ) {
 7152        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7153    }
 7154
 7155    pub fn convert_to_lower_case(
 7156        &mut self,
 7157        _: &ConvertToLowerCase,
 7158        window: &mut Window,
 7159        cx: &mut Context<Self>,
 7160    ) {
 7161        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7162    }
 7163
 7164    pub fn convert_to_title_case(
 7165        &mut self,
 7166        _: &ConvertToTitleCase,
 7167        window: &mut Window,
 7168        cx: &mut Context<Self>,
 7169    ) {
 7170        self.manipulate_text(window, cx, |text| {
 7171            text.split('\n')
 7172                .map(|line| line.to_case(Case::Title))
 7173                .join("\n")
 7174        })
 7175    }
 7176
 7177    pub fn convert_to_snake_case(
 7178        &mut self,
 7179        _: &ConvertToSnakeCase,
 7180        window: &mut Window,
 7181        cx: &mut Context<Self>,
 7182    ) {
 7183        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7184    }
 7185
 7186    pub fn convert_to_kebab_case(
 7187        &mut self,
 7188        _: &ConvertToKebabCase,
 7189        window: &mut Window,
 7190        cx: &mut Context<Self>,
 7191    ) {
 7192        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7193    }
 7194
 7195    pub fn convert_to_upper_camel_case(
 7196        &mut self,
 7197        _: &ConvertToUpperCamelCase,
 7198        window: &mut Window,
 7199        cx: &mut Context<Self>,
 7200    ) {
 7201        self.manipulate_text(window, cx, |text| {
 7202            text.split('\n')
 7203                .map(|line| line.to_case(Case::UpperCamel))
 7204                .join("\n")
 7205        })
 7206    }
 7207
 7208    pub fn convert_to_lower_camel_case(
 7209        &mut self,
 7210        _: &ConvertToLowerCamelCase,
 7211        window: &mut Window,
 7212        cx: &mut Context<Self>,
 7213    ) {
 7214        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7215    }
 7216
 7217    pub fn convert_to_opposite_case(
 7218        &mut self,
 7219        _: &ConvertToOppositeCase,
 7220        window: &mut Window,
 7221        cx: &mut Context<Self>,
 7222    ) {
 7223        self.manipulate_text(window, cx, |text| {
 7224            text.chars()
 7225                .fold(String::with_capacity(text.len()), |mut t, c| {
 7226                    if c.is_uppercase() {
 7227                        t.extend(c.to_lowercase());
 7228                    } else {
 7229                        t.extend(c.to_uppercase());
 7230                    }
 7231                    t
 7232                })
 7233        })
 7234    }
 7235
 7236    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7237    where
 7238        Fn: FnMut(&str) -> String,
 7239    {
 7240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7241        let buffer = self.buffer.read(cx).snapshot(cx);
 7242
 7243        let mut new_selections = Vec::new();
 7244        let mut edits = Vec::new();
 7245        let mut selection_adjustment = 0i32;
 7246
 7247        for selection in self.selections.all::<usize>(cx) {
 7248            let selection_is_empty = selection.is_empty();
 7249
 7250            let (start, end) = if selection_is_empty {
 7251                let word_range = movement::surrounding_word(
 7252                    &display_map,
 7253                    selection.start.to_display_point(&display_map),
 7254                );
 7255                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7256                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7257                (start, end)
 7258            } else {
 7259                (selection.start, selection.end)
 7260            };
 7261
 7262            let text = buffer.text_for_range(start..end).collect::<String>();
 7263            let old_length = text.len() as i32;
 7264            let text = callback(&text);
 7265
 7266            new_selections.push(Selection {
 7267                start: (start as i32 - selection_adjustment) as usize,
 7268                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7269                goal: SelectionGoal::None,
 7270                ..selection
 7271            });
 7272
 7273            selection_adjustment += old_length - text.len() as i32;
 7274
 7275            edits.push((start..end, text));
 7276        }
 7277
 7278        self.transact(window, cx, |this, window, cx| {
 7279            this.buffer.update(cx, |buffer, cx| {
 7280                buffer.edit(edits, None, cx);
 7281            });
 7282
 7283            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7284                s.select(new_selections);
 7285            });
 7286
 7287            this.request_autoscroll(Autoscroll::fit(), cx);
 7288        });
 7289    }
 7290
 7291    pub fn duplicate(
 7292        &mut self,
 7293        upwards: bool,
 7294        whole_lines: bool,
 7295        window: &mut Window,
 7296        cx: &mut Context<Self>,
 7297    ) {
 7298        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7299        let buffer = &display_map.buffer_snapshot;
 7300        let selections = self.selections.all::<Point>(cx);
 7301
 7302        let mut edits = Vec::new();
 7303        let mut selections_iter = selections.iter().peekable();
 7304        while let Some(selection) = selections_iter.next() {
 7305            let mut rows = selection.spanned_rows(false, &display_map);
 7306            // duplicate line-wise
 7307            if whole_lines || selection.start == selection.end {
 7308                // Avoid duplicating the same lines twice.
 7309                while let Some(next_selection) = selections_iter.peek() {
 7310                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7311                    if next_rows.start < rows.end {
 7312                        rows.end = next_rows.end;
 7313                        selections_iter.next().unwrap();
 7314                    } else {
 7315                        break;
 7316                    }
 7317                }
 7318
 7319                // Copy the text from the selected row region and splice it either at the start
 7320                // or end of the region.
 7321                let start = Point::new(rows.start.0, 0);
 7322                let end = Point::new(
 7323                    rows.end.previous_row().0,
 7324                    buffer.line_len(rows.end.previous_row()),
 7325                );
 7326                let text = buffer
 7327                    .text_for_range(start..end)
 7328                    .chain(Some("\n"))
 7329                    .collect::<String>();
 7330                let insert_location = if upwards {
 7331                    Point::new(rows.end.0, 0)
 7332                } else {
 7333                    start
 7334                };
 7335                edits.push((insert_location..insert_location, text));
 7336            } else {
 7337                // duplicate character-wise
 7338                let start = selection.start;
 7339                let end = selection.end;
 7340                let text = buffer.text_for_range(start..end).collect::<String>();
 7341                edits.push((selection.end..selection.end, text));
 7342            }
 7343        }
 7344
 7345        self.transact(window, cx, |this, _, cx| {
 7346            this.buffer.update(cx, |buffer, cx| {
 7347                buffer.edit(edits, None, cx);
 7348            });
 7349
 7350            this.request_autoscroll(Autoscroll::fit(), cx);
 7351        });
 7352    }
 7353
 7354    pub fn duplicate_line_up(
 7355        &mut self,
 7356        _: &DuplicateLineUp,
 7357        window: &mut Window,
 7358        cx: &mut Context<Self>,
 7359    ) {
 7360        self.duplicate(true, true, window, cx);
 7361    }
 7362
 7363    pub fn duplicate_line_down(
 7364        &mut self,
 7365        _: &DuplicateLineDown,
 7366        window: &mut Window,
 7367        cx: &mut Context<Self>,
 7368    ) {
 7369        self.duplicate(false, true, window, cx);
 7370    }
 7371
 7372    pub fn duplicate_selection(
 7373        &mut self,
 7374        _: &DuplicateSelection,
 7375        window: &mut Window,
 7376        cx: &mut Context<Self>,
 7377    ) {
 7378        self.duplicate(false, false, window, cx);
 7379    }
 7380
 7381    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7383        let buffer = self.buffer.read(cx).snapshot(cx);
 7384
 7385        let mut edits = Vec::new();
 7386        let mut unfold_ranges = Vec::new();
 7387        let mut refold_creases = Vec::new();
 7388
 7389        let selections = self.selections.all::<Point>(cx);
 7390        let mut selections = selections.iter().peekable();
 7391        let mut contiguous_row_selections = Vec::new();
 7392        let mut new_selections = Vec::new();
 7393
 7394        while let Some(selection) = selections.next() {
 7395            // Find all the selections that span a contiguous row range
 7396            let (start_row, end_row) = consume_contiguous_rows(
 7397                &mut contiguous_row_selections,
 7398                selection,
 7399                &display_map,
 7400                &mut selections,
 7401            );
 7402
 7403            // Move the text spanned by the row range to be before the line preceding the row range
 7404            if start_row.0 > 0 {
 7405                let range_to_move = Point::new(
 7406                    start_row.previous_row().0,
 7407                    buffer.line_len(start_row.previous_row()),
 7408                )
 7409                    ..Point::new(
 7410                        end_row.previous_row().0,
 7411                        buffer.line_len(end_row.previous_row()),
 7412                    );
 7413                let insertion_point = display_map
 7414                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7415                    .0;
 7416
 7417                // Don't move lines across excerpts
 7418                if buffer
 7419                    .excerpt_containing(insertion_point..range_to_move.end)
 7420                    .is_some()
 7421                {
 7422                    let text = buffer
 7423                        .text_for_range(range_to_move.clone())
 7424                        .flat_map(|s| s.chars())
 7425                        .skip(1)
 7426                        .chain(['\n'])
 7427                        .collect::<String>();
 7428
 7429                    edits.push((
 7430                        buffer.anchor_after(range_to_move.start)
 7431                            ..buffer.anchor_before(range_to_move.end),
 7432                        String::new(),
 7433                    ));
 7434                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7435                    edits.push((insertion_anchor..insertion_anchor, text));
 7436
 7437                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7438
 7439                    // Move selections up
 7440                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7441                        |mut selection| {
 7442                            selection.start.row -= row_delta;
 7443                            selection.end.row -= row_delta;
 7444                            selection
 7445                        },
 7446                    ));
 7447
 7448                    // Move folds up
 7449                    unfold_ranges.push(range_to_move.clone());
 7450                    for fold in display_map.folds_in_range(
 7451                        buffer.anchor_before(range_to_move.start)
 7452                            ..buffer.anchor_after(range_to_move.end),
 7453                    ) {
 7454                        let mut start = fold.range.start.to_point(&buffer);
 7455                        let mut end = fold.range.end.to_point(&buffer);
 7456                        start.row -= row_delta;
 7457                        end.row -= row_delta;
 7458                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7459                    }
 7460                }
 7461            }
 7462
 7463            // If we didn't move line(s), preserve the existing selections
 7464            new_selections.append(&mut contiguous_row_selections);
 7465        }
 7466
 7467        self.transact(window, cx, |this, window, cx| {
 7468            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7469            this.buffer.update(cx, |buffer, cx| {
 7470                for (range, text) in edits {
 7471                    buffer.edit([(range, text)], None, cx);
 7472                }
 7473            });
 7474            this.fold_creases(refold_creases, true, window, cx);
 7475            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7476                s.select(new_selections);
 7477            })
 7478        });
 7479    }
 7480
 7481    pub fn move_line_down(
 7482        &mut self,
 7483        _: &MoveLineDown,
 7484        window: &mut Window,
 7485        cx: &mut Context<Self>,
 7486    ) {
 7487        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7488        let buffer = self.buffer.read(cx).snapshot(cx);
 7489
 7490        let mut edits = Vec::new();
 7491        let mut unfold_ranges = Vec::new();
 7492        let mut refold_creases = Vec::new();
 7493
 7494        let selections = self.selections.all::<Point>(cx);
 7495        let mut selections = selections.iter().peekable();
 7496        let mut contiguous_row_selections = Vec::new();
 7497        let mut new_selections = Vec::new();
 7498
 7499        while let Some(selection) = selections.next() {
 7500            // Find all the selections that span a contiguous row range
 7501            let (start_row, end_row) = consume_contiguous_rows(
 7502                &mut contiguous_row_selections,
 7503                selection,
 7504                &display_map,
 7505                &mut selections,
 7506            );
 7507
 7508            // Move the text spanned by the row range to be after the last line of the row range
 7509            if end_row.0 <= buffer.max_point().row {
 7510                let range_to_move =
 7511                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7512                let insertion_point = display_map
 7513                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7514                    .0;
 7515
 7516                // Don't move lines across excerpt boundaries
 7517                if buffer
 7518                    .excerpt_containing(range_to_move.start..insertion_point)
 7519                    .is_some()
 7520                {
 7521                    let mut text = String::from("\n");
 7522                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7523                    text.pop(); // Drop trailing newline
 7524                    edits.push((
 7525                        buffer.anchor_after(range_to_move.start)
 7526                            ..buffer.anchor_before(range_to_move.end),
 7527                        String::new(),
 7528                    ));
 7529                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7530                    edits.push((insertion_anchor..insertion_anchor, text));
 7531
 7532                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7533
 7534                    // Move selections down
 7535                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7536                        |mut selection| {
 7537                            selection.start.row += row_delta;
 7538                            selection.end.row += row_delta;
 7539                            selection
 7540                        },
 7541                    ));
 7542
 7543                    // Move folds down
 7544                    unfold_ranges.push(range_to_move.clone());
 7545                    for fold in display_map.folds_in_range(
 7546                        buffer.anchor_before(range_to_move.start)
 7547                            ..buffer.anchor_after(range_to_move.end),
 7548                    ) {
 7549                        let mut start = fold.range.start.to_point(&buffer);
 7550                        let mut end = fold.range.end.to_point(&buffer);
 7551                        start.row += row_delta;
 7552                        end.row += row_delta;
 7553                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7554                    }
 7555                }
 7556            }
 7557
 7558            // If we didn't move line(s), preserve the existing selections
 7559            new_selections.append(&mut contiguous_row_selections);
 7560        }
 7561
 7562        self.transact(window, cx, |this, window, cx| {
 7563            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7564            this.buffer.update(cx, |buffer, cx| {
 7565                for (range, text) in edits {
 7566                    buffer.edit([(range, text)], None, cx);
 7567                }
 7568            });
 7569            this.fold_creases(refold_creases, true, window, cx);
 7570            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7571                s.select(new_selections)
 7572            });
 7573        });
 7574    }
 7575
 7576    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7577        let text_layout_details = &self.text_layout_details(window);
 7578        self.transact(window, cx, |this, window, cx| {
 7579            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7580                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7581                let line_mode = s.line_mode;
 7582                s.move_with(|display_map, selection| {
 7583                    if !selection.is_empty() || line_mode {
 7584                        return;
 7585                    }
 7586
 7587                    let mut head = selection.head();
 7588                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7589                    if head.column() == display_map.line_len(head.row()) {
 7590                        transpose_offset = display_map
 7591                            .buffer_snapshot
 7592                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7593                    }
 7594
 7595                    if transpose_offset == 0 {
 7596                        return;
 7597                    }
 7598
 7599                    *head.column_mut() += 1;
 7600                    head = display_map.clip_point(head, Bias::Right);
 7601                    let goal = SelectionGoal::HorizontalPosition(
 7602                        display_map
 7603                            .x_for_display_point(head, text_layout_details)
 7604                            .into(),
 7605                    );
 7606                    selection.collapse_to(head, goal);
 7607
 7608                    let transpose_start = display_map
 7609                        .buffer_snapshot
 7610                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7611                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7612                        let transpose_end = display_map
 7613                            .buffer_snapshot
 7614                            .clip_offset(transpose_offset + 1, Bias::Right);
 7615                        if let Some(ch) =
 7616                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7617                        {
 7618                            edits.push((transpose_start..transpose_offset, String::new()));
 7619                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7620                        }
 7621                    }
 7622                });
 7623                edits
 7624            });
 7625            this.buffer
 7626                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7627            let selections = this.selections.all::<usize>(cx);
 7628            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7629                s.select(selections);
 7630            });
 7631        });
 7632    }
 7633
 7634    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7635        self.rewrap_impl(IsVimMode::No, cx)
 7636    }
 7637
 7638    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7639        let buffer = self.buffer.read(cx).snapshot(cx);
 7640        let selections = self.selections.all::<Point>(cx);
 7641        let mut selections = selections.iter().peekable();
 7642
 7643        let mut edits = Vec::new();
 7644        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7645
 7646        while let Some(selection) = selections.next() {
 7647            let mut start_row = selection.start.row;
 7648            let mut end_row = selection.end.row;
 7649
 7650            // Skip selections that overlap with a range that has already been rewrapped.
 7651            let selection_range = start_row..end_row;
 7652            if rewrapped_row_ranges
 7653                .iter()
 7654                .any(|range| range.overlaps(&selection_range))
 7655            {
 7656                continue;
 7657            }
 7658
 7659            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7660
 7661            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7662                match language_scope.language_name().as_ref() {
 7663                    "Markdown" | "Plain Text" => {
 7664                        should_rewrap = true;
 7665                    }
 7666                    _ => {}
 7667                }
 7668            }
 7669
 7670            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7671
 7672            // Since not all lines in the selection may be at the same indent
 7673            // level, choose the indent size that is the most common between all
 7674            // of the lines.
 7675            //
 7676            // If there is a tie, we use the deepest indent.
 7677            let (indent_size, indent_end) = {
 7678                let mut indent_size_occurrences = HashMap::default();
 7679                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7680
 7681                for row in start_row..=end_row {
 7682                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7683                    rows_by_indent_size.entry(indent).or_default().push(row);
 7684                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7685                }
 7686
 7687                let indent_size = indent_size_occurrences
 7688                    .into_iter()
 7689                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7690                    .map(|(indent, _)| indent)
 7691                    .unwrap_or_default();
 7692                let row = rows_by_indent_size[&indent_size][0];
 7693                let indent_end = Point::new(row, indent_size.len);
 7694
 7695                (indent_size, indent_end)
 7696            };
 7697
 7698            let mut line_prefix = indent_size.chars().collect::<String>();
 7699
 7700            if let Some(comment_prefix) =
 7701                buffer
 7702                    .language_scope_at(selection.head())
 7703                    .and_then(|language| {
 7704                        language
 7705                            .line_comment_prefixes()
 7706                            .iter()
 7707                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7708                            .cloned()
 7709                    })
 7710            {
 7711                line_prefix.push_str(&comment_prefix);
 7712                should_rewrap = true;
 7713            }
 7714
 7715            if !should_rewrap {
 7716                continue;
 7717            }
 7718
 7719            if selection.is_empty() {
 7720                'expand_upwards: while start_row > 0 {
 7721                    let prev_row = start_row - 1;
 7722                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7723                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7724                    {
 7725                        start_row = prev_row;
 7726                    } else {
 7727                        break 'expand_upwards;
 7728                    }
 7729                }
 7730
 7731                'expand_downwards: while end_row < buffer.max_point().row {
 7732                    let next_row = end_row + 1;
 7733                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7734                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7735                    {
 7736                        end_row = next_row;
 7737                    } else {
 7738                        break 'expand_downwards;
 7739                    }
 7740                }
 7741            }
 7742
 7743            let start = Point::new(start_row, 0);
 7744            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7745            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7746            let Some(lines_without_prefixes) = selection_text
 7747                .lines()
 7748                .map(|line| {
 7749                    line.strip_prefix(&line_prefix)
 7750                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7751                        .ok_or_else(|| {
 7752                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7753                        })
 7754                })
 7755                .collect::<Result<Vec<_>, _>>()
 7756                .log_err()
 7757            else {
 7758                continue;
 7759            };
 7760
 7761            let wrap_column = buffer
 7762                .settings_at(Point::new(start_row, 0), cx)
 7763                .preferred_line_length as usize;
 7764            let wrapped_text = wrap_with_prefix(
 7765                line_prefix,
 7766                lines_without_prefixes.join(" "),
 7767                wrap_column,
 7768                tab_size,
 7769            );
 7770
 7771            // TODO: should always use char-based diff while still supporting cursor behavior that
 7772            // matches vim.
 7773            let diff = match is_vim_mode {
 7774                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7775                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7776            };
 7777            let mut offset = start.to_offset(&buffer);
 7778            let mut moved_since_edit = true;
 7779
 7780            for change in diff.iter_all_changes() {
 7781                let value = change.value();
 7782                match change.tag() {
 7783                    ChangeTag::Equal => {
 7784                        offset += value.len();
 7785                        moved_since_edit = true;
 7786                    }
 7787                    ChangeTag::Delete => {
 7788                        let start = buffer.anchor_after(offset);
 7789                        let end = buffer.anchor_before(offset + value.len());
 7790
 7791                        if moved_since_edit {
 7792                            edits.push((start..end, String::new()));
 7793                        } else {
 7794                            edits.last_mut().unwrap().0.end = end;
 7795                        }
 7796
 7797                        offset += value.len();
 7798                        moved_since_edit = false;
 7799                    }
 7800                    ChangeTag::Insert => {
 7801                        if moved_since_edit {
 7802                            let anchor = buffer.anchor_after(offset);
 7803                            edits.push((anchor..anchor, value.to_string()));
 7804                        } else {
 7805                            edits.last_mut().unwrap().1.push_str(value);
 7806                        }
 7807
 7808                        moved_since_edit = false;
 7809                    }
 7810                }
 7811            }
 7812
 7813            rewrapped_row_ranges.push(start_row..=end_row);
 7814        }
 7815
 7816        self.buffer
 7817            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7818    }
 7819
 7820    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7821        let mut text = String::new();
 7822        let buffer = self.buffer.read(cx).snapshot(cx);
 7823        let mut selections = self.selections.all::<Point>(cx);
 7824        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7825        {
 7826            let max_point = buffer.max_point();
 7827            let mut is_first = true;
 7828            for selection in &mut selections {
 7829                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7830                if is_entire_line {
 7831                    selection.start = Point::new(selection.start.row, 0);
 7832                    if !selection.is_empty() && selection.end.column == 0 {
 7833                        selection.end = cmp::min(max_point, selection.end);
 7834                    } else {
 7835                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7836                    }
 7837                    selection.goal = SelectionGoal::None;
 7838                }
 7839                if is_first {
 7840                    is_first = false;
 7841                } else {
 7842                    text += "\n";
 7843                }
 7844                let mut len = 0;
 7845                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7846                    text.push_str(chunk);
 7847                    len += chunk.len();
 7848                }
 7849                clipboard_selections.push(ClipboardSelection {
 7850                    len,
 7851                    is_entire_line,
 7852                    first_line_indent: buffer
 7853                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7854                        .len,
 7855                });
 7856            }
 7857        }
 7858
 7859        self.transact(window, cx, |this, window, cx| {
 7860            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7861                s.select(selections);
 7862            });
 7863            this.insert("", window, cx);
 7864        });
 7865        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7866    }
 7867
 7868    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7869        let item = self.cut_common(window, cx);
 7870        cx.write_to_clipboard(item);
 7871    }
 7872
 7873    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7874        self.change_selections(None, window, cx, |s| {
 7875            s.move_with(|snapshot, sel| {
 7876                if sel.is_empty() {
 7877                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7878                }
 7879            });
 7880        });
 7881        let item = self.cut_common(window, cx);
 7882        cx.set_global(KillRing(item))
 7883    }
 7884
 7885    pub fn kill_ring_yank(
 7886        &mut self,
 7887        _: &KillRingYank,
 7888        window: &mut Window,
 7889        cx: &mut Context<Self>,
 7890    ) {
 7891        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7892            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7893                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7894            } else {
 7895                return;
 7896            }
 7897        } else {
 7898            return;
 7899        };
 7900        self.do_paste(&text, metadata, false, window, cx);
 7901    }
 7902
 7903    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7904        let selections = self.selections.all::<Point>(cx);
 7905        let buffer = self.buffer.read(cx).read(cx);
 7906        let mut text = String::new();
 7907
 7908        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7909        {
 7910            let max_point = buffer.max_point();
 7911            let mut is_first = true;
 7912            for selection in selections.iter() {
 7913                let mut start = selection.start;
 7914                let mut end = selection.end;
 7915                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7916                if is_entire_line {
 7917                    start = Point::new(start.row, 0);
 7918                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7919                }
 7920                if is_first {
 7921                    is_first = false;
 7922                } else {
 7923                    text += "\n";
 7924                }
 7925                let mut len = 0;
 7926                for chunk in buffer.text_for_range(start..end) {
 7927                    text.push_str(chunk);
 7928                    len += chunk.len();
 7929                }
 7930                clipboard_selections.push(ClipboardSelection {
 7931                    len,
 7932                    is_entire_line,
 7933                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7934                });
 7935            }
 7936        }
 7937
 7938        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7939            text,
 7940            clipboard_selections,
 7941        ));
 7942    }
 7943
 7944    pub fn do_paste(
 7945        &mut self,
 7946        text: &String,
 7947        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7948        handle_entire_lines: bool,
 7949        window: &mut Window,
 7950        cx: &mut Context<Self>,
 7951    ) {
 7952        if self.read_only(cx) {
 7953            return;
 7954        }
 7955
 7956        let clipboard_text = Cow::Borrowed(text);
 7957
 7958        self.transact(window, cx, |this, window, cx| {
 7959            if let Some(mut clipboard_selections) = clipboard_selections {
 7960                let old_selections = this.selections.all::<usize>(cx);
 7961                let all_selections_were_entire_line =
 7962                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7963                let first_selection_indent_column =
 7964                    clipboard_selections.first().map(|s| s.first_line_indent);
 7965                if clipboard_selections.len() != old_selections.len() {
 7966                    clipboard_selections.drain(..);
 7967                }
 7968                let cursor_offset = this.selections.last::<usize>(cx).head();
 7969                let mut auto_indent_on_paste = true;
 7970
 7971                this.buffer.update(cx, |buffer, cx| {
 7972                    let snapshot = buffer.read(cx);
 7973                    auto_indent_on_paste =
 7974                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7975
 7976                    let mut start_offset = 0;
 7977                    let mut edits = Vec::new();
 7978                    let mut original_indent_columns = Vec::new();
 7979                    for (ix, selection) in old_selections.iter().enumerate() {
 7980                        let to_insert;
 7981                        let entire_line;
 7982                        let original_indent_column;
 7983                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7984                            let end_offset = start_offset + clipboard_selection.len;
 7985                            to_insert = &clipboard_text[start_offset..end_offset];
 7986                            entire_line = clipboard_selection.is_entire_line;
 7987                            start_offset = end_offset + 1;
 7988                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7989                        } else {
 7990                            to_insert = clipboard_text.as_str();
 7991                            entire_line = all_selections_were_entire_line;
 7992                            original_indent_column = first_selection_indent_column
 7993                        }
 7994
 7995                        // If the corresponding selection was empty when this slice of the
 7996                        // clipboard text was written, then the entire line containing the
 7997                        // selection was copied. If this selection is also currently empty,
 7998                        // then paste the line before the current line of the buffer.
 7999                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8000                            let column = selection.start.to_point(&snapshot).column as usize;
 8001                            let line_start = selection.start - column;
 8002                            line_start..line_start
 8003                        } else {
 8004                            selection.range()
 8005                        };
 8006
 8007                        edits.push((range, to_insert));
 8008                        original_indent_columns.extend(original_indent_column);
 8009                    }
 8010                    drop(snapshot);
 8011
 8012                    buffer.edit(
 8013                        edits,
 8014                        if auto_indent_on_paste {
 8015                            Some(AutoindentMode::Block {
 8016                                original_indent_columns,
 8017                            })
 8018                        } else {
 8019                            None
 8020                        },
 8021                        cx,
 8022                    );
 8023                });
 8024
 8025                let selections = this.selections.all::<usize>(cx);
 8026                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8027                    s.select(selections)
 8028                });
 8029            } else {
 8030                this.insert(&clipboard_text, window, cx);
 8031            }
 8032        });
 8033    }
 8034
 8035    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8036        if let Some(item) = cx.read_from_clipboard() {
 8037            let entries = item.entries();
 8038
 8039            match entries.first() {
 8040                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8041                // of all the pasted entries.
 8042                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8043                    .do_paste(
 8044                        clipboard_string.text(),
 8045                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8046                        true,
 8047                        window,
 8048                        cx,
 8049                    ),
 8050                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8051            }
 8052        }
 8053    }
 8054
 8055    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8056        if self.read_only(cx) {
 8057            return;
 8058        }
 8059
 8060        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8061            if let Some((selections, _)) =
 8062                self.selection_history.transaction(transaction_id).cloned()
 8063            {
 8064                self.change_selections(None, window, cx, |s| {
 8065                    s.select_anchors(selections.to_vec());
 8066                });
 8067            }
 8068            self.request_autoscroll(Autoscroll::fit(), cx);
 8069            self.unmark_text(window, cx);
 8070            self.refresh_inline_completion(true, false, window, cx);
 8071            cx.emit(EditorEvent::Edited { transaction_id });
 8072            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8073        }
 8074    }
 8075
 8076    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8077        if self.read_only(cx) {
 8078            return;
 8079        }
 8080
 8081        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8082            if let Some((_, Some(selections))) =
 8083                self.selection_history.transaction(transaction_id).cloned()
 8084            {
 8085                self.change_selections(None, window, cx, |s| {
 8086                    s.select_anchors(selections.to_vec());
 8087                });
 8088            }
 8089            self.request_autoscroll(Autoscroll::fit(), cx);
 8090            self.unmark_text(window, cx);
 8091            self.refresh_inline_completion(true, false, window, cx);
 8092            cx.emit(EditorEvent::Edited { transaction_id });
 8093        }
 8094    }
 8095
 8096    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8097        self.buffer
 8098            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8099    }
 8100
 8101    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8102        self.buffer
 8103            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8104    }
 8105
 8106    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8107        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8108            let line_mode = s.line_mode;
 8109            s.move_with(|map, selection| {
 8110                let cursor = if selection.is_empty() && !line_mode {
 8111                    movement::left(map, selection.start)
 8112                } else {
 8113                    selection.start
 8114                };
 8115                selection.collapse_to(cursor, SelectionGoal::None);
 8116            });
 8117        })
 8118    }
 8119
 8120    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8121        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8122            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8123        })
 8124    }
 8125
 8126    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8127        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8128            let line_mode = s.line_mode;
 8129            s.move_with(|map, selection| {
 8130                let cursor = if selection.is_empty() && !line_mode {
 8131                    movement::right(map, selection.end)
 8132                } else {
 8133                    selection.end
 8134                };
 8135                selection.collapse_to(cursor, SelectionGoal::None)
 8136            });
 8137        })
 8138    }
 8139
 8140    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8141        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8142            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8143        })
 8144    }
 8145
 8146    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8147        if self.take_rename(true, window, cx).is_some() {
 8148            return;
 8149        }
 8150
 8151        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8152            cx.propagate();
 8153            return;
 8154        }
 8155
 8156        let text_layout_details = &self.text_layout_details(window);
 8157        let selection_count = self.selections.count();
 8158        let first_selection = self.selections.first_anchor();
 8159
 8160        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8161            let line_mode = s.line_mode;
 8162            s.move_with(|map, selection| {
 8163                if !selection.is_empty() && !line_mode {
 8164                    selection.goal = SelectionGoal::None;
 8165                }
 8166                let (cursor, goal) = movement::up(
 8167                    map,
 8168                    selection.start,
 8169                    selection.goal,
 8170                    false,
 8171                    text_layout_details,
 8172                );
 8173                selection.collapse_to(cursor, goal);
 8174            });
 8175        });
 8176
 8177        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8178        {
 8179            cx.propagate();
 8180        }
 8181    }
 8182
 8183    pub fn move_up_by_lines(
 8184        &mut self,
 8185        action: &MoveUpByLines,
 8186        window: &mut Window,
 8187        cx: &mut Context<Self>,
 8188    ) {
 8189        if self.take_rename(true, window, cx).is_some() {
 8190            return;
 8191        }
 8192
 8193        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8194            cx.propagate();
 8195            return;
 8196        }
 8197
 8198        let text_layout_details = &self.text_layout_details(window);
 8199
 8200        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8201            let line_mode = s.line_mode;
 8202            s.move_with(|map, selection| {
 8203                if !selection.is_empty() && !line_mode {
 8204                    selection.goal = SelectionGoal::None;
 8205                }
 8206                let (cursor, goal) = movement::up_by_rows(
 8207                    map,
 8208                    selection.start,
 8209                    action.lines,
 8210                    selection.goal,
 8211                    false,
 8212                    text_layout_details,
 8213                );
 8214                selection.collapse_to(cursor, goal);
 8215            });
 8216        })
 8217    }
 8218
 8219    pub fn move_down_by_lines(
 8220        &mut self,
 8221        action: &MoveDownByLines,
 8222        window: &mut Window,
 8223        cx: &mut Context<Self>,
 8224    ) {
 8225        if self.take_rename(true, window, cx).is_some() {
 8226            return;
 8227        }
 8228
 8229        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8230            cx.propagate();
 8231            return;
 8232        }
 8233
 8234        let text_layout_details = &self.text_layout_details(window);
 8235
 8236        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237            let line_mode = s.line_mode;
 8238            s.move_with(|map, selection| {
 8239                if !selection.is_empty() && !line_mode {
 8240                    selection.goal = SelectionGoal::None;
 8241                }
 8242                let (cursor, goal) = movement::down_by_rows(
 8243                    map,
 8244                    selection.start,
 8245                    action.lines,
 8246                    selection.goal,
 8247                    false,
 8248                    text_layout_details,
 8249                );
 8250                selection.collapse_to(cursor, goal);
 8251            });
 8252        })
 8253    }
 8254
 8255    pub fn select_down_by_lines(
 8256        &mut self,
 8257        action: &SelectDownByLines,
 8258        window: &mut Window,
 8259        cx: &mut Context<Self>,
 8260    ) {
 8261        let text_layout_details = &self.text_layout_details(window);
 8262        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8263            s.move_heads_with(|map, head, goal| {
 8264                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8265            })
 8266        })
 8267    }
 8268
 8269    pub fn select_up_by_lines(
 8270        &mut self,
 8271        action: &SelectUpByLines,
 8272        window: &mut Window,
 8273        cx: &mut Context<Self>,
 8274    ) {
 8275        let text_layout_details = &self.text_layout_details(window);
 8276        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8277            s.move_heads_with(|map, head, goal| {
 8278                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8279            })
 8280        })
 8281    }
 8282
 8283    pub fn select_page_up(
 8284        &mut self,
 8285        _: &SelectPageUp,
 8286        window: &mut Window,
 8287        cx: &mut Context<Self>,
 8288    ) {
 8289        let Some(row_count) = self.visible_row_count() else {
 8290            return;
 8291        };
 8292
 8293        let text_layout_details = &self.text_layout_details(window);
 8294
 8295        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8296            s.move_heads_with(|map, head, goal| {
 8297                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8298            })
 8299        })
 8300    }
 8301
 8302    pub fn move_page_up(
 8303        &mut self,
 8304        action: &MovePageUp,
 8305        window: &mut Window,
 8306        cx: &mut Context<Self>,
 8307    ) {
 8308        if self.take_rename(true, window, cx).is_some() {
 8309            return;
 8310        }
 8311
 8312        if self
 8313            .context_menu
 8314            .borrow_mut()
 8315            .as_mut()
 8316            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8317            .unwrap_or(false)
 8318        {
 8319            return;
 8320        }
 8321
 8322        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8323            cx.propagate();
 8324            return;
 8325        }
 8326
 8327        let Some(row_count) = self.visible_row_count() else {
 8328            return;
 8329        };
 8330
 8331        let autoscroll = if action.center_cursor {
 8332            Autoscroll::center()
 8333        } else {
 8334            Autoscroll::fit()
 8335        };
 8336
 8337        let text_layout_details = &self.text_layout_details(window);
 8338
 8339        self.change_selections(Some(autoscroll), window, cx, |s| {
 8340            let line_mode = s.line_mode;
 8341            s.move_with(|map, selection| {
 8342                if !selection.is_empty() && !line_mode {
 8343                    selection.goal = SelectionGoal::None;
 8344                }
 8345                let (cursor, goal) = movement::up_by_rows(
 8346                    map,
 8347                    selection.end,
 8348                    row_count,
 8349                    selection.goal,
 8350                    false,
 8351                    text_layout_details,
 8352                );
 8353                selection.collapse_to(cursor, goal);
 8354            });
 8355        });
 8356    }
 8357
 8358    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8359        let text_layout_details = &self.text_layout_details(window);
 8360        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8361            s.move_heads_with(|map, head, goal| {
 8362                movement::up(map, head, goal, false, text_layout_details)
 8363            })
 8364        })
 8365    }
 8366
 8367    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8368        self.take_rename(true, window, cx);
 8369
 8370        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8371            cx.propagate();
 8372            return;
 8373        }
 8374
 8375        let text_layout_details = &self.text_layout_details(window);
 8376        let selection_count = self.selections.count();
 8377        let first_selection = self.selections.first_anchor();
 8378
 8379        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8380            let line_mode = s.line_mode;
 8381            s.move_with(|map, selection| {
 8382                if !selection.is_empty() && !line_mode {
 8383                    selection.goal = SelectionGoal::None;
 8384                }
 8385                let (cursor, goal) = movement::down(
 8386                    map,
 8387                    selection.end,
 8388                    selection.goal,
 8389                    false,
 8390                    text_layout_details,
 8391                );
 8392                selection.collapse_to(cursor, goal);
 8393            });
 8394        });
 8395
 8396        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8397        {
 8398            cx.propagate();
 8399        }
 8400    }
 8401
 8402    pub fn select_page_down(
 8403        &mut self,
 8404        _: &SelectPageDown,
 8405        window: &mut Window,
 8406        cx: &mut Context<Self>,
 8407    ) {
 8408        let Some(row_count) = self.visible_row_count() else {
 8409            return;
 8410        };
 8411
 8412        let text_layout_details = &self.text_layout_details(window);
 8413
 8414        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8415            s.move_heads_with(|map, head, goal| {
 8416                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8417            })
 8418        })
 8419    }
 8420
 8421    pub fn move_page_down(
 8422        &mut self,
 8423        action: &MovePageDown,
 8424        window: &mut Window,
 8425        cx: &mut Context<Self>,
 8426    ) {
 8427        if self.take_rename(true, window, cx).is_some() {
 8428            return;
 8429        }
 8430
 8431        if self
 8432            .context_menu
 8433            .borrow_mut()
 8434            .as_mut()
 8435            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8436            .unwrap_or(false)
 8437        {
 8438            return;
 8439        }
 8440
 8441        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8442            cx.propagate();
 8443            return;
 8444        }
 8445
 8446        let Some(row_count) = self.visible_row_count() else {
 8447            return;
 8448        };
 8449
 8450        let autoscroll = if action.center_cursor {
 8451            Autoscroll::center()
 8452        } else {
 8453            Autoscroll::fit()
 8454        };
 8455
 8456        let text_layout_details = &self.text_layout_details(window);
 8457        self.change_selections(Some(autoscroll), window, cx, |s| {
 8458            let line_mode = s.line_mode;
 8459            s.move_with(|map, selection| {
 8460                if !selection.is_empty() && !line_mode {
 8461                    selection.goal = SelectionGoal::None;
 8462                }
 8463                let (cursor, goal) = movement::down_by_rows(
 8464                    map,
 8465                    selection.end,
 8466                    row_count,
 8467                    selection.goal,
 8468                    false,
 8469                    text_layout_details,
 8470                );
 8471                selection.collapse_to(cursor, goal);
 8472            });
 8473        });
 8474    }
 8475
 8476    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8477        let text_layout_details = &self.text_layout_details(window);
 8478        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8479            s.move_heads_with(|map, head, goal| {
 8480                movement::down(map, head, goal, false, text_layout_details)
 8481            })
 8482        });
 8483    }
 8484
 8485    pub fn context_menu_first(
 8486        &mut self,
 8487        _: &ContextMenuFirst,
 8488        _window: &mut Window,
 8489        cx: &mut Context<Self>,
 8490    ) {
 8491        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8492            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8493        }
 8494    }
 8495
 8496    pub fn context_menu_prev(
 8497        &mut self,
 8498        _: &ContextMenuPrev,
 8499        _window: &mut Window,
 8500        cx: &mut Context<Self>,
 8501    ) {
 8502        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8503            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8504        }
 8505    }
 8506
 8507    pub fn context_menu_next(
 8508        &mut self,
 8509        _: &ContextMenuNext,
 8510        _window: &mut Window,
 8511        cx: &mut Context<Self>,
 8512    ) {
 8513        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8514            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8515        }
 8516    }
 8517
 8518    pub fn context_menu_last(
 8519        &mut self,
 8520        _: &ContextMenuLast,
 8521        _window: &mut Window,
 8522        cx: &mut Context<Self>,
 8523    ) {
 8524        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8525            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8526        }
 8527    }
 8528
 8529    pub fn move_to_previous_word_start(
 8530        &mut self,
 8531        _: &MoveToPreviousWordStart,
 8532        window: &mut Window,
 8533        cx: &mut Context<Self>,
 8534    ) {
 8535        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8536            s.move_cursors_with(|map, head, _| {
 8537                (
 8538                    movement::previous_word_start(map, head),
 8539                    SelectionGoal::None,
 8540                )
 8541            });
 8542        })
 8543    }
 8544
 8545    pub fn move_to_previous_subword_start(
 8546        &mut self,
 8547        _: &MoveToPreviousSubwordStart,
 8548        window: &mut Window,
 8549        cx: &mut Context<Self>,
 8550    ) {
 8551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8552            s.move_cursors_with(|map, head, _| {
 8553                (
 8554                    movement::previous_subword_start(map, head),
 8555                    SelectionGoal::None,
 8556                )
 8557            });
 8558        })
 8559    }
 8560
 8561    pub fn select_to_previous_word_start(
 8562        &mut self,
 8563        _: &SelectToPreviousWordStart,
 8564        window: &mut Window,
 8565        cx: &mut Context<Self>,
 8566    ) {
 8567        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8568            s.move_heads_with(|map, head, _| {
 8569                (
 8570                    movement::previous_word_start(map, head),
 8571                    SelectionGoal::None,
 8572                )
 8573            });
 8574        })
 8575    }
 8576
 8577    pub fn select_to_previous_subword_start(
 8578        &mut self,
 8579        _: &SelectToPreviousSubwordStart,
 8580        window: &mut Window,
 8581        cx: &mut Context<Self>,
 8582    ) {
 8583        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584            s.move_heads_with(|map, head, _| {
 8585                (
 8586                    movement::previous_subword_start(map, head),
 8587                    SelectionGoal::None,
 8588                )
 8589            });
 8590        })
 8591    }
 8592
 8593    pub fn delete_to_previous_word_start(
 8594        &mut self,
 8595        action: &DeleteToPreviousWordStart,
 8596        window: &mut Window,
 8597        cx: &mut Context<Self>,
 8598    ) {
 8599        self.transact(window, cx, |this, window, cx| {
 8600            this.select_autoclose_pair(window, cx);
 8601            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8602                let line_mode = s.line_mode;
 8603                s.move_with(|map, selection| {
 8604                    if selection.is_empty() && !line_mode {
 8605                        let cursor = if action.ignore_newlines {
 8606                            movement::previous_word_start(map, selection.head())
 8607                        } else {
 8608                            movement::previous_word_start_or_newline(map, selection.head())
 8609                        };
 8610                        selection.set_head(cursor, SelectionGoal::None);
 8611                    }
 8612                });
 8613            });
 8614            this.insert("", window, cx);
 8615        });
 8616    }
 8617
 8618    pub fn delete_to_previous_subword_start(
 8619        &mut self,
 8620        _: &DeleteToPreviousSubwordStart,
 8621        window: &mut Window,
 8622        cx: &mut Context<Self>,
 8623    ) {
 8624        self.transact(window, cx, |this, window, cx| {
 8625            this.select_autoclose_pair(window, cx);
 8626            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8627                let line_mode = s.line_mode;
 8628                s.move_with(|map, selection| {
 8629                    if selection.is_empty() && !line_mode {
 8630                        let cursor = movement::previous_subword_start(map, selection.head());
 8631                        selection.set_head(cursor, SelectionGoal::None);
 8632                    }
 8633                });
 8634            });
 8635            this.insert("", window, cx);
 8636        });
 8637    }
 8638
 8639    pub fn move_to_next_word_end(
 8640        &mut self,
 8641        _: &MoveToNextWordEnd,
 8642        window: &mut Window,
 8643        cx: &mut Context<Self>,
 8644    ) {
 8645        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8646            s.move_cursors_with(|map, head, _| {
 8647                (movement::next_word_end(map, head), SelectionGoal::None)
 8648            });
 8649        })
 8650    }
 8651
 8652    pub fn move_to_next_subword_end(
 8653        &mut self,
 8654        _: &MoveToNextSubwordEnd,
 8655        window: &mut Window,
 8656        cx: &mut Context<Self>,
 8657    ) {
 8658        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8659            s.move_cursors_with(|map, head, _| {
 8660                (movement::next_subword_end(map, head), SelectionGoal::None)
 8661            });
 8662        })
 8663    }
 8664
 8665    pub fn select_to_next_word_end(
 8666        &mut self,
 8667        _: &SelectToNextWordEnd,
 8668        window: &mut Window,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8672            s.move_heads_with(|map, head, _| {
 8673                (movement::next_word_end(map, head), SelectionGoal::None)
 8674            });
 8675        })
 8676    }
 8677
 8678    pub fn select_to_next_subword_end(
 8679        &mut self,
 8680        _: &SelectToNextSubwordEnd,
 8681        window: &mut Window,
 8682        cx: &mut Context<Self>,
 8683    ) {
 8684        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8685            s.move_heads_with(|map, head, _| {
 8686                (movement::next_subword_end(map, head), SelectionGoal::None)
 8687            });
 8688        })
 8689    }
 8690
 8691    pub fn delete_to_next_word_end(
 8692        &mut self,
 8693        action: &DeleteToNextWordEnd,
 8694        window: &mut Window,
 8695        cx: &mut Context<Self>,
 8696    ) {
 8697        self.transact(window, cx, |this, window, cx| {
 8698            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8699                let line_mode = s.line_mode;
 8700                s.move_with(|map, selection| {
 8701                    if selection.is_empty() && !line_mode {
 8702                        let cursor = if action.ignore_newlines {
 8703                            movement::next_word_end(map, selection.head())
 8704                        } else {
 8705                            movement::next_word_end_or_newline(map, selection.head())
 8706                        };
 8707                        selection.set_head(cursor, SelectionGoal::None);
 8708                    }
 8709                });
 8710            });
 8711            this.insert("", window, cx);
 8712        });
 8713    }
 8714
 8715    pub fn delete_to_next_subword_end(
 8716        &mut self,
 8717        _: &DeleteToNextSubwordEnd,
 8718        window: &mut Window,
 8719        cx: &mut Context<Self>,
 8720    ) {
 8721        self.transact(window, cx, |this, window, cx| {
 8722            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8723                s.move_with(|map, selection| {
 8724                    if selection.is_empty() {
 8725                        let cursor = movement::next_subword_end(map, selection.head());
 8726                        selection.set_head(cursor, SelectionGoal::None);
 8727                    }
 8728                });
 8729            });
 8730            this.insert("", window, cx);
 8731        });
 8732    }
 8733
 8734    pub fn move_to_beginning_of_line(
 8735        &mut self,
 8736        action: &MoveToBeginningOfLine,
 8737        window: &mut Window,
 8738        cx: &mut Context<Self>,
 8739    ) {
 8740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741            s.move_cursors_with(|map, head, _| {
 8742                (
 8743                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8744                    SelectionGoal::None,
 8745                )
 8746            });
 8747        })
 8748    }
 8749
 8750    pub fn select_to_beginning_of_line(
 8751        &mut self,
 8752        action: &SelectToBeginningOfLine,
 8753        window: &mut Window,
 8754        cx: &mut Context<Self>,
 8755    ) {
 8756        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8757            s.move_heads_with(|map, head, _| {
 8758                (
 8759                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8760                    SelectionGoal::None,
 8761                )
 8762            });
 8763        });
 8764    }
 8765
 8766    pub fn delete_to_beginning_of_line(
 8767        &mut self,
 8768        _: &DeleteToBeginningOfLine,
 8769        window: &mut Window,
 8770        cx: &mut Context<Self>,
 8771    ) {
 8772        self.transact(window, cx, |this, window, cx| {
 8773            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8774                s.move_with(|_, selection| {
 8775                    selection.reversed = true;
 8776                });
 8777            });
 8778
 8779            this.select_to_beginning_of_line(
 8780                &SelectToBeginningOfLine {
 8781                    stop_at_soft_wraps: false,
 8782                },
 8783                window,
 8784                cx,
 8785            );
 8786            this.backspace(&Backspace, window, cx);
 8787        });
 8788    }
 8789
 8790    pub fn move_to_end_of_line(
 8791        &mut self,
 8792        action: &MoveToEndOfLine,
 8793        window: &mut Window,
 8794        cx: &mut Context<Self>,
 8795    ) {
 8796        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8797            s.move_cursors_with(|map, head, _| {
 8798                (
 8799                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8800                    SelectionGoal::None,
 8801                )
 8802            });
 8803        })
 8804    }
 8805
 8806    pub fn select_to_end_of_line(
 8807        &mut self,
 8808        action: &SelectToEndOfLine,
 8809        window: &mut Window,
 8810        cx: &mut Context<Self>,
 8811    ) {
 8812        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8813            s.move_heads_with(|map, head, _| {
 8814                (
 8815                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8816                    SelectionGoal::None,
 8817                )
 8818            });
 8819        })
 8820    }
 8821
 8822    pub fn delete_to_end_of_line(
 8823        &mut self,
 8824        _: &DeleteToEndOfLine,
 8825        window: &mut Window,
 8826        cx: &mut Context<Self>,
 8827    ) {
 8828        self.transact(window, cx, |this, window, cx| {
 8829            this.select_to_end_of_line(
 8830                &SelectToEndOfLine {
 8831                    stop_at_soft_wraps: false,
 8832                },
 8833                window,
 8834                cx,
 8835            );
 8836            this.delete(&Delete, window, cx);
 8837        });
 8838    }
 8839
 8840    pub fn cut_to_end_of_line(
 8841        &mut self,
 8842        _: &CutToEndOfLine,
 8843        window: &mut Window,
 8844        cx: &mut Context<Self>,
 8845    ) {
 8846        self.transact(window, cx, |this, window, cx| {
 8847            this.select_to_end_of_line(
 8848                &SelectToEndOfLine {
 8849                    stop_at_soft_wraps: false,
 8850                },
 8851                window,
 8852                cx,
 8853            );
 8854            this.cut(&Cut, window, cx);
 8855        });
 8856    }
 8857
 8858    pub fn move_to_start_of_paragraph(
 8859        &mut self,
 8860        _: &MoveToStartOfParagraph,
 8861        window: &mut Window,
 8862        cx: &mut Context<Self>,
 8863    ) {
 8864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8865            cx.propagate();
 8866            return;
 8867        }
 8868
 8869        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8870            s.move_with(|map, selection| {
 8871                selection.collapse_to(
 8872                    movement::start_of_paragraph(map, selection.head(), 1),
 8873                    SelectionGoal::None,
 8874                )
 8875            });
 8876        })
 8877    }
 8878
 8879    pub fn move_to_end_of_paragraph(
 8880        &mut self,
 8881        _: &MoveToEndOfParagraph,
 8882        window: &mut Window,
 8883        cx: &mut Context<Self>,
 8884    ) {
 8885        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8886            cx.propagate();
 8887            return;
 8888        }
 8889
 8890        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8891            s.move_with(|map, selection| {
 8892                selection.collapse_to(
 8893                    movement::end_of_paragraph(map, selection.head(), 1),
 8894                    SelectionGoal::None,
 8895                )
 8896            });
 8897        })
 8898    }
 8899
 8900    pub fn select_to_start_of_paragraph(
 8901        &mut self,
 8902        _: &SelectToStartOfParagraph,
 8903        window: &mut Window,
 8904        cx: &mut Context<Self>,
 8905    ) {
 8906        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8907            cx.propagate();
 8908            return;
 8909        }
 8910
 8911        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8912            s.move_heads_with(|map, head, _| {
 8913                (
 8914                    movement::start_of_paragraph(map, head, 1),
 8915                    SelectionGoal::None,
 8916                )
 8917            });
 8918        })
 8919    }
 8920
 8921    pub fn select_to_end_of_paragraph(
 8922        &mut self,
 8923        _: &SelectToEndOfParagraph,
 8924        window: &mut Window,
 8925        cx: &mut Context<Self>,
 8926    ) {
 8927        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8928            cx.propagate();
 8929            return;
 8930        }
 8931
 8932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8933            s.move_heads_with(|map, head, _| {
 8934                (
 8935                    movement::end_of_paragraph(map, head, 1),
 8936                    SelectionGoal::None,
 8937                )
 8938            });
 8939        })
 8940    }
 8941
 8942    pub fn move_to_beginning(
 8943        &mut self,
 8944        _: &MoveToBeginning,
 8945        window: &mut Window,
 8946        cx: &mut Context<Self>,
 8947    ) {
 8948        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8949            cx.propagate();
 8950            return;
 8951        }
 8952
 8953        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8954            s.select_ranges(vec![0..0]);
 8955        });
 8956    }
 8957
 8958    pub fn select_to_beginning(
 8959        &mut self,
 8960        _: &SelectToBeginning,
 8961        window: &mut Window,
 8962        cx: &mut Context<Self>,
 8963    ) {
 8964        let mut selection = self.selections.last::<Point>(cx);
 8965        selection.set_head(Point::zero(), SelectionGoal::None);
 8966
 8967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8968            s.select(vec![selection]);
 8969        });
 8970    }
 8971
 8972    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8973        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8974            cx.propagate();
 8975            return;
 8976        }
 8977
 8978        let cursor = self.buffer.read(cx).read(cx).len();
 8979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8980            s.select_ranges(vec![cursor..cursor])
 8981        });
 8982    }
 8983
 8984    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8985        self.nav_history = nav_history;
 8986    }
 8987
 8988    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8989        self.nav_history.as_ref()
 8990    }
 8991
 8992    fn push_to_nav_history(
 8993        &mut self,
 8994        cursor_anchor: Anchor,
 8995        new_position: Option<Point>,
 8996        cx: &mut Context<Self>,
 8997    ) {
 8998        if let Some(nav_history) = self.nav_history.as_mut() {
 8999            let buffer = self.buffer.read(cx).read(cx);
 9000            let cursor_position = cursor_anchor.to_point(&buffer);
 9001            let scroll_state = self.scroll_manager.anchor();
 9002            let scroll_top_row = scroll_state.top_row(&buffer);
 9003            drop(buffer);
 9004
 9005            if let Some(new_position) = new_position {
 9006                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9007                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9008                    return;
 9009                }
 9010            }
 9011
 9012            nav_history.push(
 9013                Some(NavigationData {
 9014                    cursor_anchor,
 9015                    cursor_position,
 9016                    scroll_anchor: scroll_state,
 9017                    scroll_top_row,
 9018                }),
 9019                cx,
 9020            );
 9021        }
 9022    }
 9023
 9024    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9025        let buffer = self.buffer.read(cx).snapshot(cx);
 9026        let mut selection = self.selections.first::<usize>(cx);
 9027        selection.set_head(buffer.len(), SelectionGoal::None);
 9028        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9029            s.select(vec![selection]);
 9030        });
 9031    }
 9032
 9033    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9034        let end = self.buffer.read(cx).read(cx).len();
 9035        self.change_selections(None, window, cx, |s| {
 9036            s.select_ranges(vec![0..end]);
 9037        });
 9038    }
 9039
 9040    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9042        let mut selections = self.selections.all::<Point>(cx);
 9043        let max_point = display_map.buffer_snapshot.max_point();
 9044        for selection in &mut selections {
 9045            let rows = selection.spanned_rows(true, &display_map);
 9046            selection.start = Point::new(rows.start.0, 0);
 9047            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9048            selection.reversed = false;
 9049        }
 9050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9051            s.select(selections);
 9052        });
 9053    }
 9054
 9055    pub fn split_selection_into_lines(
 9056        &mut self,
 9057        _: &SplitSelectionIntoLines,
 9058        window: &mut Window,
 9059        cx: &mut Context<Self>,
 9060    ) {
 9061        let mut to_unfold = Vec::new();
 9062        let mut new_selection_ranges = Vec::new();
 9063        {
 9064            let selections = self.selections.all::<Point>(cx);
 9065            let buffer = self.buffer.read(cx).read(cx);
 9066            for selection in selections {
 9067                for row in selection.start.row..selection.end.row {
 9068                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9069                    new_selection_ranges.push(cursor..cursor);
 9070                }
 9071                new_selection_ranges.push(selection.end..selection.end);
 9072                to_unfold.push(selection.start..selection.end);
 9073            }
 9074        }
 9075        self.unfold_ranges(&to_unfold, true, true, cx);
 9076        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9077            s.select_ranges(new_selection_ranges);
 9078        });
 9079    }
 9080
 9081    pub fn add_selection_above(
 9082        &mut self,
 9083        _: &AddSelectionAbove,
 9084        window: &mut Window,
 9085        cx: &mut Context<Self>,
 9086    ) {
 9087        self.add_selection(true, window, cx);
 9088    }
 9089
 9090    pub fn add_selection_below(
 9091        &mut self,
 9092        _: &AddSelectionBelow,
 9093        window: &mut Window,
 9094        cx: &mut Context<Self>,
 9095    ) {
 9096        self.add_selection(false, window, cx);
 9097    }
 9098
 9099    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9100        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9101        let mut selections = self.selections.all::<Point>(cx);
 9102        let text_layout_details = self.text_layout_details(window);
 9103        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9104            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9105            let range = oldest_selection.display_range(&display_map).sorted();
 9106
 9107            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9108            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9109            let positions = start_x.min(end_x)..start_x.max(end_x);
 9110
 9111            selections.clear();
 9112            let mut stack = Vec::new();
 9113            for row in range.start.row().0..=range.end.row().0 {
 9114                if let Some(selection) = self.selections.build_columnar_selection(
 9115                    &display_map,
 9116                    DisplayRow(row),
 9117                    &positions,
 9118                    oldest_selection.reversed,
 9119                    &text_layout_details,
 9120                ) {
 9121                    stack.push(selection.id);
 9122                    selections.push(selection);
 9123                }
 9124            }
 9125
 9126            if above {
 9127                stack.reverse();
 9128            }
 9129
 9130            AddSelectionsState { above, stack }
 9131        });
 9132
 9133        let last_added_selection = *state.stack.last().unwrap();
 9134        let mut new_selections = Vec::new();
 9135        if above == state.above {
 9136            let end_row = if above {
 9137                DisplayRow(0)
 9138            } else {
 9139                display_map.max_point().row()
 9140            };
 9141
 9142            'outer: for selection in selections {
 9143                if selection.id == last_added_selection {
 9144                    let range = selection.display_range(&display_map).sorted();
 9145                    debug_assert_eq!(range.start.row(), range.end.row());
 9146                    let mut row = range.start.row();
 9147                    let positions =
 9148                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9149                            px(start)..px(end)
 9150                        } else {
 9151                            let start_x =
 9152                                display_map.x_for_display_point(range.start, &text_layout_details);
 9153                            let end_x =
 9154                                display_map.x_for_display_point(range.end, &text_layout_details);
 9155                            start_x.min(end_x)..start_x.max(end_x)
 9156                        };
 9157
 9158                    while row != end_row {
 9159                        if above {
 9160                            row.0 -= 1;
 9161                        } else {
 9162                            row.0 += 1;
 9163                        }
 9164
 9165                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9166                            &display_map,
 9167                            row,
 9168                            &positions,
 9169                            selection.reversed,
 9170                            &text_layout_details,
 9171                        ) {
 9172                            state.stack.push(new_selection.id);
 9173                            if above {
 9174                                new_selections.push(new_selection);
 9175                                new_selections.push(selection);
 9176                            } else {
 9177                                new_selections.push(selection);
 9178                                new_selections.push(new_selection);
 9179                            }
 9180
 9181                            continue 'outer;
 9182                        }
 9183                    }
 9184                }
 9185
 9186                new_selections.push(selection);
 9187            }
 9188        } else {
 9189            new_selections = selections;
 9190            new_selections.retain(|s| s.id != last_added_selection);
 9191            state.stack.pop();
 9192        }
 9193
 9194        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9195            s.select(new_selections);
 9196        });
 9197        if state.stack.len() > 1 {
 9198            self.add_selections_state = Some(state);
 9199        }
 9200    }
 9201
 9202    pub fn select_next_match_internal(
 9203        &mut self,
 9204        display_map: &DisplaySnapshot,
 9205        replace_newest: bool,
 9206        autoscroll: Option<Autoscroll>,
 9207        window: &mut Window,
 9208        cx: &mut Context<Self>,
 9209    ) -> Result<()> {
 9210        fn select_next_match_ranges(
 9211            this: &mut Editor,
 9212            range: Range<usize>,
 9213            replace_newest: bool,
 9214            auto_scroll: Option<Autoscroll>,
 9215            window: &mut Window,
 9216            cx: &mut Context<Editor>,
 9217        ) {
 9218            this.unfold_ranges(&[range.clone()], false, true, cx);
 9219            this.change_selections(auto_scroll, window, cx, |s| {
 9220                if replace_newest {
 9221                    s.delete(s.newest_anchor().id);
 9222                }
 9223                s.insert_range(range.clone());
 9224            });
 9225        }
 9226
 9227        let buffer = &display_map.buffer_snapshot;
 9228        let mut selections = self.selections.all::<usize>(cx);
 9229        if let Some(mut select_next_state) = self.select_next_state.take() {
 9230            let query = &select_next_state.query;
 9231            if !select_next_state.done {
 9232                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9233                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9234                let mut next_selected_range = None;
 9235
 9236                let bytes_after_last_selection =
 9237                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9238                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9239                let query_matches = query
 9240                    .stream_find_iter(bytes_after_last_selection)
 9241                    .map(|result| (last_selection.end, result))
 9242                    .chain(
 9243                        query
 9244                            .stream_find_iter(bytes_before_first_selection)
 9245                            .map(|result| (0, result)),
 9246                    );
 9247
 9248                for (start_offset, query_match) in query_matches {
 9249                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9250                    let offset_range =
 9251                        start_offset + query_match.start()..start_offset + query_match.end();
 9252                    let display_range = offset_range.start.to_display_point(display_map)
 9253                        ..offset_range.end.to_display_point(display_map);
 9254
 9255                    if !select_next_state.wordwise
 9256                        || (!movement::is_inside_word(display_map, display_range.start)
 9257                            && !movement::is_inside_word(display_map, display_range.end))
 9258                    {
 9259                        // TODO: This is n^2, because we might check all the selections
 9260                        if !selections
 9261                            .iter()
 9262                            .any(|selection| selection.range().overlaps(&offset_range))
 9263                        {
 9264                            next_selected_range = Some(offset_range);
 9265                            break;
 9266                        }
 9267                    }
 9268                }
 9269
 9270                if let Some(next_selected_range) = next_selected_range {
 9271                    select_next_match_ranges(
 9272                        self,
 9273                        next_selected_range,
 9274                        replace_newest,
 9275                        autoscroll,
 9276                        window,
 9277                        cx,
 9278                    );
 9279                } else {
 9280                    select_next_state.done = true;
 9281                }
 9282            }
 9283
 9284            self.select_next_state = Some(select_next_state);
 9285        } else {
 9286            let mut only_carets = true;
 9287            let mut same_text_selected = true;
 9288            let mut selected_text = None;
 9289
 9290            let mut selections_iter = selections.iter().peekable();
 9291            while let Some(selection) = selections_iter.next() {
 9292                if selection.start != selection.end {
 9293                    only_carets = false;
 9294                }
 9295
 9296                if same_text_selected {
 9297                    if selected_text.is_none() {
 9298                        selected_text =
 9299                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9300                    }
 9301
 9302                    if let Some(next_selection) = selections_iter.peek() {
 9303                        if next_selection.range().len() == selection.range().len() {
 9304                            let next_selected_text = buffer
 9305                                .text_for_range(next_selection.range())
 9306                                .collect::<String>();
 9307                            if Some(next_selected_text) != selected_text {
 9308                                same_text_selected = false;
 9309                                selected_text = None;
 9310                            }
 9311                        } else {
 9312                            same_text_selected = false;
 9313                            selected_text = None;
 9314                        }
 9315                    }
 9316                }
 9317            }
 9318
 9319            if only_carets {
 9320                for selection in &mut selections {
 9321                    let word_range = movement::surrounding_word(
 9322                        display_map,
 9323                        selection.start.to_display_point(display_map),
 9324                    );
 9325                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9326                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9327                    selection.goal = SelectionGoal::None;
 9328                    selection.reversed = false;
 9329                    select_next_match_ranges(
 9330                        self,
 9331                        selection.start..selection.end,
 9332                        replace_newest,
 9333                        autoscroll,
 9334                        window,
 9335                        cx,
 9336                    );
 9337                }
 9338
 9339                if selections.len() == 1 {
 9340                    let selection = selections
 9341                        .last()
 9342                        .expect("ensured that there's only one selection");
 9343                    let query = buffer
 9344                        .text_for_range(selection.start..selection.end)
 9345                        .collect::<String>();
 9346                    let is_empty = query.is_empty();
 9347                    let select_state = SelectNextState {
 9348                        query: AhoCorasick::new(&[query])?,
 9349                        wordwise: true,
 9350                        done: is_empty,
 9351                    };
 9352                    self.select_next_state = Some(select_state);
 9353                } else {
 9354                    self.select_next_state = None;
 9355                }
 9356            } else if let Some(selected_text) = selected_text {
 9357                self.select_next_state = Some(SelectNextState {
 9358                    query: AhoCorasick::new(&[selected_text])?,
 9359                    wordwise: false,
 9360                    done: false,
 9361                });
 9362                self.select_next_match_internal(
 9363                    display_map,
 9364                    replace_newest,
 9365                    autoscroll,
 9366                    window,
 9367                    cx,
 9368                )?;
 9369            }
 9370        }
 9371        Ok(())
 9372    }
 9373
 9374    pub fn select_all_matches(
 9375        &mut self,
 9376        _action: &SelectAllMatches,
 9377        window: &mut Window,
 9378        cx: &mut Context<Self>,
 9379    ) -> Result<()> {
 9380        self.push_to_selection_history();
 9381        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9382
 9383        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9384        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9385            return Ok(());
 9386        };
 9387        if select_next_state.done {
 9388            return Ok(());
 9389        }
 9390
 9391        let mut new_selections = self.selections.all::<usize>(cx);
 9392
 9393        let buffer = &display_map.buffer_snapshot;
 9394        let query_matches = select_next_state
 9395            .query
 9396            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9397
 9398        for query_match in query_matches {
 9399            let query_match = query_match.unwrap(); // can only fail due to I/O
 9400            let offset_range = query_match.start()..query_match.end();
 9401            let display_range = offset_range.start.to_display_point(&display_map)
 9402                ..offset_range.end.to_display_point(&display_map);
 9403
 9404            if !select_next_state.wordwise
 9405                || (!movement::is_inside_word(&display_map, display_range.start)
 9406                    && !movement::is_inside_word(&display_map, display_range.end))
 9407            {
 9408                self.selections.change_with(cx, |selections| {
 9409                    new_selections.push(Selection {
 9410                        id: selections.new_selection_id(),
 9411                        start: offset_range.start,
 9412                        end: offset_range.end,
 9413                        reversed: false,
 9414                        goal: SelectionGoal::None,
 9415                    });
 9416                });
 9417            }
 9418        }
 9419
 9420        new_selections.sort_by_key(|selection| selection.start);
 9421        let mut ix = 0;
 9422        while ix + 1 < new_selections.len() {
 9423            let current_selection = &new_selections[ix];
 9424            let next_selection = &new_selections[ix + 1];
 9425            if current_selection.range().overlaps(&next_selection.range()) {
 9426                if current_selection.id < next_selection.id {
 9427                    new_selections.remove(ix + 1);
 9428                } else {
 9429                    new_selections.remove(ix);
 9430                }
 9431            } else {
 9432                ix += 1;
 9433            }
 9434        }
 9435
 9436        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9437
 9438        for selection in new_selections.iter_mut() {
 9439            selection.reversed = reversed;
 9440        }
 9441
 9442        select_next_state.done = true;
 9443        self.unfold_ranges(
 9444            &new_selections
 9445                .iter()
 9446                .map(|selection| selection.range())
 9447                .collect::<Vec<_>>(),
 9448            false,
 9449            false,
 9450            cx,
 9451        );
 9452        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9453            selections.select(new_selections)
 9454        });
 9455
 9456        Ok(())
 9457    }
 9458
 9459    pub fn select_next(
 9460        &mut self,
 9461        action: &SelectNext,
 9462        window: &mut Window,
 9463        cx: &mut Context<Self>,
 9464    ) -> Result<()> {
 9465        self.push_to_selection_history();
 9466        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9467        self.select_next_match_internal(
 9468            &display_map,
 9469            action.replace_newest,
 9470            Some(Autoscroll::newest()),
 9471            window,
 9472            cx,
 9473        )?;
 9474        Ok(())
 9475    }
 9476
 9477    pub fn select_previous(
 9478        &mut self,
 9479        action: &SelectPrevious,
 9480        window: &mut Window,
 9481        cx: &mut Context<Self>,
 9482    ) -> Result<()> {
 9483        self.push_to_selection_history();
 9484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9485        let buffer = &display_map.buffer_snapshot;
 9486        let mut selections = self.selections.all::<usize>(cx);
 9487        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9488            let query = &select_prev_state.query;
 9489            if !select_prev_state.done {
 9490                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9491                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9492                let mut next_selected_range = None;
 9493                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9494                let bytes_before_last_selection =
 9495                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9496                let bytes_after_first_selection =
 9497                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9498                let query_matches = query
 9499                    .stream_find_iter(bytes_before_last_selection)
 9500                    .map(|result| (last_selection.start, result))
 9501                    .chain(
 9502                        query
 9503                            .stream_find_iter(bytes_after_first_selection)
 9504                            .map(|result| (buffer.len(), result)),
 9505                    );
 9506                for (end_offset, query_match) in query_matches {
 9507                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9508                    let offset_range =
 9509                        end_offset - query_match.end()..end_offset - query_match.start();
 9510                    let display_range = offset_range.start.to_display_point(&display_map)
 9511                        ..offset_range.end.to_display_point(&display_map);
 9512
 9513                    if !select_prev_state.wordwise
 9514                        || (!movement::is_inside_word(&display_map, display_range.start)
 9515                            && !movement::is_inside_word(&display_map, display_range.end))
 9516                    {
 9517                        next_selected_range = Some(offset_range);
 9518                        break;
 9519                    }
 9520                }
 9521
 9522                if let Some(next_selected_range) = next_selected_range {
 9523                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9524                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9525                        if action.replace_newest {
 9526                            s.delete(s.newest_anchor().id);
 9527                        }
 9528                        s.insert_range(next_selected_range);
 9529                    });
 9530                } else {
 9531                    select_prev_state.done = true;
 9532                }
 9533            }
 9534
 9535            self.select_prev_state = Some(select_prev_state);
 9536        } else {
 9537            let mut only_carets = true;
 9538            let mut same_text_selected = true;
 9539            let mut selected_text = None;
 9540
 9541            let mut selections_iter = selections.iter().peekable();
 9542            while let Some(selection) = selections_iter.next() {
 9543                if selection.start != selection.end {
 9544                    only_carets = false;
 9545                }
 9546
 9547                if same_text_selected {
 9548                    if selected_text.is_none() {
 9549                        selected_text =
 9550                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9551                    }
 9552
 9553                    if let Some(next_selection) = selections_iter.peek() {
 9554                        if next_selection.range().len() == selection.range().len() {
 9555                            let next_selected_text = buffer
 9556                                .text_for_range(next_selection.range())
 9557                                .collect::<String>();
 9558                            if Some(next_selected_text) != selected_text {
 9559                                same_text_selected = false;
 9560                                selected_text = None;
 9561                            }
 9562                        } else {
 9563                            same_text_selected = false;
 9564                            selected_text = None;
 9565                        }
 9566                    }
 9567                }
 9568            }
 9569
 9570            if only_carets {
 9571                for selection in &mut selections {
 9572                    let word_range = movement::surrounding_word(
 9573                        &display_map,
 9574                        selection.start.to_display_point(&display_map),
 9575                    );
 9576                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9577                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9578                    selection.goal = SelectionGoal::None;
 9579                    selection.reversed = false;
 9580                }
 9581                if selections.len() == 1 {
 9582                    let selection = selections
 9583                        .last()
 9584                        .expect("ensured that there's only one selection");
 9585                    let query = buffer
 9586                        .text_for_range(selection.start..selection.end)
 9587                        .collect::<String>();
 9588                    let is_empty = query.is_empty();
 9589                    let select_state = SelectNextState {
 9590                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9591                        wordwise: true,
 9592                        done: is_empty,
 9593                    };
 9594                    self.select_prev_state = Some(select_state);
 9595                } else {
 9596                    self.select_prev_state = None;
 9597                }
 9598
 9599                self.unfold_ranges(
 9600                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9601                    false,
 9602                    true,
 9603                    cx,
 9604                );
 9605                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9606                    s.select(selections);
 9607                });
 9608            } else if let Some(selected_text) = selected_text {
 9609                self.select_prev_state = Some(SelectNextState {
 9610                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9611                    wordwise: false,
 9612                    done: false,
 9613                });
 9614                self.select_previous(action, window, cx)?;
 9615            }
 9616        }
 9617        Ok(())
 9618    }
 9619
 9620    pub fn toggle_comments(
 9621        &mut self,
 9622        action: &ToggleComments,
 9623        window: &mut Window,
 9624        cx: &mut Context<Self>,
 9625    ) {
 9626        if self.read_only(cx) {
 9627            return;
 9628        }
 9629        let text_layout_details = &self.text_layout_details(window);
 9630        self.transact(window, cx, |this, window, cx| {
 9631            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9632            let mut edits = Vec::new();
 9633            let mut selection_edit_ranges = Vec::new();
 9634            let mut last_toggled_row = None;
 9635            let snapshot = this.buffer.read(cx).read(cx);
 9636            let empty_str: Arc<str> = Arc::default();
 9637            let mut suffixes_inserted = Vec::new();
 9638            let ignore_indent = action.ignore_indent;
 9639
 9640            fn comment_prefix_range(
 9641                snapshot: &MultiBufferSnapshot,
 9642                row: MultiBufferRow,
 9643                comment_prefix: &str,
 9644                comment_prefix_whitespace: &str,
 9645                ignore_indent: bool,
 9646            ) -> Range<Point> {
 9647                let indent_size = if ignore_indent {
 9648                    0
 9649                } else {
 9650                    snapshot.indent_size_for_line(row).len
 9651                };
 9652
 9653                let start = Point::new(row.0, indent_size);
 9654
 9655                let mut line_bytes = snapshot
 9656                    .bytes_in_range(start..snapshot.max_point())
 9657                    .flatten()
 9658                    .copied();
 9659
 9660                // If this line currently begins with the line comment prefix, then record
 9661                // the range containing the prefix.
 9662                if line_bytes
 9663                    .by_ref()
 9664                    .take(comment_prefix.len())
 9665                    .eq(comment_prefix.bytes())
 9666                {
 9667                    // Include any whitespace that matches the comment prefix.
 9668                    let matching_whitespace_len = line_bytes
 9669                        .zip(comment_prefix_whitespace.bytes())
 9670                        .take_while(|(a, b)| a == b)
 9671                        .count() as u32;
 9672                    let end = Point::new(
 9673                        start.row,
 9674                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9675                    );
 9676                    start..end
 9677                } else {
 9678                    start..start
 9679                }
 9680            }
 9681
 9682            fn comment_suffix_range(
 9683                snapshot: &MultiBufferSnapshot,
 9684                row: MultiBufferRow,
 9685                comment_suffix: &str,
 9686                comment_suffix_has_leading_space: bool,
 9687            ) -> Range<Point> {
 9688                let end = Point::new(row.0, snapshot.line_len(row));
 9689                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9690
 9691                let mut line_end_bytes = snapshot
 9692                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9693                    .flatten()
 9694                    .copied();
 9695
 9696                let leading_space_len = if suffix_start_column > 0
 9697                    && line_end_bytes.next() == Some(b' ')
 9698                    && comment_suffix_has_leading_space
 9699                {
 9700                    1
 9701                } else {
 9702                    0
 9703                };
 9704
 9705                // If this line currently begins with the line comment prefix, then record
 9706                // the range containing the prefix.
 9707                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9708                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9709                    start..end
 9710                } else {
 9711                    end..end
 9712                }
 9713            }
 9714
 9715            // TODO: Handle selections that cross excerpts
 9716            for selection in &mut selections {
 9717                let start_column = snapshot
 9718                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9719                    .len;
 9720                let language = if let Some(language) =
 9721                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9722                {
 9723                    language
 9724                } else {
 9725                    continue;
 9726                };
 9727
 9728                selection_edit_ranges.clear();
 9729
 9730                // If multiple selections contain a given row, avoid processing that
 9731                // row more than once.
 9732                let mut start_row = MultiBufferRow(selection.start.row);
 9733                if last_toggled_row == Some(start_row) {
 9734                    start_row = start_row.next_row();
 9735                }
 9736                let end_row =
 9737                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9738                        MultiBufferRow(selection.end.row - 1)
 9739                    } else {
 9740                        MultiBufferRow(selection.end.row)
 9741                    };
 9742                last_toggled_row = Some(end_row);
 9743
 9744                if start_row > end_row {
 9745                    continue;
 9746                }
 9747
 9748                // If the language has line comments, toggle those.
 9749                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9750
 9751                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9752                if ignore_indent {
 9753                    full_comment_prefixes = full_comment_prefixes
 9754                        .into_iter()
 9755                        .map(|s| Arc::from(s.trim_end()))
 9756                        .collect();
 9757                }
 9758
 9759                if !full_comment_prefixes.is_empty() {
 9760                    let first_prefix = full_comment_prefixes
 9761                        .first()
 9762                        .expect("prefixes is non-empty");
 9763                    let prefix_trimmed_lengths = full_comment_prefixes
 9764                        .iter()
 9765                        .map(|p| p.trim_end_matches(' ').len())
 9766                        .collect::<SmallVec<[usize; 4]>>();
 9767
 9768                    let mut all_selection_lines_are_comments = true;
 9769
 9770                    for row in start_row.0..=end_row.0 {
 9771                        let row = MultiBufferRow(row);
 9772                        if start_row < end_row && snapshot.is_line_blank(row) {
 9773                            continue;
 9774                        }
 9775
 9776                        let prefix_range = full_comment_prefixes
 9777                            .iter()
 9778                            .zip(prefix_trimmed_lengths.iter().copied())
 9779                            .map(|(prefix, trimmed_prefix_len)| {
 9780                                comment_prefix_range(
 9781                                    snapshot.deref(),
 9782                                    row,
 9783                                    &prefix[..trimmed_prefix_len],
 9784                                    &prefix[trimmed_prefix_len..],
 9785                                    ignore_indent,
 9786                                )
 9787                            })
 9788                            .max_by_key(|range| range.end.column - range.start.column)
 9789                            .expect("prefixes is non-empty");
 9790
 9791                        if prefix_range.is_empty() {
 9792                            all_selection_lines_are_comments = false;
 9793                        }
 9794
 9795                        selection_edit_ranges.push(prefix_range);
 9796                    }
 9797
 9798                    if all_selection_lines_are_comments {
 9799                        edits.extend(
 9800                            selection_edit_ranges
 9801                                .iter()
 9802                                .cloned()
 9803                                .map(|range| (range, empty_str.clone())),
 9804                        );
 9805                    } else {
 9806                        let min_column = selection_edit_ranges
 9807                            .iter()
 9808                            .map(|range| range.start.column)
 9809                            .min()
 9810                            .unwrap_or(0);
 9811                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9812                            let position = Point::new(range.start.row, min_column);
 9813                            (position..position, first_prefix.clone())
 9814                        }));
 9815                    }
 9816                } else if let Some((full_comment_prefix, comment_suffix)) =
 9817                    language.block_comment_delimiters()
 9818                {
 9819                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9820                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9821                    let prefix_range = comment_prefix_range(
 9822                        snapshot.deref(),
 9823                        start_row,
 9824                        comment_prefix,
 9825                        comment_prefix_whitespace,
 9826                        ignore_indent,
 9827                    );
 9828                    let suffix_range = comment_suffix_range(
 9829                        snapshot.deref(),
 9830                        end_row,
 9831                        comment_suffix.trim_start_matches(' '),
 9832                        comment_suffix.starts_with(' '),
 9833                    );
 9834
 9835                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9836                        edits.push((
 9837                            prefix_range.start..prefix_range.start,
 9838                            full_comment_prefix.clone(),
 9839                        ));
 9840                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9841                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9842                    } else {
 9843                        edits.push((prefix_range, empty_str.clone()));
 9844                        edits.push((suffix_range, empty_str.clone()));
 9845                    }
 9846                } else {
 9847                    continue;
 9848                }
 9849            }
 9850
 9851            drop(snapshot);
 9852            this.buffer.update(cx, |buffer, cx| {
 9853                buffer.edit(edits, None, cx);
 9854            });
 9855
 9856            // Adjust selections so that they end before any comment suffixes that
 9857            // were inserted.
 9858            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9859            let mut selections = this.selections.all::<Point>(cx);
 9860            let snapshot = this.buffer.read(cx).read(cx);
 9861            for selection in &mut selections {
 9862                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9863                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9864                        Ordering::Less => {
 9865                            suffixes_inserted.next();
 9866                            continue;
 9867                        }
 9868                        Ordering::Greater => break,
 9869                        Ordering::Equal => {
 9870                            if selection.end.column == snapshot.line_len(row) {
 9871                                if selection.is_empty() {
 9872                                    selection.start.column -= suffix_len as u32;
 9873                                }
 9874                                selection.end.column -= suffix_len as u32;
 9875                            }
 9876                            break;
 9877                        }
 9878                    }
 9879                }
 9880            }
 9881
 9882            drop(snapshot);
 9883            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9884                s.select(selections)
 9885            });
 9886
 9887            let selections = this.selections.all::<Point>(cx);
 9888            let selections_on_single_row = selections.windows(2).all(|selections| {
 9889                selections[0].start.row == selections[1].start.row
 9890                    && selections[0].end.row == selections[1].end.row
 9891                    && selections[0].start.row == selections[0].end.row
 9892            });
 9893            let selections_selecting = selections
 9894                .iter()
 9895                .any(|selection| selection.start != selection.end);
 9896            let advance_downwards = action.advance_downwards
 9897                && selections_on_single_row
 9898                && !selections_selecting
 9899                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9900
 9901            if advance_downwards {
 9902                let snapshot = this.buffer.read(cx).snapshot(cx);
 9903
 9904                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9905                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9906                        let mut point = display_point.to_point(display_snapshot);
 9907                        point.row += 1;
 9908                        point = snapshot.clip_point(point, Bias::Left);
 9909                        let display_point = point.to_display_point(display_snapshot);
 9910                        let goal = SelectionGoal::HorizontalPosition(
 9911                            display_snapshot
 9912                                .x_for_display_point(display_point, text_layout_details)
 9913                                .into(),
 9914                        );
 9915                        (display_point, goal)
 9916                    })
 9917                });
 9918            }
 9919        });
 9920    }
 9921
 9922    pub fn select_enclosing_symbol(
 9923        &mut self,
 9924        _: &SelectEnclosingSymbol,
 9925        window: &mut Window,
 9926        cx: &mut Context<Self>,
 9927    ) {
 9928        let buffer = self.buffer.read(cx).snapshot(cx);
 9929        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9930
 9931        fn update_selection(
 9932            selection: &Selection<usize>,
 9933            buffer_snap: &MultiBufferSnapshot,
 9934        ) -> Option<Selection<usize>> {
 9935            let cursor = selection.head();
 9936            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9937            for symbol in symbols.iter().rev() {
 9938                let start = symbol.range.start.to_offset(buffer_snap);
 9939                let end = symbol.range.end.to_offset(buffer_snap);
 9940                let new_range = start..end;
 9941                if start < selection.start || end > selection.end {
 9942                    return Some(Selection {
 9943                        id: selection.id,
 9944                        start: new_range.start,
 9945                        end: new_range.end,
 9946                        goal: SelectionGoal::None,
 9947                        reversed: selection.reversed,
 9948                    });
 9949                }
 9950            }
 9951            None
 9952        }
 9953
 9954        let mut selected_larger_symbol = false;
 9955        let new_selections = old_selections
 9956            .iter()
 9957            .map(|selection| match update_selection(selection, &buffer) {
 9958                Some(new_selection) => {
 9959                    if new_selection.range() != selection.range() {
 9960                        selected_larger_symbol = true;
 9961                    }
 9962                    new_selection
 9963                }
 9964                None => selection.clone(),
 9965            })
 9966            .collect::<Vec<_>>();
 9967
 9968        if selected_larger_symbol {
 9969            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9970                s.select(new_selections);
 9971            });
 9972        }
 9973    }
 9974
 9975    pub fn select_larger_syntax_node(
 9976        &mut self,
 9977        _: &SelectLargerSyntaxNode,
 9978        window: &mut Window,
 9979        cx: &mut Context<Self>,
 9980    ) {
 9981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9982        let buffer = self.buffer.read(cx).snapshot(cx);
 9983        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9984
 9985        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9986        let mut selected_larger_node = false;
 9987        let new_selections = old_selections
 9988            .iter()
 9989            .map(|selection| {
 9990                let old_range = selection.start..selection.end;
 9991                let mut new_range = old_range.clone();
 9992                let mut new_node = None;
 9993                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9994                {
 9995                    new_node = Some(node);
 9996                    new_range = containing_range;
 9997                    if !display_map.intersects_fold(new_range.start)
 9998                        && !display_map.intersects_fold(new_range.end)
 9999                    {
10000                        break;
10001                    }
10002                }
10003
10004                if let Some(node) = new_node {
10005                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10006                    // nodes. Parent and grandparent are also logged because this operation will not
10007                    // visit nodes that have the same range as their parent.
10008                    log::info!("Node: {node:?}");
10009                    let parent = node.parent();
10010                    log::info!("Parent: {parent:?}");
10011                    let grandparent = parent.and_then(|x| x.parent());
10012                    log::info!("Grandparent: {grandparent:?}");
10013                }
10014
10015                selected_larger_node |= new_range != old_range;
10016                Selection {
10017                    id: selection.id,
10018                    start: new_range.start,
10019                    end: new_range.end,
10020                    goal: SelectionGoal::None,
10021                    reversed: selection.reversed,
10022                }
10023            })
10024            .collect::<Vec<_>>();
10025
10026        if selected_larger_node {
10027            stack.push(old_selections);
10028            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10029                s.select(new_selections);
10030            });
10031        }
10032        self.select_larger_syntax_node_stack = stack;
10033    }
10034
10035    pub fn select_smaller_syntax_node(
10036        &mut self,
10037        _: &SelectSmallerSyntaxNode,
10038        window: &mut Window,
10039        cx: &mut Context<Self>,
10040    ) {
10041        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10042        if let Some(selections) = stack.pop() {
10043            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10044                s.select(selections.to_vec());
10045            });
10046        }
10047        self.select_larger_syntax_node_stack = stack;
10048    }
10049
10050    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10051        if !EditorSettings::get_global(cx).gutter.runnables {
10052            self.clear_tasks();
10053            return Task::ready(());
10054        }
10055        let project = self.project.as_ref().map(Entity::downgrade);
10056        cx.spawn_in(window, |this, mut cx| async move {
10057            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10058            let Some(project) = project.and_then(|p| p.upgrade()) else {
10059                return;
10060            };
10061            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10062                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10063            }) else {
10064                return;
10065            };
10066
10067            let hide_runnables = project
10068                .update(&mut cx, |project, cx| {
10069                    // Do not display any test indicators in non-dev server remote projects.
10070                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10071                })
10072                .unwrap_or(true);
10073            if hide_runnables {
10074                return;
10075            }
10076            let new_rows =
10077                cx.background_executor()
10078                    .spawn({
10079                        let snapshot = display_snapshot.clone();
10080                        async move {
10081                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10082                        }
10083                    })
10084                    .await;
10085
10086            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10087            this.update(&mut cx, |this, _| {
10088                this.clear_tasks();
10089                for (key, value) in rows {
10090                    this.insert_tasks(key, value);
10091                }
10092            })
10093            .ok();
10094        })
10095    }
10096    fn fetch_runnable_ranges(
10097        snapshot: &DisplaySnapshot,
10098        range: Range<Anchor>,
10099    ) -> Vec<language::RunnableRange> {
10100        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10101    }
10102
10103    fn runnable_rows(
10104        project: Entity<Project>,
10105        snapshot: DisplaySnapshot,
10106        runnable_ranges: Vec<RunnableRange>,
10107        mut cx: AsyncWindowContext,
10108    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10109        runnable_ranges
10110            .into_iter()
10111            .filter_map(|mut runnable| {
10112                let tasks = cx
10113                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10114                    .ok()?;
10115                if tasks.is_empty() {
10116                    return None;
10117                }
10118
10119                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10120
10121                let row = snapshot
10122                    .buffer_snapshot
10123                    .buffer_line_for_row(MultiBufferRow(point.row))?
10124                    .1
10125                    .start
10126                    .row;
10127
10128                let context_range =
10129                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10130                Some((
10131                    (runnable.buffer_id, row),
10132                    RunnableTasks {
10133                        templates: tasks,
10134                        offset: MultiBufferOffset(runnable.run_range.start),
10135                        context_range,
10136                        column: point.column,
10137                        extra_variables: runnable.extra_captures,
10138                    },
10139                ))
10140            })
10141            .collect()
10142    }
10143
10144    fn templates_with_tags(
10145        project: &Entity<Project>,
10146        runnable: &mut Runnable,
10147        cx: &mut App,
10148    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10149        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10150            let (worktree_id, file) = project
10151                .buffer_for_id(runnable.buffer, cx)
10152                .and_then(|buffer| buffer.read(cx).file())
10153                .map(|file| (file.worktree_id(cx), file.clone()))
10154                .unzip();
10155
10156            (
10157                project.task_store().read(cx).task_inventory().cloned(),
10158                worktree_id,
10159                file,
10160            )
10161        });
10162
10163        let tags = mem::take(&mut runnable.tags);
10164        let mut tags: Vec<_> = tags
10165            .into_iter()
10166            .flat_map(|tag| {
10167                let tag = tag.0.clone();
10168                inventory
10169                    .as_ref()
10170                    .into_iter()
10171                    .flat_map(|inventory| {
10172                        inventory.read(cx).list_tasks(
10173                            file.clone(),
10174                            Some(runnable.language.clone()),
10175                            worktree_id,
10176                            cx,
10177                        )
10178                    })
10179                    .filter(move |(_, template)| {
10180                        template.tags.iter().any(|source_tag| source_tag == &tag)
10181                    })
10182            })
10183            .sorted_by_key(|(kind, _)| kind.to_owned())
10184            .collect();
10185        if let Some((leading_tag_source, _)) = tags.first() {
10186            // Strongest source wins; if we have worktree tag binding, prefer that to
10187            // global and language bindings;
10188            // if we have a global binding, prefer that to language binding.
10189            let first_mismatch = tags
10190                .iter()
10191                .position(|(tag_source, _)| tag_source != leading_tag_source);
10192            if let Some(index) = first_mismatch {
10193                tags.truncate(index);
10194            }
10195        }
10196
10197        tags
10198    }
10199
10200    pub fn move_to_enclosing_bracket(
10201        &mut self,
10202        _: &MoveToEnclosingBracket,
10203        window: &mut Window,
10204        cx: &mut Context<Self>,
10205    ) {
10206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10207            s.move_offsets_with(|snapshot, selection| {
10208                let Some(enclosing_bracket_ranges) =
10209                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10210                else {
10211                    return;
10212                };
10213
10214                let mut best_length = usize::MAX;
10215                let mut best_inside = false;
10216                let mut best_in_bracket_range = false;
10217                let mut best_destination = None;
10218                for (open, close) in enclosing_bracket_ranges {
10219                    let close = close.to_inclusive();
10220                    let length = close.end() - open.start;
10221                    let inside = selection.start >= open.end && selection.end <= *close.start();
10222                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10223                        || close.contains(&selection.head());
10224
10225                    // If best is next to a bracket and current isn't, skip
10226                    if !in_bracket_range && best_in_bracket_range {
10227                        continue;
10228                    }
10229
10230                    // Prefer smaller lengths unless best is inside and current isn't
10231                    if length > best_length && (best_inside || !inside) {
10232                        continue;
10233                    }
10234
10235                    best_length = length;
10236                    best_inside = inside;
10237                    best_in_bracket_range = in_bracket_range;
10238                    best_destination = Some(
10239                        if close.contains(&selection.start) && close.contains(&selection.end) {
10240                            if inside {
10241                                open.end
10242                            } else {
10243                                open.start
10244                            }
10245                        } else if inside {
10246                            *close.start()
10247                        } else {
10248                            *close.end()
10249                        },
10250                    );
10251                }
10252
10253                if let Some(destination) = best_destination {
10254                    selection.collapse_to(destination, SelectionGoal::None);
10255                }
10256            })
10257        });
10258    }
10259
10260    pub fn undo_selection(
10261        &mut self,
10262        _: &UndoSelection,
10263        window: &mut Window,
10264        cx: &mut Context<Self>,
10265    ) {
10266        self.end_selection(window, cx);
10267        self.selection_history.mode = SelectionHistoryMode::Undoing;
10268        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10269            self.change_selections(None, window, cx, |s| {
10270                s.select_anchors(entry.selections.to_vec())
10271            });
10272            self.select_next_state = entry.select_next_state;
10273            self.select_prev_state = entry.select_prev_state;
10274            self.add_selections_state = entry.add_selections_state;
10275            self.request_autoscroll(Autoscroll::newest(), cx);
10276        }
10277        self.selection_history.mode = SelectionHistoryMode::Normal;
10278    }
10279
10280    pub fn redo_selection(
10281        &mut self,
10282        _: &RedoSelection,
10283        window: &mut Window,
10284        cx: &mut Context<Self>,
10285    ) {
10286        self.end_selection(window, cx);
10287        self.selection_history.mode = SelectionHistoryMode::Redoing;
10288        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10289            self.change_selections(None, window, cx, |s| {
10290                s.select_anchors(entry.selections.to_vec())
10291            });
10292            self.select_next_state = entry.select_next_state;
10293            self.select_prev_state = entry.select_prev_state;
10294            self.add_selections_state = entry.add_selections_state;
10295            self.request_autoscroll(Autoscroll::newest(), cx);
10296        }
10297        self.selection_history.mode = SelectionHistoryMode::Normal;
10298    }
10299
10300    pub fn expand_excerpts(
10301        &mut self,
10302        action: &ExpandExcerpts,
10303        _: &mut Window,
10304        cx: &mut Context<Self>,
10305    ) {
10306        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10307    }
10308
10309    pub fn expand_excerpts_down(
10310        &mut self,
10311        action: &ExpandExcerptsDown,
10312        _: &mut Window,
10313        cx: &mut Context<Self>,
10314    ) {
10315        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10316    }
10317
10318    pub fn expand_excerpts_up(
10319        &mut self,
10320        action: &ExpandExcerptsUp,
10321        _: &mut Window,
10322        cx: &mut Context<Self>,
10323    ) {
10324        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10325    }
10326
10327    pub fn expand_excerpts_for_direction(
10328        &mut self,
10329        lines: u32,
10330        direction: ExpandExcerptDirection,
10331
10332        cx: &mut Context<Self>,
10333    ) {
10334        let selections = self.selections.disjoint_anchors();
10335
10336        let lines = if lines == 0 {
10337            EditorSettings::get_global(cx).expand_excerpt_lines
10338        } else {
10339            lines
10340        };
10341
10342        self.buffer.update(cx, |buffer, cx| {
10343            let snapshot = buffer.snapshot(cx);
10344            let mut excerpt_ids = selections
10345                .iter()
10346                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10347                .collect::<Vec<_>>();
10348            excerpt_ids.sort();
10349            excerpt_ids.dedup();
10350            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10351        })
10352    }
10353
10354    pub fn expand_excerpt(
10355        &mut self,
10356        excerpt: ExcerptId,
10357        direction: ExpandExcerptDirection,
10358        cx: &mut Context<Self>,
10359    ) {
10360        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10361        self.buffer.update(cx, |buffer, cx| {
10362            buffer.expand_excerpts([excerpt], lines, direction, cx)
10363        })
10364    }
10365
10366    pub fn go_to_singleton_buffer_point(
10367        &mut self,
10368        point: Point,
10369        window: &mut Window,
10370        cx: &mut Context<Self>,
10371    ) {
10372        self.go_to_singleton_buffer_range(point..point, window, cx);
10373    }
10374
10375    pub fn go_to_singleton_buffer_range(
10376        &mut self,
10377        range: Range<Point>,
10378        window: &mut Window,
10379        cx: &mut Context<Self>,
10380    ) {
10381        let multibuffer = self.buffer().read(cx);
10382        let Some(buffer) = multibuffer.as_singleton() else {
10383            return;
10384        };
10385        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10386            return;
10387        };
10388        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10389            return;
10390        };
10391        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10392            s.select_anchor_ranges([start..end])
10393        });
10394    }
10395
10396    fn go_to_diagnostic(
10397        &mut self,
10398        _: &GoToDiagnostic,
10399        window: &mut Window,
10400        cx: &mut Context<Self>,
10401    ) {
10402        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10403    }
10404
10405    fn go_to_prev_diagnostic(
10406        &mut self,
10407        _: &GoToPrevDiagnostic,
10408        window: &mut Window,
10409        cx: &mut Context<Self>,
10410    ) {
10411        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10412    }
10413
10414    pub fn go_to_diagnostic_impl(
10415        &mut self,
10416        direction: Direction,
10417        window: &mut Window,
10418        cx: &mut Context<Self>,
10419    ) {
10420        let buffer = self.buffer.read(cx).snapshot(cx);
10421        let selection = self.selections.newest::<usize>(cx);
10422
10423        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10424        if direction == Direction::Next {
10425            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10426                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10427                    return;
10428                };
10429                self.activate_diagnostics(
10430                    buffer_id,
10431                    popover.local_diagnostic.diagnostic.group_id,
10432                    window,
10433                    cx,
10434                );
10435                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10436                    let primary_range_start = active_diagnostics.primary_range.start;
10437                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10438                        let mut new_selection = s.newest_anchor().clone();
10439                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10440                        s.select_anchors(vec![new_selection.clone()]);
10441                    });
10442                    self.refresh_inline_completion(false, true, window, cx);
10443                }
10444                return;
10445            }
10446        }
10447
10448        let active_group_id = self
10449            .active_diagnostics
10450            .as_ref()
10451            .map(|active_group| active_group.group_id);
10452        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10453            active_diagnostics
10454                .primary_range
10455                .to_offset(&buffer)
10456                .to_inclusive()
10457        });
10458        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10459            if active_primary_range.contains(&selection.head()) {
10460                *active_primary_range.start()
10461            } else {
10462                selection.head()
10463            }
10464        } else {
10465            selection.head()
10466        };
10467
10468        let snapshot = self.snapshot(window, cx);
10469        let primary_diagnostics_before = buffer
10470            .diagnostics_in_range::<usize>(0..search_start)
10471            .filter(|entry| entry.diagnostic.is_primary)
10472            .filter(|entry| entry.range.start != entry.range.end)
10473            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10474            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10475            .collect::<Vec<_>>();
10476        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10477            primary_diagnostics_before
10478                .iter()
10479                .position(|entry| entry.diagnostic.group_id == active_group_id)
10480        });
10481
10482        let primary_diagnostics_after = buffer
10483            .diagnostics_in_range::<usize>(search_start..buffer.len())
10484            .filter(|entry| entry.diagnostic.is_primary)
10485            .filter(|entry| entry.range.start != entry.range.end)
10486            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10487            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10488            .collect::<Vec<_>>();
10489        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10490            primary_diagnostics_after
10491                .iter()
10492                .enumerate()
10493                .rev()
10494                .find_map(|(i, entry)| {
10495                    if entry.diagnostic.group_id == active_group_id {
10496                        Some(i)
10497                    } else {
10498                        None
10499                    }
10500                })
10501        });
10502
10503        let next_primary_diagnostic = match direction {
10504            Direction::Prev => primary_diagnostics_before
10505                .iter()
10506                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10507                .rev()
10508                .next(),
10509            Direction::Next => primary_diagnostics_after
10510                .iter()
10511                .skip(
10512                    last_same_group_diagnostic_after
10513                        .map(|index| index + 1)
10514                        .unwrap_or(0),
10515                )
10516                .next(),
10517        };
10518
10519        // Cycle around to the start of the buffer, potentially moving back to the start of
10520        // the currently active diagnostic.
10521        let cycle_around = || match direction {
10522            Direction::Prev => primary_diagnostics_after
10523                .iter()
10524                .rev()
10525                .chain(primary_diagnostics_before.iter().rev())
10526                .next(),
10527            Direction::Next => primary_diagnostics_before
10528                .iter()
10529                .chain(primary_diagnostics_after.iter())
10530                .next(),
10531        };
10532
10533        if let Some((primary_range, group_id)) = next_primary_diagnostic
10534            .or_else(cycle_around)
10535            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10536        {
10537            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10538                return;
10539            };
10540            self.activate_diagnostics(buffer_id, group_id, window, cx);
10541            if self.active_diagnostics.is_some() {
10542                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10543                    s.select(vec![Selection {
10544                        id: selection.id,
10545                        start: primary_range.start,
10546                        end: primary_range.start,
10547                        reversed: false,
10548                        goal: SelectionGoal::None,
10549                    }]);
10550                });
10551                self.refresh_inline_completion(false, true, window, cx);
10552            }
10553        }
10554    }
10555
10556    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10557        let snapshot = self.snapshot(window, cx);
10558        let selection = self.selections.newest::<Point>(cx);
10559        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10560    }
10561
10562    fn go_to_hunk_after_position(
10563        &mut self,
10564        snapshot: &EditorSnapshot,
10565        position: Point,
10566        window: &mut Window,
10567        cx: &mut Context<Editor>,
10568    ) -> Option<MultiBufferDiffHunk> {
10569        let mut hunk = snapshot
10570            .buffer_snapshot
10571            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10572            .find(|hunk| hunk.row_range.start.0 > position.row);
10573        if hunk.is_none() {
10574            hunk = snapshot
10575                .buffer_snapshot
10576                .diff_hunks_in_range(Point::zero()..position)
10577                .find(|hunk| hunk.row_range.end.0 < position.row)
10578        }
10579        if let Some(hunk) = &hunk {
10580            let destination = Point::new(hunk.row_range.start.0, 0);
10581            self.unfold_ranges(&[destination..destination], false, false, cx);
10582            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10583                s.select_ranges(vec![destination..destination]);
10584            });
10585        }
10586
10587        hunk
10588    }
10589
10590    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10591        let snapshot = self.snapshot(window, cx);
10592        let selection = self.selections.newest::<Point>(cx);
10593        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10594    }
10595
10596    fn go_to_hunk_before_position(
10597        &mut self,
10598        snapshot: &EditorSnapshot,
10599        position: Point,
10600        window: &mut Window,
10601        cx: &mut Context<Editor>,
10602    ) -> Option<MultiBufferDiffHunk> {
10603        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10604        if hunk.is_none() {
10605            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10606        }
10607        if let Some(hunk) = &hunk {
10608            let destination = Point::new(hunk.row_range.start.0, 0);
10609            self.unfold_ranges(&[destination..destination], false, false, cx);
10610            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10611                s.select_ranges(vec![destination..destination]);
10612            });
10613        }
10614
10615        hunk
10616    }
10617
10618    pub fn go_to_definition(
10619        &mut self,
10620        _: &GoToDefinition,
10621        window: &mut Window,
10622        cx: &mut Context<Self>,
10623    ) -> Task<Result<Navigated>> {
10624        let definition =
10625            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10626        cx.spawn_in(window, |editor, mut cx| async move {
10627            if definition.await? == Navigated::Yes {
10628                return Ok(Navigated::Yes);
10629            }
10630            match editor.update_in(&mut cx, |editor, window, cx| {
10631                editor.find_all_references(&FindAllReferences, window, cx)
10632            })? {
10633                Some(references) => references.await,
10634                None => Ok(Navigated::No),
10635            }
10636        })
10637    }
10638
10639    pub fn go_to_declaration(
10640        &mut self,
10641        _: &GoToDeclaration,
10642        window: &mut Window,
10643        cx: &mut Context<Self>,
10644    ) -> Task<Result<Navigated>> {
10645        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10646    }
10647
10648    pub fn go_to_declaration_split(
10649        &mut self,
10650        _: &GoToDeclaration,
10651        window: &mut Window,
10652        cx: &mut Context<Self>,
10653    ) -> Task<Result<Navigated>> {
10654        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10655    }
10656
10657    pub fn go_to_implementation(
10658        &mut self,
10659        _: &GoToImplementation,
10660        window: &mut Window,
10661        cx: &mut Context<Self>,
10662    ) -> Task<Result<Navigated>> {
10663        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10664    }
10665
10666    pub fn go_to_implementation_split(
10667        &mut self,
10668        _: &GoToImplementationSplit,
10669        window: &mut Window,
10670        cx: &mut Context<Self>,
10671    ) -> Task<Result<Navigated>> {
10672        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10673    }
10674
10675    pub fn go_to_type_definition(
10676        &mut self,
10677        _: &GoToTypeDefinition,
10678        window: &mut Window,
10679        cx: &mut Context<Self>,
10680    ) -> Task<Result<Navigated>> {
10681        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10682    }
10683
10684    pub fn go_to_definition_split(
10685        &mut self,
10686        _: &GoToDefinitionSplit,
10687        window: &mut Window,
10688        cx: &mut Context<Self>,
10689    ) -> Task<Result<Navigated>> {
10690        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10691    }
10692
10693    pub fn go_to_type_definition_split(
10694        &mut self,
10695        _: &GoToTypeDefinitionSplit,
10696        window: &mut Window,
10697        cx: &mut Context<Self>,
10698    ) -> Task<Result<Navigated>> {
10699        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10700    }
10701
10702    fn go_to_definition_of_kind(
10703        &mut self,
10704        kind: GotoDefinitionKind,
10705        split: bool,
10706        window: &mut Window,
10707        cx: &mut Context<Self>,
10708    ) -> Task<Result<Navigated>> {
10709        let Some(provider) = self.semantics_provider.clone() else {
10710            return Task::ready(Ok(Navigated::No));
10711        };
10712        let head = self.selections.newest::<usize>(cx).head();
10713        let buffer = self.buffer.read(cx);
10714        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10715            text_anchor
10716        } else {
10717            return Task::ready(Ok(Navigated::No));
10718        };
10719
10720        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10721            return Task::ready(Ok(Navigated::No));
10722        };
10723
10724        cx.spawn_in(window, |editor, mut cx| async move {
10725            let definitions = definitions.await?;
10726            let navigated = editor
10727                .update_in(&mut cx, |editor, window, cx| {
10728                    editor.navigate_to_hover_links(
10729                        Some(kind),
10730                        definitions
10731                            .into_iter()
10732                            .filter(|location| {
10733                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10734                            })
10735                            .map(HoverLink::Text)
10736                            .collect::<Vec<_>>(),
10737                        split,
10738                        window,
10739                        cx,
10740                    )
10741                })?
10742                .await?;
10743            anyhow::Ok(navigated)
10744        })
10745    }
10746
10747    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10748        let selection = self.selections.newest_anchor();
10749        let head = selection.head();
10750        let tail = selection.tail();
10751
10752        let Some((buffer, start_position)) =
10753            self.buffer.read(cx).text_anchor_for_position(head, cx)
10754        else {
10755            return;
10756        };
10757
10758        let end_position = if head != tail {
10759            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10760                return;
10761            };
10762            Some(pos)
10763        } else {
10764            None
10765        };
10766
10767        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10768            let url = if let Some(end_pos) = end_position {
10769                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10770            } else {
10771                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10772            };
10773
10774            if let Some(url) = url {
10775                editor.update(&mut cx, |_, cx| {
10776                    cx.open_url(&url);
10777                })
10778            } else {
10779                Ok(())
10780            }
10781        });
10782
10783        url_finder.detach();
10784    }
10785
10786    pub fn open_selected_filename(
10787        &mut self,
10788        _: &OpenSelectedFilename,
10789        window: &mut Window,
10790        cx: &mut Context<Self>,
10791    ) {
10792        let Some(workspace) = self.workspace() else {
10793            return;
10794        };
10795
10796        let position = self.selections.newest_anchor().head();
10797
10798        let Some((buffer, buffer_position)) =
10799            self.buffer.read(cx).text_anchor_for_position(position, cx)
10800        else {
10801            return;
10802        };
10803
10804        let project = self.project.clone();
10805
10806        cx.spawn_in(window, |_, mut cx| async move {
10807            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10808
10809            if let Some((_, path)) = result {
10810                workspace
10811                    .update_in(&mut cx, |workspace, window, cx| {
10812                        workspace.open_resolved_path(path, window, cx)
10813                    })?
10814                    .await?;
10815            }
10816            anyhow::Ok(())
10817        })
10818        .detach();
10819    }
10820
10821    pub(crate) fn navigate_to_hover_links(
10822        &mut self,
10823        kind: Option<GotoDefinitionKind>,
10824        mut definitions: Vec<HoverLink>,
10825        split: bool,
10826        window: &mut Window,
10827        cx: &mut Context<Editor>,
10828    ) -> Task<Result<Navigated>> {
10829        // If there is one definition, just open it directly
10830        if definitions.len() == 1 {
10831            let definition = definitions.pop().unwrap();
10832
10833            enum TargetTaskResult {
10834                Location(Option<Location>),
10835                AlreadyNavigated,
10836            }
10837
10838            let target_task = match definition {
10839                HoverLink::Text(link) => {
10840                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10841                }
10842                HoverLink::InlayHint(lsp_location, server_id) => {
10843                    let computation =
10844                        self.compute_target_location(lsp_location, server_id, window, cx);
10845                    cx.background_executor().spawn(async move {
10846                        let location = computation.await?;
10847                        Ok(TargetTaskResult::Location(location))
10848                    })
10849                }
10850                HoverLink::Url(url) => {
10851                    cx.open_url(&url);
10852                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10853                }
10854                HoverLink::File(path) => {
10855                    if let Some(workspace) = self.workspace() {
10856                        cx.spawn_in(window, |_, mut cx| async move {
10857                            workspace
10858                                .update_in(&mut cx, |workspace, window, cx| {
10859                                    workspace.open_resolved_path(path, window, cx)
10860                                })?
10861                                .await
10862                                .map(|_| TargetTaskResult::AlreadyNavigated)
10863                        })
10864                    } else {
10865                        Task::ready(Ok(TargetTaskResult::Location(None)))
10866                    }
10867                }
10868            };
10869            cx.spawn_in(window, |editor, mut cx| async move {
10870                let target = match target_task.await.context("target resolution task")? {
10871                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10872                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10873                    TargetTaskResult::Location(Some(target)) => target,
10874                };
10875
10876                editor.update_in(&mut cx, |editor, window, cx| {
10877                    let Some(workspace) = editor.workspace() else {
10878                        return Navigated::No;
10879                    };
10880                    let pane = workspace.read(cx).active_pane().clone();
10881
10882                    let range = target.range.to_point(target.buffer.read(cx));
10883                    let range = editor.range_for_match(&range);
10884                    let range = collapse_multiline_range(range);
10885
10886                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10887                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10888                    } else {
10889                        window.defer(cx, move |window, cx| {
10890                            let target_editor: Entity<Self> =
10891                                workspace.update(cx, |workspace, cx| {
10892                                    let pane = if split {
10893                                        workspace.adjacent_pane(window, cx)
10894                                    } else {
10895                                        workspace.active_pane().clone()
10896                                    };
10897
10898                                    workspace.open_project_item(
10899                                        pane,
10900                                        target.buffer.clone(),
10901                                        true,
10902                                        true,
10903                                        window,
10904                                        cx,
10905                                    )
10906                                });
10907                            target_editor.update(cx, |target_editor, cx| {
10908                                // When selecting a definition in a different buffer, disable the nav history
10909                                // to avoid creating a history entry at the previous cursor location.
10910                                pane.update(cx, |pane, _| pane.disable_history());
10911                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10912                                pane.update(cx, |pane, _| pane.enable_history());
10913                            });
10914                        });
10915                    }
10916                    Navigated::Yes
10917                })
10918            })
10919        } else if !definitions.is_empty() {
10920            cx.spawn_in(window, |editor, mut cx| async move {
10921                let (title, location_tasks, workspace) = editor
10922                    .update_in(&mut cx, |editor, window, cx| {
10923                        let tab_kind = match kind {
10924                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10925                            _ => "Definitions",
10926                        };
10927                        let title = definitions
10928                            .iter()
10929                            .find_map(|definition| match definition {
10930                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10931                                    let buffer = origin.buffer.read(cx);
10932                                    format!(
10933                                        "{} for {}",
10934                                        tab_kind,
10935                                        buffer
10936                                            .text_for_range(origin.range.clone())
10937                                            .collect::<String>()
10938                                    )
10939                                }),
10940                                HoverLink::InlayHint(_, _) => None,
10941                                HoverLink::Url(_) => None,
10942                                HoverLink::File(_) => None,
10943                            })
10944                            .unwrap_or(tab_kind.to_string());
10945                        let location_tasks = definitions
10946                            .into_iter()
10947                            .map(|definition| match definition {
10948                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10949                                HoverLink::InlayHint(lsp_location, server_id) => editor
10950                                    .compute_target_location(lsp_location, server_id, window, cx),
10951                                HoverLink::Url(_) => Task::ready(Ok(None)),
10952                                HoverLink::File(_) => Task::ready(Ok(None)),
10953                            })
10954                            .collect::<Vec<_>>();
10955                        (title, location_tasks, editor.workspace().clone())
10956                    })
10957                    .context("location tasks preparation")?;
10958
10959                let locations = future::join_all(location_tasks)
10960                    .await
10961                    .into_iter()
10962                    .filter_map(|location| location.transpose())
10963                    .collect::<Result<_>>()
10964                    .context("location tasks")?;
10965
10966                let Some(workspace) = workspace else {
10967                    return Ok(Navigated::No);
10968                };
10969                let opened = workspace
10970                    .update_in(&mut cx, |workspace, window, cx| {
10971                        Self::open_locations_in_multibuffer(
10972                            workspace,
10973                            locations,
10974                            title,
10975                            split,
10976                            MultibufferSelectionMode::First,
10977                            window,
10978                            cx,
10979                        )
10980                    })
10981                    .ok();
10982
10983                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10984            })
10985        } else {
10986            Task::ready(Ok(Navigated::No))
10987        }
10988    }
10989
10990    fn compute_target_location(
10991        &self,
10992        lsp_location: lsp::Location,
10993        server_id: LanguageServerId,
10994        window: &mut Window,
10995        cx: &mut Context<Self>,
10996    ) -> Task<anyhow::Result<Option<Location>>> {
10997        let Some(project) = self.project.clone() else {
10998            return Task::ready(Ok(None));
10999        };
11000
11001        cx.spawn_in(window, move |editor, mut cx| async move {
11002            let location_task = editor.update(&mut cx, |_, cx| {
11003                project.update(cx, |project, cx| {
11004                    let language_server_name = project
11005                        .language_server_statuses(cx)
11006                        .find(|(id, _)| server_id == *id)
11007                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11008                    language_server_name.map(|language_server_name| {
11009                        project.open_local_buffer_via_lsp(
11010                            lsp_location.uri.clone(),
11011                            server_id,
11012                            language_server_name,
11013                            cx,
11014                        )
11015                    })
11016                })
11017            })?;
11018            let location = match location_task {
11019                Some(task) => Some({
11020                    let target_buffer_handle = task.await.context("open local buffer")?;
11021                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11022                        let target_start = target_buffer
11023                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11024                        let target_end = target_buffer
11025                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11026                        target_buffer.anchor_after(target_start)
11027                            ..target_buffer.anchor_before(target_end)
11028                    })?;
11029                    Location {
11030                        buffer: target_buffer_handle,
11031                        range,
11032                    }
11033                }),
11034                None => None,
11035            };
11036            Ok(location)
11037        })
11038    }
11039
11040    pub fn find_all_references(
11041        &mut self,
11042        _: &FindAllReferences,
11043        window: &mut Window,
11044        cx: &mut Context<Self>,
11045    ) -> Option<Task<Result<Navigated>>> {
11046        let selection = self.selections.newest::<usize>(cx);
11047        let multi_buffer = self.buffer.read(cx);
11048        let head = selection.head();
11049
11050        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11051        let head_anchor = multi_buffer_snapshot.anchor_at(
11052            head,
11053            if head < selection.tail() {
11054                Bias::Right
11055            } else {
11056                Bias::Left
11057            },
11058        );
11059
11060        match self
11061            .find_all_references_task_sources
11062            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11063        {
11064            Ok(_) => {
11065                log::info!(
11066                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11067                );
11068                return None;
11069            }
11070            Err(i) => {
11071                self.find_all_references_task_sources.insert(i, head_anchor);
11072            }
11073        }
11074
11075        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11076        let workspace = self.workspace()?;
11077        let project = workspace.read(cx).project().clone();
11078        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11079        Some(cx.spawn_in(window, |editor, mut cx| async move {
11080            let _cleanup = defer({
11081                let mut cx = cx.clone();
11082                move || {
11083                    let _ = editor.update(&mut cx, |editor, _| {
11084                        if let Ok(i) =
11085                            editor
11086                                .find_all_references_task_sources
11087                                .binary_search_by(|anchor| {
11088                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11089                                })
11090                        {
11091                            editor.find_all_references_task_sources.remove(i);
11092                        }
11093                    });
11094                }
11095            });
11096
11097            let locations = references.await?;
11098            if locations.is_empty() {
11099                return anyhow::Ok(Navigated::No);
11100            }
11101
11102            workspace.update_in(&mut cx, |workspace, window, cx| {
11103                let title = locations
11104                    .first()
11105                    .as_ref()
11106                    .map(|location| {
11107                        let buffer = location.buffer.read(cx);
11108                        format!(
11109                            "References to `{}`",
11110                            buffer
11111                                .text_for_range(location.range.clone())
11112                                .collect::<String>()
11113                        )
11114                    })
11115                    .unwrap();
11116                Self::open_locations_in_multibuffer(
11117                    workspace,
11118                    locations,
11119                    title,
11120                    false,
11121                    MultibufferSelectionMode::First,
11122                    window,
11123                    cx,
11124                );
11125                Navigated::Yes
11126            })
11127        }))
11128    }
11129
11130    /// Opens a multibuffer with the given project locations in it
11131    pub fn open_locations_in_multibuffer(
11132        workspace: &mut Workspace,
11133        mut locations: Vec<Location>,
11134        title: String,
11135        split: bool,
11136        multibuffer_selection_mode: MultibufferSelectionMode,
11137        window: &mut Window,
11138        cx: &mut Context<Workspace>,
11139    ) {
11140        // If there are multiple definitions, open them in a multibuffer
11141        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11142        let mut locations = locations.into_iter().peekable();
11143        let mut ranges = Vec::new();
11144        let capability = workspace.project().read(cx).capability();
11145
11146        let excerpt_buffer = cx.new(|cx| {
11147            let mut multibuffer = MultiBuffer::new(capability);
11148            while let Some(location) = locations.next() {
11149                let buffer = location.buffer.read(cx);
11150                let mut ranges_for_buffer = Vec::new();
11151                let range = location.range.to_offset(buffer);
11152                ranges_for_buffer.push(range.clone());
11153
11154                while let Some(next_location) = locations.peek() {
11155                    if next_location.buffer == location.buffer {
11156                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11157                        locations.next();
11158                    } else {
11159                        break;
11160                    }
11161                }
11162
11163                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11164                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11165                    location.buffer.clone(),
11166                    ranges_for_buffer,
11167                    DEFAULT_MULTIBUFFER_CONTEXT,
11168                    cx,
11169                ))
11170            }
11171
11172            multibuffer.with_title(title)
11173        });
11174
11175        let editor = cx.new(|cx| {
11176            Editor::for_multibuffer(
11177                excerpt_buffer,
11178                Some(workspace.project().clone()),
11179                true,
11180                window,
11181                cx,
11182            )
11183        });
11184        editor.update(cx, |editor, cx| {
11185            match multibuffer_selection_mode {
11186                MultibufferSelectionMode::First => {
11187                    if let Some(first_range) = ranges.first() {
11188                        editor.change_selections(None, window, cx, |selections| {
11189                            selections.clear_disjoint();
11190                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11191                        });
11192                    }
11193                    editor.highlight_background::<Self>(
11194                        &ranges,
11195                        |theme| theme.editor_highlighted_line_background,
11196                        cx,
11197                    );
11198                }
11199                MultibufferSelectionMode::All => {
11200                    editor.change_selections(None, window, cx, |selections| {
11201                        selections.clear_disjoint();
11202                        selections.select_anchor_ranges(ranges);
11203                    });
11204                }
11205            }
11206            editor.register_buffers_with_language_servers(cx);
11207        });
11208
11209        let item = Box::new(editor);
11210        let item_id = item.item_id();
11211
11212        if split {
11213            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11214        } else {
11215            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11216                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11217                    pane.close_current_preview_item(window, cx)
11218                } else {
11219                    None
11220                }
11221            });
11222            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11223        }
11224        workspace.active_pane().update(cx, |pane, cx| {
11225            pane.set_preview_item_id(Some(item_id), cx);
11226        });
11227    }
11228
11229    pub fn rename(
11230        &mut self,
11231        _: &Rename,
11232        window: &mut Window,
11233        cx: &mut Context<Self>,
11234    ) -> Option<Task<Result<()>>> {
11235        use language::ToOffset as _;
11236
11237        let provider = self.semantics_provider.clone()?;
11238        let selection = self.selections.newest_anchor().clone();
11239        let (cursor_buffer, cursor_buffer_position) = self
11240            .buffer
11241            .read(cx)
11242            .text_anchor_for_position(selection.head(), cx)?;
11243        let (tail_buffer, cursor_buffer_position_end) = self
11244            .buffer
11245            .read(cx)
11246            .text_anchor_for_position(selection.tail(), cx)?;
11247        if tail_buffer != cursor_buffer {
11248            return None;
11249        }
11250
11251        let snapshot = cursor_buffer.read(cx).snapshot();
11252        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11253        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11254        let prepare_rename = provider
11255            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11256            .unwrap_or_else(|| Task::ready(Ok(None)));
11257        drop(snapshot);
11258
11259        Some(cx.spawn_in(window, |this, mut cx| async move {
11260            let rename_range = if let Some(range) = prepare_rename.await? {
11261                Some(range)
11262            } else {
11263                this.update(&mut cx, |this, cx| {
11264                    let buffer = this.buffer.read(cx).snapshot(cx);
11265                    let mut buffer_highlights = this
11266                        .document_highlights_for_position(selection.head(), &buffer)
11267                        .filter(|highlight| {
11268                            highlight.start.excerpt_id == selection.head().excerpt_id
11269                                && highlight.end.excerpt_id == selection.head().excerpt_id
11270                        });
11271                    buffer_highlights
11272                        .next()
11273                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11274                })?
11275            };
11276            if let Some(rename_range) = rename_range {
11277                this.update_in(&mut cx, |this, window, cx| {
11278                    let snapshot = cursor_buffer.read(cx).snapshot();
11279                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11280                    let cursor_offset_in_rename_range =
11281                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11282                    let cursor_offset_in_rename_range_end =
11283                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11284
11285                    this.take_rename(false, window, cx);
11286                    let buffer = this.buffer.read(cx).read(cx);
11287                    let cursor_offset = selection.head().to_offset(&buffer);
11288                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11289                    let rename_end = rename_start + rename_buffer_range.len();
11290                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11291                    let mut old_highlight_id = None;
11292                    let old_name: Arc<str> = buffer
11293                        .chunks(rename_start..rename_end, true)
11294                        .map(|chunk| {
11295                            if old_highlight_id.is_none() {
11296                                old_highlight_id = chunk.syntax_highlight_id;
11297                            }
11298                            chunk.text
11299                        })
11300                        .collect::<String>()
11301                        .into();
11302
11303                    drop(buffer);
11304
11305                    // Position the selection in the rename editor so that it matches the current selection.
11306                    this.show_local_selections = false;
11307                    let rename_editor = cx.new(|cx| {
11308                        let mut editor = Editor::single_line(window, cx);
11309                        editor.buffer.update(cx, |buffer, cx| {
11310                            buffer.edit([(0..0, old_name.clone())], None, cx)
11311                        });
11312                        let rename_selection_range = match cursor_offset_in_rename_range
11313                            .cmp(&cursor_offset_in_rename_range_end)
11314                        {
11315                            Ordering::Equal => {
11316                                editor.select_all(&SelectAll, window, cx);
11317                                return editor;
11318                            }
11319                            Ordering::Less => {
11320                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11321                            }
11322                            Ordering::Greater => {
11323                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11324                            }
11325                        };
11326                        if rename_selection_range.end > old_name.len() {
11327                            editor.select_all(&SelectAll, window, cx);
11328                        } else {
11329                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11330                                s.select_ranges([rename_selection_range]);
11331                            });
11332                        }
11333                        editor
11334                    });
11335                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11336                        if e == &EditorEvent::Focused {
11337                            cx.emit(EditorEvent::FocusedIn)
11338                        }
11339                    })
11340                    .detach();
11341
11342                    let write_highlights =
11343                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11344                    let read_highlights =
11345                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11346                    let ranges = write_highlights
11347                        .iter()
11348                        .flat_map(|(_, ranges)| ranges.iter())
11349                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11350                        .cloned()
11351                        .collect();
11352
11353                    this.highlight_text::<Rename>(
11354                        ranges,
11355                        HighlightStyle {
11356                            fade_out: Some(0.6),
11357                            ..Default::default()
11358                        },
11359                        cx,
11360                    );
11361                    let rename_focus_handle = rename_editor.focus_handle(cx);
11362                    window.focus(&rename_focus_handle);
11363                    let block_id = this.insert_blocks(
11364                        [BlockProperties {
11365                            style: BlockStyle::Flex,
11366                            placement: BlockPlacement::Below(range.start),
11367                            height: 1,
11368                            render: Arc::new({
11369                                let rename_editor = rename_editor.clone();
11370                                move |cx: &mut BlockContext| {
11371                                    let mut text_style = cx.editor_style.text.clone();
11372                                    if let Some(highlight_style) = old_highlight_id
11373                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11374                                    {
11375                                        text_style = text_style.highlight(highlight_style);
11376                                    }
11377                                    div()
11378                                        .block_mouse_down()
11379                                        .pl(cx.anchor_x)
11380                                        .child(EditorElement::new(
11381                                            &rename_editor,
11382                                            EditorStyle {
11383                                                background: cx.theme().system().transparent,
11384                                                local_player: cx.editor_style.local_player,
11385                                                text: text_style,
11386                                                scrollbar_width: cx.editor_style.scrollbar_width,
11387                                                syntax: cx.editor_style.syntax.clone(),
11388                                                status: cx.editor_style.status.clone(),
11389                                                inlay_hints_style: HighlightStyle {
11390                                                    font_weight: Some(FontWeight::BOLD),
11391                                                    ..make_inlay_hints_style(cx.app)
11392                                                },
11393                                                inline_completion_styles: make_suggestion_styles(
11394                                                    cx.app,
11395                                                ),
11396                                                ..EditorStyle::default()
11397                                            },
11398                                        ))
11399                                        .into_any_element()
11400                                }
11401                            }),
11402                            priority: 0,
11403                        }],
11404                        Some(Autoscroll::fit()),
11405                        cx,
11406                    )[0];
11407                    this.pending_rename = Some(RenameState {
11408                        range,
11409                        old_name,
11410                        editor: rename_editor,
11411                        block_id,
11412                    });
11413                })?;
11414            }
11415
11416            Ok(())
11417        }))
11418    }
11419
11420    pub fn confirm_rename(
11421        &mut self,
11422        _: &ConfirmRename,
11423        window: &mut Window,
11424        cx: &mut Context<Self>,
11425    ) -> Option<Task<Result<()>>> {
11426        let rename = self.take_rename(false, window, cx)?;
11427        let workspace = self.workspace()?.downgrade();
11428        let (buffer, start) = self
11429            .buffer
11430            .read(cx)
11431            .text_anchor_for_position(rename.range.start, cx)?;
11432        let (end_buffer, _) = self
11433            .buffer
11434            .read(cx)
11435            .text_anchor_for_position(rename.range.end, cx)?;
11436        if buffer != end_buffer {
11437            return None;
11438        }
11439
11440        let old_name = rename.old_name;
11441        let new_name = rename.editor.read(cx).text(cx);
11442
11443        let rename = self.semantics_provider.as_ref()?.perform_rename(
11444            &buffer,
11445            start,
11446            new_name.clone(),
11447            cx,
11448        )?;
11449
11450        Some(cx.spawn_in(window, |editor, mut cx| async move {
11451            let project_transaction = rename.await?;
11452            Self::open_project_transaction(
11453                &editor,
11454                workspace,
11455                project_transaction,
11456                format!("Rename: {}{}", old_name, new_name),
11457                cx.clone(),
11458            )
11459            .await?;
11460
11461            editor.update(&mut cx, |editor, cx| {
11462                editor.refresh_document_highlights(cx);
11463            })?;
11464            Ok(())
11465        }))
11466    }
11467
11468    fn take_rename(
11469        &mut self,
11470        moving_cursor: bool,
11471        window: &mut Window,
11472        cx: &mut Context<Self>,
11473    ) -> Option<RenameState> {
11474        let rename = self.pending_rename.take()?;
11475        if rename.editor.focus_handle(cx).is_focused(window) {
11476            window.focus(&self.focus_handle);
11477        }
11478
11479        self.remove_blocks(
11480            [rename.block_id].into_iter().collect(),
11481            Some(Autoscroll::fit()),
11482            cx,
11483        );
11484        self.clear_highlights::<Rename>(cx);
11485        self.show_local_selections = true;
11486
11487        if moving_cursor {
11488            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11489                editor.selections.newest::<usize>(cx).head()
11490            });
11491
11492            // Update the selection to match the position of the selection inside
11493            // the rename editor.
11494            let snapshot = self.buffer.read(cx).read(cx);
11495            let rename_range = rename.range.to_offset(&snapshot);
11496            let cursor_in_editor = snapshot
11497                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11498                .min(rename_range.end);
11499            drop(snapshot);
11500
11501            self.change_selections(None, window, cx, |s| {
11502                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11503            });
11504        } else {
11505            self.refresh_document_highlights(cx);
11506        }
11507
11508        Some(rename)
11509    }
11510
11511    pub fn pending_rename(&self) -> Option<&RenameState> {
11512        self.pending_rename.as_ref()
11513    }
11514
11515    fn format(
11516        &mut self,
11517        _: &Format,
11518        window: &mut Window,
11519        cx: &mut Context<Self>,
11520    ) -> Option<Task<Result<()>>> {
11521        let project = match &self.project {
11522            Some(project) => project.clone(),
11523            None => return None,
11524        };
11525
11526        Some(self.perform_format(
11527            project,
11528            FormatTrigger::Manual,
11529            FormatTarget::Buffers,
11530            window,
11531            cx,
11532        ))
11533    }
11534
11535    fn format_selections(
11536        &mut self,
11537        _: &FormatSelections,
11538        window: &mut Window,
11539        cx: &mut Context<Self>,
11540    ) -> Option<Task<Result<()>>> {
11541        let project = match &self.project {
11542            Some(project) => project.clone(),
11543            None => return None,
11544        };
11545
11546        let ranges = self
11547            .selections
11548            .all_adjusted(cx)
11549            .into_iter()
11550            .map(|selection| selection.range())
11551            .collect_vec();
11552
11553        Some(self.perform_format(
11554            project,
11555            FormatTrigger::Manual,
11556            FormatTarget::Ranges(ranges),
11557            window,
11558            cx,
11559        ))
11560    }
11561
11562    fn perform_format(
11563        &mut self,
11564        project: Entity<Project>,
11565        trigger: FormatTrigger,
11566        target: FormatTarget,
11567        window: &mut Window,
11568        cx: &mut Context<Self>,
11569    ) -> Task<Result<()>> {
11570        let buffer = self.buffer.clone();
11571        let (buffers, target) = match target {
11572            FormatTarget::Buffers => {
11573                let mut buffers = buffer.read(cx).all_buffers();
11574                if trigger == FormatTrigger::Save {
11575                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11576                }
11577                (buffers, LspFormatTarget::Buffers)
11578            }
11579            FormatTarget::Ranges(selection_ranges) => {
11580                let multi_buffer = buffer.read(cx);
11581                let snapshot = multi_buffer.read(cx);
11582                let mut buffers = HashSet::default();
11583                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11584                    BTreeMap::new();
11585                for selection_range in selection_ranges {
11586                    for (buffer, buffer_range, _) in
11587                        snapshot.range_to_buffer_ranges(selection_range)
11588                    {
11589                        let buffer_id = buffer.remote_id();
11590                        let start = buffer.anchor_before(buffer_range.start);
11591                        let end = buffer.anchor_after(buffer_range.end);
11592                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11593                        buffer_id_to_ranges
11594                            .entry(buffer_id)
11595                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11596                            .or_insert_with(|| vec![start..end]);
11597                    }
11598                }
11599                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11600            }
11601        };
11602
11603        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11604        let format = project.update(cx, |project, cx| {
11605            project.format(buffers, target, true, trigger, cx)
11606        });
11607
11608        cx.spawn_in(window, |_, mut cx| async move {
11609            let transaction = futures::select_biased! {
11610                () = timeout => {
11611                    log::warn!("timed out waiting for formatting");
11612                    None
11613                }
11614                transaction = format.log_err().fuse() => transaction,
11615            };
11616
11617            buffer
11618                .update(&mut cx, |buffer, cx| {
11619                    if let Some(transaction) = transaction {
11620                        if !buffer.is_singleton() {
11621                            buffer.push_transaction(&transaction.0, cx);
11622                        }
11623                    }
11624
11625                    cx.notify();
11626                })
11627                .ok();
11628
11629            Ok(())
11630        })
11631    }
11632
11633    fn restart_language_server(
11634        &mut self,
11635        _: &RestartLanguageServer,
11636        _: &mut Window,
11637        cx: &mut Context<Self>,
11638    ) {
11639        if let Some(project) = self.project.clone() {
11640            self.buffer.update(cx, |multi_buffer, cx| {
11641                project.update(cx, |project, cx| {
11642                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11643                });
11644            })
11645        }
11646    }
11647
11648    fn cancel_language_server_work(
11649        workspace: &mut Workspace,
11650        _: &actions::CancelLanguageServerWork,
11651        _: &mut Window,
11652        cx: &mut Context<Workspace>,
11653    ) {
11654        let project = workspace.project();
11655        let buffers = workspace
11656            .active_item(cx)
11657            .and_then(|item| item.act_as::<Editor>(cx))
11658            .map_or(HashSet::default(), |editor| {
11659                editor.read(cx).buffer.read(cx).all_buffers()
11660            });
11661        project.update(cx, |project, cx| {
11662            project.cancel_language_server_work_for_buffers(buffers, cx);
11663        });
11664    }
11665
11666    fn show_character_palette(
11667        &mut self,
11668        _: &ShowCharacterPalette,
11669        window: &mut Window,
11670        _: &mut Context<Self>,
11671    ) {
11672        window.show_character_palette();
11673    }
11674
11675    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11676        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11677            let buffer = self.buffer.read(cx).snapshot(cx);
11678            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11679            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11680            let is_valid = buffer
11681                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11682                .any(|entry| {
11683                    entry.diagnostic.is_primary
11684                        && !entry.range.is_empty()
11685                        && entry.range.start == primary_range_start
11686                        && entry.diagnostic.message == active_diagnostics.primary_message
11687                });
11688
11689            if is_valid != active_diagnostics.is_valid {
11690                active_diagnostics.is_valid = is_valid;
11691                let mut new_styles = HashMap::default();
11692                for (block_id, diagnostic) in &active_diagnostics.blocks {
11693                    new_styles.insert(
11694                        *block_id,
11695                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11696                    );
11697                }
11698                self.display_map.update(cx, |display_map, _cx| {
11699                    display_map.replace_blocks(new_styles)
11700                });
11701            }
11702        }
11703    }
11704
11705    fn activate_diagnostics(
11706        &mut self,
11707        buffer_id: BufferId,
11708        group_id: usize,
11709        window: &mut Window,
11710        cx: &mut Context<Self>,
11711    ) {
11712        self.dismiss_diagnostics(cx);
11713        let snapshot = self.snapshot(window, cx);
11714        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11715            let buffer = self.buffer.read(cx).snapshot(cx);
11716
11717            let mut primary_range = None;
11718            let mut primary_message = None;
11719            let diagnostic_group = buffer
11720                .diagnostic_group(buffer_id, group_id)
11721                .filter_map(|entry| {
11722                    let start = entry.range.start;
11723                    let end = entry.range.end;
11724                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11725                        && (start.row == end.row
11726                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11727                    {
11728                        return None;
11729                    }
11730                    if entry.diagnostic.is_primary {
11731                        primary_range = Some(entry.range.clone());
11732                        primary_message = Some(entry.diagnostic.message.clone());
11733                    }
11734                    Some(entry)
11735                })
11736                .collect::<Vec<_>>();
11737            let primary_range = primary_range?;
11738            let primary_message = primary_message?;
11739
11740            let blocks = display_map
11741                .insert_blocks(
11742                    diagnostic_group.iter().map(|entry| {
11743                        let diagnostic = entry.diagnostic.clone();
11744                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11745                        BlockProperties {
11746                            style: BlockStyle::Fixed,
11747                            placement: BlockPlacement::Below(
11748                                buffer.anchor_after(entry.range.start),
11749                            ),
11750                            height: message_height,
11751                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11752                            priority: 0,
11753                        }
11754                    }),
11755                    cx,
11756                )
11757                .into_iter()
11758                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11759                .collect();
11760
11761            Some(ActiveDiagnosticGroup {
11762                primary_range: buffer.anchor_before(primary_range.start)
11763                    ..buffer.anchor_after(primary_range.end),
11764                primary_message,
11765                group_id,
11766                blocks,
11767                is_valid: true,
11768            })
11769        });
11770    }
11771
11772    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11773        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11774            self.display_map.update(cx, |display_map, cx| {
11775                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11776            });
11777            cx.notify();
11778        }
11779    }
11780
11781    pub fn set_selections_from_remote(
11782        &mut self,
11783        selections: Vec<Selection<Anchor>>,
11784        pending_selection: Option<Selection<Anchor>>,
11785        window: &mut Window,
11786        cx: &mut Context<Self>,
11787    ) {
11788        let old_cursor_position = self.selections.newest_anchor().head();
11789        self.selections.change_with(cx, |s| {
11790            s.select_anchors(selections);
11791            if let Some(pending_selection) = pending_selection {
11792                s.set_pending(pending_selection, SelectMode::Character);
11793            } else {
11794                s.clear_pending();
11795            }
11796        });
11797        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11798    }
11799
11800    fn push_to_selection_history(&mut self) {
11801        self.selection_history.push(SelectionHistoryEntry {
11802            selections: self.selections.disjoint_anchors(),
11803            select_next_state: self.select_next_state.clone(),
11804            select_prev_state: self.select_prev_state.clone(),
11805            add_selections_state: self.add_selections_state.clone(),
11806        });
11807    }
11808
11809    pub fn transact(
11810        &mut self,
11811        window: &mut Window,
11812        cx: &mut Context<Self>,
11813        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11814    ) -> Option<TransactionId> {
11815        self.start_transaction_at(Instant::now(), window, cx);
11816        update(self, window, cx);
11817        self.end_transaction_at(Instant::now(), cx)
11818    }
11819
11820    pub fn start_transaction_at(
11821        &mut self,
11822        now: Instant,
11823        window: &mut Window,
11824        cx: &mut Context<Self>,
11825    ) {
11826        self.end_selection(window, cx);
11827        if let Some(tx_id) = self
11828            .buffer
11829            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11830        {
11831            self.selection_history
11832                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11833            cx.emit(EditorEvent::TransactionBegun {
11834                transaction_id: tx_id,
11835            })
11836        }
11837    }
11838
11839    pub fn end_transaction_at(
11840        &mut self,
11841        now: Instant,
11842        cx: &mut Context<Self>,
11843    ) -> Option<TransactionId> {
11844        if let Some(transaction_id) = self
11845            .buffer
11846            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11847        {
11848            if let Some((_, end_selections)) =
11849                self.selection_history.transaction_mut(transaction_id)
11850            {
11851                *end_selections = Some(self.selections.disjoint_anchors());
11852            } else {
11853                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11854            }
11855
11856            cx.emit(EditorEvent::Edited { transaction_id });
11857            Some(transaction_id)
11858        } else {
11859            None
11860        }
11861    }
11862
11863    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11864        if self.selection_mark_mode {
11865            self.change_selections(None, window, cx, |s| {
11866                s.move_with(|_, sel| {
11867                    sel.collapse_to(sel.head(), SelectionGoal::None);
11868                });
11869            })
11870        }
11871        self.selection_mark_mode = true;
11872        cx.notify();
11873    }
11874
11875    pub fn swap_selection_ends(
11876        &mut self,
11877        _: &actions::SwapSelectionEnds,
11878        window: &mut Window,
11879        cx: &mut Context<Self>,
11880    ) {
11881        self.change_selections(None, window, cx, |s| {
11882            s.move_with(|_, sel| {
11883                if sel.start != sel.end {
11884                    sel.reversed = !sel.reversed
11885                }
11886            });
11887        });
11888        self.request_autoscroll(Autoscroll::newest(), cx);
11889        cx.notify();
11890    }
11891
11892    pub fn toggle_fold(
11893        &mut self,
11894        _: &actions::ToggleFold,
11895        window: &mut Window,
11896        cx: &mut Context<Self>,
11897    ) {
11898        if self.is_singleton(cx) {
11899            let selection = self.selections.newest::<Point>(cx);
11900
11901            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11902            let range = if selection.is_empty() {
11903                let point = selection.head().to_display_point(&display_map);
11904                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11905                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11906                    .to_point(&display_map);
11907                start..end
11908            } else {
11909                selection.range()
11910            };
11911            if display_map.folds_in_range(range).next().is_some() {
11912                self.unfold_lines(&Default::default(), window, cx)
11913            } else {
11914                self.fold(&Default::default(), window, cx)
11915            }
11916        } else {
11917            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11918            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11919                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11920                .map(|(snapshot, _, _)| snapshot.remote_id())
11921                .collect();
11922
11923            for buffer_id in buffer_ids {
11924                if self.is_buffer_folded(buffer_id, cx) {
11925                    self.unfold_buffer(buffer_id, cx);
11926                } else {
11927                    self.fold_buffer(buffer_id, cx);
11928                }
11929            }
11930        }
11931    }
11932
11933    pub fn toggle_fold_recursive(
11934        &mut self,
11935        _: &actions::ToggleFoldRecursive,
11936        window: &mut Window,
11937        cx: &mut Context<Self>,
11938    ) {
11939        let selection = self.selections.newest::<Point>(cx);
11940
11941        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11942        let range = if selection.is_empty() {
11943            let point = selection.head().to_display_point(&display_map);
11944            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11945            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11946                .to_point(&display_map);
11947            start..end
11948        } else {
11949            selection.range()
11950        };
11951        if display_map.folds_in_range(range).next().is_some() {
11952            self.unfold_recursive(&Default::default(), window, cx)
11953        } else {
11954            self.fold_recursive(&Default::default(), window, cx)
11955        }
11956    }
11957
11958    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11959        if self.is_singleton(cx) {
11960            let mut to_fold = Vec::new();
11961            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11962            let selections = self.selections.all_adjusted(cx);
11963
11964            for selection in selections {
11965                let range = selection.range().sorted();
11966                let buffer_start_row = range.start.row;
11967
11968                if range.start.row != range.end.row {
11969                    let mut found = false;
11970                    let mut row = range.start.row;
11971                    while row <= range.end.row {
11972                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11973                        {
11974                            found = true;
11975                            row = crease.range().end.row + 1;
11976                            to_fold.push(crease);
11977                        } else {
11978                            row += 1
11979                        }
11980                    }
11981                    if found {
11982                        continue;
11983                    }
11984                }
11985
11986                for row in (0..=range.start.row).rev() {
11987                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11988                        if crease.range().end.row >= buffer_start_row {
11989                            to_fold.push(crease);
11990                            if row <= range.start.row {
11991                                break;
11992                            }
11993                        }
11994                    }
11995                }
11996            }
11997
11998            self.fold_creases(to_fold, true, window, cx);
11999        } else {
12000            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12001
12002            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12003                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12004                .map(|(snapshot, _, _)| snapshot.remote_id())
12005                .collect();
12006            for buffer_id in buffer_ids {
12007                self.fold_buffer(buffer_id, cx);
12008            }
12009        }
12010    }
12011
12012    fn fold_at_level(
12013        &mut self,
12014        fold_at: &FoldAtLevel,
12015        window: &mut Window,
12016        cx: &mut Context<Self>,
12017    ) {
12018        if !self.buffer.read(cx).is_singleton() {
12019            return;
12020        }
12021
12022        let fold_at_level = fold_at.0;
12023        let snapshot = self.buffer.read(cx).snapshot(cx);
12024        let mut to_fold = Vec::new();
12025        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12026
12027        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12028            while start_row < end_row {
12029                match self
12030                    .snapshot(window, cx)
12031                    .crease_for_buffer_row(MultiBufferRow(start_row))
12032                {
12033                    Some(crease) => {
12034                        let nested_start_row = crease.range().start.row + 1;
12035                        let nested_end_row = crease.range().end.row;
12036
12037                        if current_level < fold_at_level {
12038                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12039                        } else if current_level == fold_at_level {
12040                            to_fold.push(crease);
12041                        }
12042
12043                        start_row = nested_end_row + 1;
12044                    }
12045                    None => start_row += 1,
12046                }
12047            }
12048        }
12049
12050        self.fold_creases(to_fold, true, window, cx);
12051    }
12052
12053    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12054        if self.buffer.read(cx).is_singleton() {
12055            let mut fold_ranges = Vec::new();
12056            let snapshot = self.buffer.read(cx).snapshot(cx);
12057
12058            for row in 0..snapshot.max_row().0 {
12059                if let Some(foldable_range) = self
12060                    .snapshot(window, cx)
12061                    .crease_for_buffer_row(MultiBufferRow(row))
12062                {
12063                    fold_ranges.push(foldable_range);
12064                }
12065            }
12066
12067            self.fold_creases(fold_ranges, true, window, cx);
12068        } else {
12069            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12070                editor
12071                    .update_in(&mut cx, |editor, _, cx| {
12072                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12073                            editor.fold_buffer(buffer_id, cx);
12074                        }
12075                    })
12076                    .ok();
12077            });
12078        }
12079    }
12080
12081    pub fn fold_function_bodies(
12082        &mut self,
12083        _: &actions::FoldFunctionBodies,
12084        window: &mut Window,
12085        cx: &mut Context<Self>,
12086    ) {
12087        let snapshot = self.buffer.read(cx).snapshot(cx);
12088
12089        let ranges = snapshot
12090            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12091            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12092            .collect::<Vec<_>>();
12093
12094        let creases = ranges
12095            .into_iter()
12096            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12097            .collect();
12098
12099        self.fold_creases(creases, true, window, cx);
12100    }
12101
12102    pub fn fold_recursive(
12103        &mut self,
12104        _: &actions::FoldRecursive,
12105        window: &mut Window,
12106        cx: &mut Context<Self>,
12107    ) {
12108        let mut to_fold = Vec::new();
12109        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12110        let selections = self.selections.all_adjusted(cx);
12111
12112        for selection in selections {
12113            let range = selection.range().sorted();
12114            let buffer_start_row = range.start.row;
12115
12116            if range.start.row != range.end.row {
12117                let mut found = false;
12118                for row in range.start.row..=range.end.row {
12119                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12120                        found = true;
12121                        to_fold.push(crease);
12122                    }
12123                }
12124                if found {
12125                    continue;
12126                }
12127            }
12128
12129            for row in (0..=range.start.row).rev() {
12130                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12131                    if crease.range().end.row >= buffer_start_row {
12132                        to_fold.push(crease);
12133                    } else {
12134                        break;
12135                    }
12136                }
12137            }
12138        }
12139
12140        self.fold_creases(to_fold, true, window, cx);
12141    }
12142
12143    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12144        let buffer_row = fold_at.buffer_row;
12145        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12146
12147        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12148            let autoscroll = self
12149                .selections
12150                .all::<Point>(cx)
12151                .iter()
12152                .any(|selection| crease.range().overlaps(&selection.range()));
12153
12154            self.fold_creases(vec![crease], autoscroll, window, cx);
12155        }
12156    }
12157
12158    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12159        if self.is_singleton(cx) {
12160            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12161            let buffer = &display_map.buffer_snapshot;
12162            let selections = self.selections.all::<Point>(cx);
12163            let ranges = selections
12164                .iter()
12165                .map(|s| {
12166                    let range = s.display_range(&display_map).sorted();
12167                    let mut start = range.start.to_point(&display_map);
12168                    let mut end = range.end.to_point(&display_map);
12169                    start.column = 0;
12170                    end.column = buffer.line_len(MultiBufferRow(end.row));
12171                    start..end
12172                })
12173                .collect::<Vec<_>>();
12174
12175            self.unfold_ranges(&ranges, true, true, cx);
12176        } else {
12177            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12178            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12179                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12180                .map(|(snapshot, _, _)| snapshot.remote_id())
12181                .collect();
12182            for buffer_id in buffer_ids {
12183                self.unfold_buffer(buffer_id, cx);
12184            }
12185        }
12186    }
12187
12188    pub fn unfold_recursive(
12189        &mut self,
12190        _: &UnfoldRecursive,
12191        _window: &mut Window,
12192        cx: &mut Context<Self>,
12193    ) {
12194        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12195        let selections = self.selections.all::<Point>(cx);
12196        let ranges = selections
12197            .iter()
12198            .map(|s| {
12199                let mut range = s.display_range(&display_map).sorted();
12200                *range.start.column_mut() = 0;
12201                *range.end.column_mut() = display_map.line_len(range.end.row());
12202                let start = range.start.to_point(&display_map);
12203                let end = range.end.to_point(&display_map);
12204                start..end
12205            })
12206            .collect::<Vec<_>>();
12207
12208        self.unfold_ranges(&ranges, true, true, cx);
12209    }
12210
12211    pub fn unfold_at(
12212        &mut self,
12213        unfold_at: &UnfoldAt,
12214        _window: &mut Window,
12215        cx: &mut Context<Self>,
12216    ) {
12217        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12218
12219        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12220            ..Point::new(
12221                unfold_at.buffer_row.0,
12222                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12223            );
12224
12225        let autoscroll = self
12226            .selections
12227            .all::<Point>(cx)
12228            .iter()
12229            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12230
12231        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12232    }
12233
12234    pub fn unfold_all(
12235        &mut self,
12236        _: &actions::UnfoldAll,
12237        _window: &mut Window,
12238        cx: &mut Context<Self>,
12239    ) {
12240        if self.buffer.read(cx).is_singleton() {
12241            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12242            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12243        } else {
12244            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12245                editor
12246                    .update(&mut cx, |editor, cx| {
12247                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12248                            editor.unfold_buffer(buffer_id, cx);
12249                        }
12250                    })
12251                    .ok();
12252            });
12253        }
12254    }
12255
12256    pub fn fold_selected_ranges(
12257        &mut self,
12258        _: &FoldSelectedRanges,
12259        window: &mut Window,
12260        cx: &mut Context<Self>,
12261    ) {
12262        let selections = self.selections.all::<Point>(cx);
12263        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12264        let line_mode = self.selections.line_mode;
12265        let ranges = selections
12266            .into_iter()
12267            .map(|s| {
12268                if line_mode {
12269                    let start = Point::new(s.start.row, 0);
12270                    let end = Point::new(
12271                        s.end.row,
12272                        display_map
12273                            .buffer_snapshot
12274                            .line_len(MultiBufferRow(s.end.row)),
12275                    );
12276                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12277                } else {
12278                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12279                }
12280            })
12281            .collect::<Vec<_>>();
12282        self.fold_creases(ranges, true, window, cx);
12283    }
12284
12285    pub fn fold_ranges<T: ToOffset + Clone>(
12286        &mut self,
12287        ranges: Vec<Range<T>>,
12288        auto_scroll: bool,
12289        window: &mut Window,
12290        cx: &mut Context<Self>,
12291    ) {
12292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12293        let ranges = ranges
12294            .into_iter()
12295            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12296            .collect::<Vec<_>>();
12297        self.fold_creases(ranges, auto_scroll, window, cx);
12298    }
12299
12300    pub fn fold_creases<T: ToOffset + Clone>(
12301        &mut self,
12302        creases: Vec<Crease<T>>,
12303        auto_scroll: bool,
12304        window: &mut Window,
12305        cx: &mut Context<Self>,
12306    ) {
12307        if creases.is_empty() {
12308            return;
12309        }
12310
12311        let mut buffers_affected = HashSet::default();
12312        let multi_buffer = self.buffer().read(cx);
12313        for crease in &creases {
12314            if let Some((_, buffer, _)) =
12315                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12316            {
12317                buffers_affected.insert(buffer.read(cx).remote_id());
12318            };
12319        }
12320
12321        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12322
12323        if auto_scroll {
12324            self.request_autoscroll(Autoscroll::fit(), cx);
12325        }
12326
12327        cx.notify();
12328
12329        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12330            // Clear diagnostics block when folding a range that contains it.
12331            let snapshot = self.snapshot(window, cx);
12332            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12333                drop(snapshot);
12334                self.active_diagnostics = Some(active_diagnostics);
12335                self.dismiss_diagnostics(cx);
12336            } else {
12337                self.active_diagnostics = Some(active_diagnostics);
12338            }
12339        }
12340
12341        self.scrollbar_marker_state.dirty = true;
12342    }
12343
12344    /// Removes any folds whose ranges intersect any of the given ranges.
12345    pub fn unfold_ranges<T: ToOffset + Clone>(
12346        &mut self,
12347        ranges: &[Range<T>],
12348        inclusive: bool,
12349        auto_scroll: bool,
12350        cx: &mut Context<Self>,
12351    ) {
12352        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12353            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12354        });
12355    }
12356
12357    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12358        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12359            return;
12360        }
12361        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12362        self.display_map
12363            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12364        cx.emit(EditorEvent::BufferFoldToggled {
12365            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12366            folded: true,
12367        });
12368        cx.notify();
12369    }
12370
12371    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12372        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12373            return;
12374        }
12375        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12376        self.display_map.update(cx, |display_map, cx| {
12377            display_map.unfold_buffer(buffer_id, cx);
12378        });
12379        cx.emit(EditorEvent::BufferFoldToggled {
12380            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12381            folded: false,
12382        });
12383        cx.notify();
12384    }
12385
12386    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12387        self.display_map.read(cx).is_buffer_folded(buffer)
12388    }
12389
12390    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12391        self.display_map.read(cx).folded_buffers()
12392    }
12393
12394    /// Removes any folds with the given ranges.
12395    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12396        &mut self,
12397        ranges: &[Range<T>],
12398        type_id: TypeId,
12399        auto_scroll: bool,
12400        cx: &mut Context<Self>,
12401    ) {
12402        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12403            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12404        });
12405    }
12406
12407    fn remove_folds_with<T: ToOffset + Clone>(
12408        &mut self,
12409        ranges: &[Range<T>],
12410        auto_scroll: bool,
12411        cx: &mut Context<Self>,
12412        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12413    ) {
12414        if ranges.is_empty() {
12415            return;
12416        }
12417
12418        let mut buffers_affected = HashSet::default();
12419        let multi_buffer = self.buffer().read(cx);
12420        for range in ranges {
12421            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12422                buffers_affected.insert(buffer.read(cx).remote_id());
12423            };
12424        }
12425
12426        self.display_map.update(cx, update);
12427
12428        if auto_scroll {
12429            self.request_autoscroll(Autoscroll::fit(), cx);
12430        }
12431
12432        cx.notify();
12433        self.scrollbar_marker_state.dirty = true;
12434        self.active_indent_guides_state.dirty = true;
12435    }
12436
12437    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12438        self.display_map.read(cx).fold_placeholder.clone()
12439    }
12440
12441    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12442        self.buffer.update(cx, |buffer, cx| {
12443            buffer.set_all_diff_hunks_expanded(cx);
12444        });
12445    }
12446
12447    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12448        self.distinguish_unstaged_diff_hunks = true;
12449    }
12450
12451    pub fn expand_all_diff_hunks(
12452        &mut self,
12453        _: &ExpandAllHunkDiffs,
12454        _window: &mut Window,
12455        cx: &mut Context<Self>,
12456    ) {
12457        self.buffer.update(cx, |buffer, cx| {
12458            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12459        });
12460    }
12461
12462    pub fn toggle_selected_diff_hunks(
12463        &mut self,
12464        _: &ToggleSelectedDiffHunks,
12465        _window: &mut Window,
12466        cx: &mut Context<Self>,
12467    ) {
12468        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12469        self.toggle_diff_hunks_in_ranges(ranges, cx);
12470    }
12471
12472    fn diff_hunks_in_ranges<'a>(
12473        &'a self,
12474        ranges: &'a [Range<Anchor>],
12475        buffer: &'a MultiBufferSnapshot,
12476    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12477        ranges.iter().flat_map(move |range| {
12478            let end_excerpt_id = range.end.excerpt_id;
12479            let range = range.to_point(buffer);
12480            let mut peek_end = range.end;
12481            if range.end.row < buffer.max_row().0 {
12482                peek_end = Point::new(range.end.row + 1, 0);
12483            }
12484            buffer
12485                .diff_hunks_in_range(range.start..peek_end)
12486                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12487        })
12488    }
12489
12490    pub fn has_stageable_diff_hunks_in_ranges(
12491        &self,
12492        ranges: &[Range<Anchor>],
12493        snapshot: &MultiBufferSnapshot,
12494    ) -> bool {
12495        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12496        hunks.any(|hunk| {
12497            log::debug!("considering {hunk:?}");
12498            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12499        })
12500    }
12501
12502    pub fn toggle_staged_selected_diff_hunks(
12503        &mut self,
12504        _: &ToggleStagedSelectedDiffHunks,
12505        _window: &mut Window,
12506        cx: &mut Context<Self>,
12507    ) {
12508        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12509        self.stage_or_unstage_diff_hunks(&ranges, cx);
12510    }
12511
12512    pub fn stage_or_unstage_diff_hunks(
12513        &mut self,
12514        ranges: &[Range<Anchor>],
12515        cx: &mut Context<Self>,
12516    ) {
12517        let Some(project) = &self.project else {
12518            return;
12519        };
12520        let snapshot = self.buffer.read(cx).snapshot(cx);
12521        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12522
12523        let chunk_by = self
12524            .diff_hunks_in_ranges(&ranges, &snapshot)
12525            .chunk_by(|hunk| hunk.buffer_id);
12526        for (buffer_id, hunks) in &chunk_by {
12527            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12528                log::debug!("no buffer for id");
12529                continue;
12530            };
12531            let buffer = buffer.read(cx).snapshot();
12532            let Some((repo, path)) = project
12533                .read(cx)
12534                .repository_and_path_for_buffer_id(buffer_id, cx)
12535            else {
12536                log::debug!("no git repo for buffer id");
12537                continue;
12538            };
12539            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12540                log::debug!("no diff for buffer id");
12541                continue;
12542            };
12543            let Some(secondary_diff) = diff.secondary_diff() else {
12544                log::debug!("no secondary diff for buffer id");
12545                continue;
12546            };
12547
12548            let edits = diff.secondary_edits_for_stage_or_unstage(
12549                stage,
12550                hunks.map(|hunk| {
12551                    (
12552                        hunk.diff_base_byte_range.clone(),
12553                        hunk.secondary_diff_base_byte_range.clone(),
12554                        hunk.buffer_range.clone(),
12555                    )
12556                }),
12557                &buffer,
12558            );
12559
12560            let index_base = secondary_diff.base_text().map_or_else(
12561                || Rope::from(""),
12562                |snapshot| snapshot.text.as_rope().clone(),
12563            );
12564            let index_buffer = cx.new(|cx| {
12565                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12566            });
12567            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12568                index_buffer.edit(edits, None, cx);
12569                index_buffer.snapshot().as_rope().to_string()
12570            });
12571            let new_index_text = if new_index_text.is_empty()
12572                && (diff.is_single_insertion
12573                    || buffer
12574                        .file()
12575                        .map_or(false, |file| file.disk_state() == DiskState::New))
12576            {
12577                log::debug!("removing from index");
12578                None
12579            } else {
12580                Some(new_index_text)
12581            };
12582
12583            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12584        }
12585    }
12586
12587    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12588        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12589        self.buffer
12590            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12591    }
12592
12593    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12594        self.buffer.update(cx, |buffer, cx| {
12595            let ranges = vec![Anchor::min()..Anchor::max()];
12596            if !buffer.all_diff_hunks_expanded()
12597                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12598            {
12599                buffer.collapse_diff_hunks(ranges, cx);
12600                true
12601            } else {
12602                false
12603            }
12604        })
12605    }
12606
12607    fn toggle_diff_hunks_in_ranges(
12608        &mut self,
12609        ranges: Vec<Range<Anchor>>,
12610        cx: &mut Context<'_, Editor>,
12611    ) {
12612        self.buffer.update(cx, |buffer, cx| {
12613            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12614            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12615        })
12616    }
12617
12618    fn toggle_diff_hunks_in_ranges_narrow(
12619        &mut self,
12620        ranges: Vec<Range<Anchor>>,
12621        cx: &mut Context<'_, Editor>,
12622    ) {
12623        self.buffer.update(cx, |buffer, cx| {
12624            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12625            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12626        })
12627    }
12628
12629    pub(crate) fn apply_all_diff_hunks(
12630        &mut self,
12631        _: &ApplyAllDiffHunks,
12632        window: &mut Window,
12633        cx: &mut Context<Self>,
12634    ) {
12635        let buffers = self.buffer.read(cx).all_buffers();
12636        for branch_buffer in buffers {
12637            branch_buffer.update(cx, |branch_buffer, cx| {
12638                branch_buffer.merge_into_base(Vec::new(), cx);
12639            });
12640        }
12641
12642        if let Some(project) = self.project.clone() {
12643            self.save(true, project, window, cx).detach_and_log_err(cx);
12644        }
12645    }
12646
12647    pub(crate) fn apply_selected_diff_hunks(
12648        &mut self,
12649        _: &ApplyDiffHunk,
12650        window: &mut Window,
12651        cx: &mut Context<Self>,
12652    ) {
12653        let snapshot = self.snapshot(window, cx);
12654        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12655        let mut ranges_by_buffer = HashMap::default();
12656        self.transact(window, cx, |editor, _window, cx| {
12657            for hunk in hunks {
12658                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12659                    ranges_by_buffer
12660                        .entry(buffer.clone())
12661                        .or_insert_with(Vec::new)
12662                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12663                }
12664            }
12665
12666            for (buffer, ranges) in ranges_by_buffer {
12667                buffer.update(cx, |buffer, cx| {
12668                    buffer.merge_into_base(ranges, cx);
12669                });
12670            }
12671        });
12672
12673        if let Some(project) = self.project.clone() {
12674            self.save(true, project, window, cx).detach_and_log_err(cx);
12675        }
12676    }
12677
12678    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12679        if hovered != self.gutter_hovered {
12680            self.gutter_hovered = hovered;
12681            cx.notify();
12682        }
12683    }
12684
12685    pub fn insert_blocks(
12686        &mut self,
12687        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12688        autoscroll: Option<Autoscroll>,
12689        cx: &mut Context<Self>,
12690    ) -> Vec<CustomBlockId> {
12691        let blocks = self
12692            .display_map
12693            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12694        if let Some(autoscroll) = autoscroll {
12695            self.request_autoscroll(autoscroll, cx);
12696        }
12697        cx.notify();
12698        blocks
12699    }
12700
12701    pub fn resize_blocks(
12702        &mut self,
12703        heights: HashMap<CustomBlockId, u32>,
12704        autoscroll: Option<Autoscroll>,
12705        cx: &mut Context<Self>,
12706    ) {
12707        self.display_map
12708            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12709        if let Some(autoscroll) = autoscroll {
12710            self.request_autoscroll(autoscroll, cx);
12711        }
12712        cx.notify();
12713    }
12714
12715    pub fn replace_blocks(
12716        &mut self,
12717        renderers: HashMap<CustomBlockId, RenderBlock>,
12718        autoscroll: Option<Autoscroll>,
12719        cx: &mut Context<Self>,
12720    ) {
12721        self.display_map
12722            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12723        if let Some(autoscroll) = autoscroll {
12724            self.request_autoscroll(autoscroll, cx);
12725        }
12726        cx.notify();
12727    }
12728
12729    pub fn remove_blocks(
12730        &mut self,
12731        block_ids: HashSet<CustomBlockId>,
12732        autoscroll: Option<Autoscroll>,
12733        cx: &mut Context<Self>,
12734    ) {
12735        self.display_map.update(cx, |display_map, cx| {
12736            display_map.remove_blocks(block_ids, cx)
12737        });
12738        if let Some(autoscroll) = autoscroll {
12739            self.request_autoscroll(autoscroll, cx);
12740        }
12741        cx.notify();
12742    }
12743
12744    pub fn row_for_block(
12745        &self,
12746        block_id: CustomBlockId,
12747        cx: &mut Context<Self>,
12748    ) -> Option<DisplayRow> {
12749        self.display_map
12750            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12751    }
12752
12753    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12754        self.focused_block = Some(focused_block);
12755    }
12756
12757    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12758        self.focused_block.take()
12759    }
12760
12761    pub fn insert_creases(
12762        &mut self,
12763        creases: impl IntoIterator<Item = Crease<Anchor>>,
12764        cx: &mut Context<Self>,
12765    ) -> Vec<CreaseId> {
12766        self.display_map
12767            .update(cx, |map, cx| map.insert_creases(creases, cx))
12768    }
12769
12770    pub fn remove_creases(
12771        &mut self,
12772        ids: impl IntoIterator<Item = CreaseId>,
12773        cx: &mut Context<Self>,
12774    ) {
12775        self.display_map
12776            .update(cx, |map, cx| map.remove_creases(ids, cx));
12777    }
12778
12779    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12780        self.display_map
12781            .update(cx, |map, cx| map.snapshot(cx))
12782            .longest_row()
12783    }
12784
12785    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12786        self.display_map
12787            .update(cx, |map, cx| map.snapshot(cx))
12788            .max_point()
12789    }
12790
12791    pub fn text(&self, cx: &App) -> String {
12792        self.buffer.read(cx).read(cx).text()
12793    }
12794
12795    pub fn is_empty(&self, cx: &App) -> bool {
12796        self.buffer.read(cx).read(cx).is_empty()
12797    }
12798
12799    pub fn text_option(&self, cx: &App) -> Option<String> {
12800        let text = self.text(cx);
12801        let text = text.trim();
12802
12803        if text.is_empty() {
12804            return None;
12805        }
12806
12807        Some(text.to_string())
12808    }
12809
12810    pub fn set_text(
12811        &mut self,
12812        text: impl Into<Arc<str>>,
12813        window: &mut Window,
12814        cx: &mut Context<Self>,
12815    ) {
12816        self.transact(window, cx, |this, _, cx| {
12817            this.buffer
12818                .read(cx)
12819                .as_singleton()
12820                .expect("you can only call set_text on editors for singleton buffers")
12821                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12822        });
12823    }
12824
12825    pub fn display_text(&self, cx: &mut App) -> String {
12826        self.display_map
12827            .update(cx, |map, cx| map.snapshot(cx))
12828            .text()
12829    }
12830
12831    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12832        let mut wrap_guides = smallvec::smallvec![];
12833
12834        if self.show_wrap_guides == Some(false) {
12835            return wrap_guides;
12836        }
12837
12838        let settings = self.buffer.read(cx).settings_at(0, cx);
12839        if settings.show_wrap_guides {
12840            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12841                wrap_guides.push((soft_wrap as usize, true));
12842            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12843                wrap_guides.push((soft_wrap as usize, true));
12844            }
12845            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12846        }
12847
12848        wrap_guides
12849    }
12850
12851    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12852        let settings = self.buffer.read(cx).settings_at(0, cx);
12853        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12854        match mode {
12855            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12856                SoftWrap::None
12857            }
12858            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12859            language_settings::SoftWrap::PreferredLineLength => {
12860                SoftWrap::Column(settings.preferred_line_length)
12861            }
12862            language_settings::SoftWrap::Bounded => {
12863                SoftWrap::Bounded(settings.preferred_line_length)
12864            }
12865        }
12866    }
12867
12868    pub fn set_soft_wrap_mode(
12869        &mut self,
12870        mode: language_settings::SoftWrap,
12871
12872        cx: &mut Context<Self>,
12873    ) {
12874        self.soft_wrap_mode_override = Some(mode);
12875        cx.notify();
12876    }
12877
12878    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12879        self.text_style_refinement = Some(style);
12880    }
12881
12882    /// called by the Element so we know what style we were most recently rendered with.
12883    pub(crate) fn set_style(
12884        &mut self,
12885        style: EditorStyle,
12886        window: &mut Window,
12887        cx: &mut Context<Self>,
12888    ) {
12889        let rem_size = window.rem_size();
12890        self.display_map.update(cx, |map, cx| {
12891            map.set_font(
12892                style.text.font(),
12893                style.text.font_size.to_pixels(rem_size),
12894                cx,
12895            )
12896        });
12897        self.style = Some(style);
12898    }
12899
12900    pub fn style(&self) -> Option<&EditorStyle> {
12901        self.style.as_ref()
12902    }
12903
12904    // Called by the element. This method is not designed to be called outside of the editor
12905    // element's layout code because it does not notify when rewrapping is computed synchronously.
12906    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12907        self.display_map
12908            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12909    }
12910
12911    pub fn set_soft_wrap(&mut self) {
12912        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12913    }
12914
12915    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12916        if self.soft_wrap_mode_override.is_some() {
12917            self.soft_wrap_mode_override.take();
12918        } else {
12919            let soft_wrap = match self.soft_wrap_mode(cx) {
12920                SoftWrap::GitDiff => return,
12921                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12922                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12923                    language_settings::SoftWrap::None
12924                }
12925            };
12926            self.soft_wrap_mode_override = Some(soft_wrap);
12927        }
12928        cx.notify();
12929    }
12930
12931    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12932        let Some(workspace) = self.workspace() else {
12933            return;
12934        };
12935        let fs = workspace.read(cx).app_state().fs.clone();
12936        let current_show = TabBarSettings::get_global(cx).show;
12937        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12938            setting.show = Some(!current_show);
12939        });
12940    }
12941
12942    pub fn toggle_indent_guides(
12943        &mut self,
12944        _: &ToggleIndentGuides,
12945        _: &mut Window,
12946        cx: &mut Context<Self>,
12947    ) {
12948        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12949            self.buffer
12950                .read(cx)
12951                .settings_at(0, cx)
12952                .indent_guides
12953                .enabled
12954        });
12955        self.show_indent_guides = Some(!currently_enabled);
12956        cx.notify();
12957    }
12958
12959    fn should_show_indent_guides(&self) -> Option<bool> {
12960        self.show_indent_guides
12961    }
12962
12963    pub fn toggle_line_numbers(
12964        &mut self,
12965        _: &ToggleLineNumbers,
12966        _: &mut Window,
12967        cx: &mut Context<Self>,
12968    ) {
12969        let mut editor_settings = EditorSettings::get_global(cx).clone();
12970        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12971        EditorSettings::override_global(editor_settings, cx);
12972    }
12973
12974    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12975        self.use_relative_line_numbers
12976            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12977    }
12978
12979    pub fn toggle_relative_line_numbers(
12980        &mut self,
12981        _: &ToggleRelativeLineNumbers,
12982        _: &mut Window,
12983        cx: &mut Context<Self>,
12984    ) {
12985        let is_relative = self.should_use_relative_line_numbers(cx);
12986        self.set_relative_line_number(Some(!is_relative), cx)
12987    }
12988
12989    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12990        self.use_relative_line_numbers = is_relative;
12991        cx.notify();
12992    }
12993
12994    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12995        self.show_gutter = show_gutter;
12996        cx.notify();
12997    }
12998
12999    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13000        self.show_scrollbars = show_scrollbars;
13001        cx.notify();
13002    }
13003
13004    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13005        self.show_line_numbers = Some(show_line_numbers);
13006        cx.notify();
13007    }
13008
13009    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13010        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13011        cx.notify();
13012    }
13013
13014    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13015        self.show_code_actions = Some(show_code_actions);
13016        cx.notify();
13017    }
13018
13019    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13020        self.show_runnables = Some(show_runnables);
13021        cx.notify();
13022    }
13023
13024    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13025        if self.display_map.read(cx).masked != masked {
13026            self.display_map.update(cx, |map, _| map.masked = masked);
13027        }
13028        cx.notify()
13029    }
13030
13031    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13032        self.show_wrap_guides = Some(show_wrap_guides);
13033        cx.notify();
13034    }
13035
13036    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13037        self.show_indent_guides = Some(show_indent_guides);
13038        cx.notify();
13039    }
13040
13041    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13042        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13043            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13044                if let Some(dir) = file.abs_path(cx).parent() {
13045                    return Some(dir.to_owned());
13046                }
13047            }
13048
13049            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13050                return Some(project_path.path.to_path_buf());
13051            }
13052        }
13053
13054        None
13055    }
13056
13057    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13058        self.active_excerpt(cx)?
13059            .1
13060            .read(cx)
13061            .file()
13062            .and_then(|f| f.as_local())
13063    }
13064
13065    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13066        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13067            let buffer = buffer.read(cx);
13068            if let Some(project_path) = buffer.project_path(cx) {
13069                let project = self.project.as_ref()?.read(cx);
13070                project.absolute_path(&project_path, cx)
13071            } else {
13072                buffer
13073                    .file()
13074                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13075            }
13076        })
13077    }
13078
13079    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13080        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13081            let project_path = buffer.read(cx).project_path(cx)?;
13082            let project = self.project.as_ref()?.read(cx);
13083            let entry = project.entry_for_path(&project_path, cx)?;
13084            let path = entry.path.to_path_buf();
13085            Some(path)
13086        })
13087    }
13088
13089    pub fn reveal_in_finder(
13090        &mut self,
13091        _: &RevealInFileManager,
13092        _window: &mut Window,
13093        cx: &mut Context<Self>,
13094    ) {
13095        if let Some(target) = self.target_file(cx) {
13096            cx.reveal_path(&target.abs_path(cx));
13097        }
13098    }
13099
13100    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13101        if let Some(path) = self.target_file_abs_path(cx) {
13102            if let Some(path) = path.to_str() {
13103                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13104            }
13105        }
13106    }
13107
13108    pub fn copy_relative_path(
13109        &mut self,
13110        _: &CopyRelativePath,
13111        _window: &mut Window,
13112        cx: &mut Context<Self>,
13113    ) {
13114        if let Some(path) = self.target_file_path(cx) {
13115            if let Some(path) = path.to_str() {
13116                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13117            }
13118        }
13119    }
13120
13121    pub fn copy_file_name_without_extension(
13122        &mut self,
13123        _: &CopyFileNameWithoutExtension,
13124        _: &mut Window,
13125        cx: &mut Context<Self>,
13126    ) {
13127        if let Some(file) = self.target_file(cx) {
13128            if let Some(file_stem) = file.path().file_stem() {
13129                if let Some(name) = file_stem.to_str() {
13130                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13131                }
13132            }
13133        }
13134    }
13135
13136    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13137        if let Some(file) = self.target_file(cx) {
13138            if let Some(file_name) = file.path().file_name() {
13139                if let Some(name) = file_name.to_str() {
13140                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13141                }
13142            }
13143        }
13144    }
13145
13146    pub fn toggle_git_blame(
13147        &mut self,
13148        _: &ToggleGitBlame,
13149        window: &mut Window,
13150        cx: &mut Context<Self>,
13151    ) {
13152        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13153
13154        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13155            self.start_git_blame(true, window, cx);
13156        }
13157
13158        cx.notify();
13159    }
13160
13161    pub fn toggle_git_blame_inline(
13162        &mut self,
13163        _: &ToggleGitBlameInline,
13164        window: &mut Window,
13165        cx: &mut Context<Self>,
13166    ) {
13167        self.toggle_git_blame_inline_internal(true, window, cx);
13168        cx.notify();
13169    }
13170
13171    pub fn git_blame_inline_enabled(&self) -> bool {
13172        self.git_blame_inline_enabled
13173    }
13174
13175    pub fn toggle_selection_menu(
13176        &mut self,
13177        _: &ToggleSelectionMenu,
13178        _: &mut Window,
13179        cx: &mut Context<Self>,
13180    ) {
13181        self.show_selection_menu = self
13182            .show_selection_menu
13183            .map(|show_selections_menu| !show_selections_menu)
13184            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13185
13186        cx.notify();
13187    }
13188
13189    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13190        self.show_selection_menu
13191            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13192    }
13193
13194    fn start_git_blame(
13195        &mut self,
13196        user_triggered: bool,
13197        window: &mut Window,
13198        cx: &mut Context<Self>,
13199    ) {
13200        if let Some(project) = self.project.as_ref() {
13201            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13202                return;
13203            };
13204
13205            if buffer.read(cx).file().is_none() {
13206                return;
13207            }
13208
13209            let focused = self.focus_handle(cx).contains_focused(window, cx);
13210
13211            let project = project.clone();
13212            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13213            self.blame_subscription =
13214                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13215            self.blame = Some(blame);
13216        }
13217    }
13218
13219    fn toggle_git_blame_inline_internal(
13220        &mut self,
13221        user_triggered: bool,
13222        window: &mut Window,
13223        cx: &mut Context<Self>,
13224    ) {
13225        if self.git_blame_inline_enabled {
13226            self.git_blame_inline_enabled = false;
13227            self.show_git_blame_inline = false;
13228            self.show_git_blame_inline_delay_task.take();
13229        } else {
13230            self.git_blame_inline_enabled = true;
13231            self.start_git_blame_inline(user_triggered, window, cx);
13232        }
13233
13234        cx.notify();
13235    }
13236
13237    fn start_git_blame_inline(
13238        &mut self,
13239        user_triggered: bool,
13240        window: &mut Window,
13241        cx: &mut Context<Self>,
13242    ) {
13243        self.start_git_blame(user_triggered, window, cx);
13244
13245        if ProjectSettings::get_global(cx)
13246            .git
13247            .inline_blame_delay()
13248            .is_some()
13249        {
13250            self.start_inline_blame_timer(window, cx);
13251        } else {
13252            self.show_git_blame_inline = true
13253        }
13254    }
13255
13256    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13257        self.blame.as_ref()
13258    }
13259
13260    pub fn show_git_blame_gutter(&self) -> bool {
13261        self.show_git_blame_gutter
13262    }
13263
13264    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13265        self.show_git_blame_gutter && self.has_blame_entries(cx)
13266    }
13267
13268    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13269        self.show_git_blame_inline
13270            && self.focus_handle.is_focused(window)
13271            && !self.newest_selection_head_on_empty_line(cx)
13272            && self.has_blame_entries(cx)
13273    }
13274
13275    fn has_blame_entries(&self, cx: &App) -> bool {
13276        self.blame()
13277            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13278    }
13279
13280    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13281        let cursor_anchor = self.selections.newest_anchor().head();
13282
13283        let snapshot = self.buffer.read(cx).snapshot(cx);
13284        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13285
13286        snapshot.line_len(buffer_row) == 0
13287    }
13288
13289    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13290        let buffer_and_selection = maybe!({
13291            let selection = self.selections.newest::<Point>(cx);
13292            let selection_range = selection.range();
13293
13294            let multi_buffer = self.buffer().read(cx);
13295            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13296            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13297
13298            let (buffer, range, _) = if selection.reversed {
13299                buffer_ranges.first()
13300            } else {
13301                buffer_ranges.last()
13302            }?;
13303
13304            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13305                ..text::ToPoint::to_point(&range.end, &buffer).row;
13306            Some((
13307                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13308                selection,
13309            ))
13310        });
13311
13312        let Some((buffer, selection)) = buffer_and_selection else {
13313            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13314        };
13315
13316        let Some(project) = self.project.as_ref() else {
13317            return Task::ready(Err(anyhow!("editor does not have project")));
13318        };
13319
13320        project.update(cx, |project, cx| {
13321            project.get_permalink_to_line(&buffer, selection, cx)
13322        })
13323    }
13324
13325    pub fn copy_permalink_to_line(
13326        &mut self,
13327        _: &CopyPermalinkToLine,
13328        window: &mut Window,
13329        cx: &mut Context<Self>,
13330    ) {
13331        let permalink_task = self.get_permalink_to_line(cx);
13332        let workspace = self.workspace();
13333
13334        cx.spawn_in(window, |_, mut cx| async move {
13335            match permalink_task.await {
13336                Ok(permalink) => {
13337                    cx.update(|_, cx| {
13338                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13339                    })
13340                    .ok();
13341                }
13342                Err(err) => {
13343                    let message = format!("Failed to copy permalink: {err}");
13344
13345                    Err::<(), anyhow::Error>(err).log_err();
13346
13347                    if let Some(workspace) = workspace {
13348                        workspace
13349                            .update_in(&mut cx, |workspace, _, cx| {
13350                                struct CopyPermalinkToLine;
13351
13352                                workspace.show_toast(
13353                                    Toast::new(
13354                                        NotificationId::unique::<CopyPermalinkToLine>(),
13355                                        message,
13356                                    ),
13357                                    cx,
13358                                )
13359                            })
13360                            .ok();
13361                    }
13362                }
13363            }
13364        })
13365        .detach();
13366    }
13367
13368    pub fn copy_file_location(
13369        &mut self,
13370        _: &CopyFileLocation,
13371        _: &mut Window,
13372        cx: &mut Context<Self>,
13373    ) {
13374        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13375        if let Some(file) = self.target_file(cx) {
13376            if let Some(path) = file.path().to_str() {
13377                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13378            }
13379        }
13380    }
13381
13382    pub fn open_permalink_to_line(
13383        &mut self,
13384        _: &OpenPermalinkToLine,
13385        window: &mut Window,
13386        cx: &mut Context<Self>,
13387    ) {
13388        let permalink_task = self.get_permalink_to_line(cx);
13389        let workspace = self.workspace();
13390
13391        cx.spawn_in(window, |_, mut cx| async move {
13392            match permalink_task.await {
13393                Ok(permalink) => {
13394                    cx.update(|_, cx| {
13395                        cx.open_url(permalink.as_ref());
13396                    })
13397                    .ok();
13398                }
13399                Err(err) => {
13400                    let message = format!("Failed to open permalink: {err}");
13401
13402                    Err::<(), anyhow::Error>(err).log_err();
13403
13404                    if let Some(workspace) = workspace {
13405                        workspace
13406                            .update(&mut cx, |workspace, cx| {
13407                                struct OpenPermalinkToLine;
13408
13409                                workspace.show_toast(
13410                                    Toast::new(
13411                                        NotificationId::unique::<OpenPermalinkToLine>(),
13412                                        message,
13413                                    ),
13414                                    cx,
13415                                )
13416                            })
13417                            .ok();
13418                    }
13419                }
13420            }
13421        })
13422        .detach();
13423    }
13424
13425    pub fn insert_uuid_v4(
13426        &mut self,
13427        _: &InsertUuidV4,
13428        window: &mut Window,
13429        cx: &mut Context<Self>,
13430    ) {
13431        self.insert_uuid(UuidVersion::V4, window, cx);
13432    }
13433
13434    pub fn insert_uuid_v7(
13435        &mut self,
13436        _: &InsertUuidV7,
13437        window: &mut Window,
13438        cx: &mut Context<Self>,
13439    ) {
13440        self.insert_uuid(UuidVersion::V7, window, cx);
13441    }
13442
13443    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13444        self.transact(window, cx, |this, window, cx| {
13445            let edits = this
13446                .selections
13447                .all::<Point>(cx)
13448                .into_iter()
13449                .map(|selection| {
13450                    let uuid = match version {
13451                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13452                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13453                    };
13454
13455                    (selection.range(), uuid.to_string())
13456                });
13457            this.edit(edits, cx);
13458            this.refresh_inline_completion(true, false, window, cx);
13459        });
13460    }
13461
13462    pub fn open_selections_in_multibuffer(
13463        &mut self,
13464        _: &OpenSelectionsInMultibuffer,
13465        window: &mut Window,
13466        cx: &mut Context<Self>,
13467    ) {
13468        let multibuffer = self.buffer.read(cx);
13469
13470        let Some(buffer) = multibuffer.as_singleton() else {
13471            return;
13472        };
13473
13474        let Some(workspace) = self.workspace() else {
13475            return;
13476        };
13477
13478        let locations = self
13479            .selections
13480            .disjoint_anchors()
13481            .iter()
13482            .map(|range| Location {
13483                buffer: buffer.clone(),
13484                range: range.start.text_anchor..range.end.text_anchor,
13485            })
13486            .collect::<Vec<_>>();
13487
13488        let title = multibuffer.title(cx).to_string();
13489
13490        cx.spawn_in(window, |_, mut cx| async move {
13491            workspace.update_in(&mut cx, |workspace, window, cx| {
13492                Self::open_locations_in_multibuffer(
13493                    workspace,
13494                    locations,
13495                    format!("Selections for '{title}'"),
13496                    false,
13497                    MultibufferSelectionMode::All,
13498                    window,
13499                    cx,
13500                );
13501            })
13502        })
13503        .detach();
13504    }
13505
13506    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13507    /// last highlight added will be used.
13508    ///
13509    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13510    pub fn highlight_rows<T: 'static>(
13511        &mut self,
13512        range: Range<Anchor>,
13513        color: Hsla,
13514        should_autoscroll: bool,
13515        cx: &mut Context<Self>,
13516    ) {
13517        let snapshot = self.buffer().read(cx).snapshot(cx);
13518        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13519        let ix = row_highlights.binary_search_by(|highlight| {
13520            Ordering::Equal
13521                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13522                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13523        });
13524
13525        if let Err(mut ix) = ix {
13526            let index = post_inc(&mut self.highlight_order);
13527
13528            // If this range intersects with the preceding highlight, then merge it with
13529            // the preceding highlight. Otherwise insert a new highlight.
13530            let mut merged = false;
13531            if ix > 0 {
13532                let prev_highlight = &mut row_highlights[ix - 1];
13533                if prev_highlight
13534                    .range
13535                    .end
13536                    .cmp(&range.start, &snapshot)
13537                    .is_ge()
13538                {
13539                    ix -= 1;
13540                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13541                        prev_highlight.range.end = range.end;
13542                    }
13543                    merged = true;
13544                    prev_highlight.index = index;
13545                    prev_highlight.color = color;
13546                    prev_highlight.should_autoscroll = should_autoscroll;
13547                }
13548            }
13549
13550            if !merged {
13551                row_highlights.insert(
13552                    ix,
13553                    RowHighlight {
13554                        range: range.clone(),
13555                        index,
13556                        color,
13557                        should_autoscroll,
13558                    },
13559                );
13560            }
13561
13562            // If any of the following highlights intersect with this one, merge them.
13563            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13564                let highlight = &row_highlights[ix];
13565                if next_highlight
13566                    .range
13567                    .start
13568                    .cmp(&highlight.range.end, &snapshot)
13569                    .is_le()
13570                {
13571                    if next_highlight
13572                        .range
13573                        .end
13574                        .cmp(&highlight.range.end, &snapshot)
13575                        .is_gt()
13576                    {
13577                        row_highlights[ix].range.end = next_highlight.range.end;
13578                    }
13579                    row_highlights.remove(ix + 1);
13580                } else {
13581                    break;
13582                }
13583            }
13584        }
13585    }
13586
13587    /// Remove any highlighted row ranges of the given type that intersect the
13588    /// given ranges.
13589    pub fn remove_highlighted_rows<T: 'static>(
13590        &mut self,
13591        ranges_to_remove: Vec<Range<Anchor>>,
13592        cx: &mut Context<Self>,
13593    ) {
13594        let snapshot = self.buffer().read(cx).snapshot(cx);
13595        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13596        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13597        row_highlights.retain(|highlight| {
13598            while let Some(range_to_remove) = ranges_to_remove.peek() {
13599                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13600                    Ordering::Less | Ordering::Equal => {
13601                        ranges_to_remove.next();
13602                    }
13603                    Ordering::Greater => {
13604                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13605                            Ordering::Less | Ordering::Equal => {
13606                                return false;
13607                            }
13608                            Ordering::Greater => break,
13609                        }
13610                    }
13611                }
13612            }
13613
13614            true
13615        })
13616    }
13617
13618    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13619    pub fn clear_row_highlights<T: 'static>(&mut self) {
13620        self.highlighted_rows.remove(&TypeId::of::<T>());
13621    }
13622
13623    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13624    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13625        self.highlighted_rows
13626            .get(&TypeId::of::<T>())
13627            .map_or(&[] as &[_], |vec| vec.as_slice())
13628            .iter()
13629            .map(|highlight| (highlight.range.clone(), highlight.color))
13630    }
13631
13632    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13633    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13634    /// Allows to ignore certain kinds of highlights.
13635    pub fn highlighted_display_rows(
13636        &self,
13637        window: &mut Window,
13638        cx: &mut App,
13639    ) -> BTreeMap<DisplayRow, Background> {
13640        let snapshot = self.snapshot(window, cx);
13641        let mut used_highlight_orders = HashMap::default();
13642        self.highlighted_rows
13643            .iter()
13644            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13645            .fold(
13646                BTreeMap::<DisplayRow, Background>::new(),
13647                |mut unique_rows, highlight| {
13648                    let start = highlight.range.start.to_display_point(&snapshot);
13649                    let end = highlight.range.end.to_display_point(&snapshot);
13650                    let start_row = start.row().0;
13651                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13652                        && end.column() == 0
13653                    {
13654                        end.row().0.saturating_sub(1)
13655                    } else {
13656                        end.row().0
13657                    };
13658                    for row in start_row..=end_row {
13659                        let used_index =
13660                            used_highlight_orders.entry(row).or_insert(highlight.index);
13661                        if highlight.index >= *used_index {
13662                            *used_index = highlight.index;
13663                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13664                        }
13665                    }
13666                    unique_rows
13667                },
13668            )
13669    }
13670
13671    pub fn highlighted_display_row_for_autoscroll(
13672        &self,
13673        snapshot: &DisplaySnapshot,
13674    ) -> Option<DisplayRow> {
13675        self.highlighted_rows
13676            .values()
13677            .flat_map(|highlighted_rows| highlighted_rows.iter())
13678            .filter_map(|highlight| {
13679                if highlight.should_autoscroll {
13680                    Some(highlight.range.start.to_display_point(snapshot).row())
13681                } else {
13682                    None
13683                }
13684            })
13685            .min()
13686    }
13687
13688    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13689        self.highlight_background::<SearchWithinRange>(
13690            ranges,
13691            |colors| colors.editor_document_highlight_read_background,
13692            cx,
13693        )
13694    }
13695
13696    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13697        self.breadcrumb_header = Some(new_header);
13698    }
13699
13700    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13701        self.clear_background_highlights::<SearchWithinRange>(cx);
13702    }
13703
13704    pub fn highlight_background<T: 'static>(
13705        &mut self,
13706        ranges: &[Range<Anchor>],
13707        color_fetcher: fn(&ThemeColors) -> Hsla,
13708        cx: &mut Context<Self>,
13709    ) {
13710        self.background_highlights
13711            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13712        self.scrollbar_marker_state.dirty = true;
13713        cx.notify();
13714    }
13715
13716    pub fn clear_background_highlights<T: 'static>(
13717        &mut self,
13718        cx: &mut Context<Self>,
13719    ) -> Option<BackgroundHighlight> {
13720        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13721        if !text_highlights.1.is_empty() {
13722            self.scrollbar_marker_state.dirty = true;
13723            cx.notify();
13724        }
13725        Some(text_highlights)
13726    }
13727
13728    pub fn highlight_gutter<T: 'static>(
13729        &mut self,
13730        ranges: &[Range<Anchor>],
13731        color_fetcher: fn(&App) -> Hsla,
13732        cx: &mut Context<Self>,
13733    ) {
13734        self.gutter_highlights
13735            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13736        cx.notify();
13737    }
13738
13739    pub fn clear_gutter_highlights<T: 'static>(
13740        &mut self,
13741        cx: &mut Context<Self>,
13742    ) -> Option<GutterHighlight> {
13743        cx.notify();
13744        self.gutter_highlights.remove(&TypeId::of::<T>())
13745    }
13746
13747    #[cfg(feature = "test-support")]
13748    pub fn all_text_background_highlights(
13749        &self,
13750        window: &mut Window,
13751        cx: &mut Context<Self>,
13752    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13753        let snapshot = self.snapshot(window, cx);
13754        let buffer = &snapshot.buffer_snapshot;
13755        let start = buffer.anchor_before(0);
13756        let end = buffer.anchor_after(buffer.len());
13757        let theme = cx.theme().colors();
13758        self.background_highlights_in_range(start..end, &snapshot, theme)
13759    }
13760
13761    #[cfg(feature = "test-support")]
13762    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13763        let snapshot = self.buffer().read(cx).snapshot(cx);
13764
13765        let highlights = self
13766            .background_highlights
13767            .get(&TypeId::of::<items::BufferSearchHighlights>());
13768
13769        if let Some((_color, ranges)) = highlights {
13770            ranges
13771                .iter()
13772                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13773                .collect_vec()
13774        } else {
13775            vec![]
13776        }
13777    }
13778
13779    fn document_highlights_for_position<'a>(
13780        &'a self,
13781        position: Anchor,
13782        buffer: &'a MultiBufferSnapshot,
13783    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13784        let read_highlights = self
13785            .background_highlights
13786            .get(&TypeId::of::<DocumentHighlightRead>())
13787            .map(|h| &h.1);
13788        let write_highlights = self
13789            .background_highlights
13790            .get(&TypeId::of::<DocumentHighlightWrite>())
13791            .map(|h| &h.1);
13792        let left_position = position.bias_left(buffer);
13793        let right_position = position.bias_right(buffer);
13794        read_highlights
13795            .into_iter()
13796            .chain(write_highlights)
13797            .flat_map(move |ranges| {
13798                let start_ix = match ranges.binary_search_by(|probe| {
13799                    let cmp = probe.end.cmp(&left_position, buffer);
13800                    if cmp.is_ge() {
13801                        Ordering::Greater
13802                    } else {
13803                        Ordering::Less
13804                    }
13805                }) {
13806                    Ok(i) | Err(i) => i,
13807                };
13808
13809                ranges[start_ix..]
13810                    .iter()
13811                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13812            })
13813    }
13814
13815    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13816        self.background_highlights
13817            .get(&TypeId::of::<T>())
13818            .map_or(false, |(_, highlights)| !highlights.is_empty())
13819    }
13820
13821    pub fn background_highlights_in_range(
13822        &self,
13823        search_range: Range<Anchor>,
13824        display_snapshot: &DisplaySnapshot,
13825        theme: &ThemeColors,
13826    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13827        let mut results = Vec::new();
13828        for (color_fetcher, ranges) in self.background_highlights.values() {
13829            let color = color_fetcher(theme);
13830            let start_ix = match ranges.binary_search_by(|probe| {
13831                let cmp = probe
13832                    .end
13833                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13834                if cmp.is_gt() {
13835                    Ordering::Greater
13836                } else {
13837                    Ordering::Less
13838                }
13839            }) {
13840                Ok(i) | Err(i) => i,
13841            };
13842            for range in &ranges[start_ix..] {
13843                if range
13844                    .start
13845                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13846                    .is_ge()
13847                {
13848                    break;
13849                }
13850
13851                let start = range.start.to_display_point(display_snapshot);
13852                let end = range.end.to_display_point(display_snapshot);
13853                results.push((start..end, color))
13854            }
13855        }
13856        results
13857    }
13858
13859    pub fn background_highlight_row_ranges<T: 'static>(
13860        &self,
13861        search_range: Range<Anchor>,
13862        display_snapshot: &DisplaySnapshot,
13863        count: usize,
13864    ) -> Vec<RangeInclusive<DisplayPoint>> {
13865        let mut results = Vec::new();
13866        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13867            return vec![];
13868        };
13869
13870        let start_ix = match ranges.binary_search_by(|probe| {
13871            let cmp = probe
13872                .end
13873                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13874            if cmp.is_gt() {
13875                Ordering::Greater
13876            } else {
13877                Ordering::Less
13878            }
13879        }) {
13880            Ok(i) | Err(i) => i,
13881        };
13882        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13883            if let (Some(start_display), Some(end_display)) = (start, end) {
13884                results.push(
13885                    start_display.to_display_point(display_snapshot)
13886                        ..=end_display.to_display_point(display_snapshot),
13887                );
13888            }
13889        };
13890        let mut start_row: Option<Point> = None;
13891        let mut end_row: Option<Point> = None;
13892        if ranges.len() > count {
13893            return Vec::new();
13894        }
13895        for range in &ranges[start_ix..] {
13896            if range
13897                .start
13898                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13899                .is_ge()
13900            {
13901                break;
13902            }
13903            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13904            if let Some(current_row) = &end_row {
13905                if end.row == current_row.row {
13906                    continue;
13907                }
13908            }
13909            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13910            if start_row.is_none() {
13911                assert_eq!(end_row, None);
13912                start_row = Some(start);
13913                end_row = Some(end);
13914                continue;
13915            }
13916            if let Some(current_end) = end_row.as_mut() {
13917                if start.row > current_end.row + 1 {
13918                    push_region(start_row, end_row);
13919                    start_row = Some(start);
13920                    end_row = Some(end);
13921                } else {
13922                    // Merge two hunks.
13923                    *current_end = end;
13924                }
13925            } else {
13926                unreachable!();
13927            }
13928        }
13929        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13930        push_region(start_row, end_row);
13931        results
13932    }
13933
13934    pub fn gutter_highlights_in_range(
13935        &self,
13936        search_range: Range<Anchor>,
13937        display_snapshot: &DisplaySnapshot,
13938        cx: &App,
13939    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13940        let mut results = Vec::new();
13941        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13942            let color = color_fetcher(cx);
13943            let start_ix = match ranges.binary_search_by(|probe| {
13944                let cmp = probe
13945                    .end
13946                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13947                if cmp.is_gt() {
13948                    Ordering::Greater
13949                } else {
13950                    Ordering::Less
13951                }
13952            }) {
13953                Ok(i) | Err(i) => i,
13954            };
13955            for range in &ranges[start_ix..] {
13956                if range
13957                    .start
13958                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13959                    .is_ge()
13960                {
13961                    break;
13962                }
13963
13964                let start = range.start.to_display_point(display_snapshot);
13965                let end = range.end.to_display_point(display_snapshot);
13966                results.push((start..end, color))
13967            }
13968        }
13969        results
13970    }
13971
13972    /// Get the text ranges corresponding to the redaction query
13973    pub fn redacted_ranges(
13974        &self,
13975        search_range: Range<Anchor>,
13976        display_snapshot: &DisplaySnapshot,
13977        cx: &App,
13978    ) -> Vec<Range<DisplayPoint>> {
13979        display_snapshot
13980            .buffer_snapshot
13981            .redacted_ranges(search_range, |file| {
13982                if let Some(file) = file {
13983                    file.is_private()
13984                        && EditorSettings::get(
13985                            Some(SettingsLocation {
13986                                worktree_id: file.worktree_id(cx),
13987                                path: file.path().as_ref(),
13988                            }),
13989                            cx,
13990                        )
13991                        .redact_private_values
13992                } else {
13993                    false
13994                }
13995            })
13996            .map(|range| {
13997                range.start.to_display_point(display_snapshot)
13998                    ..range.end.to_display_point(display_snapshot)
13999            })
14000            .collect()
14001    }
14002
14003    pub fn highlight_text<T: 'static>(
14004        &mut self,
14005        ranges: Vec<Range<Anchor>>,
14006        style: HighlightStyle,
14007        cx: &mut Context<Self>,
14008    ) {
14009        self.display_map.update(cx, |map, _| {
14010            map.highlight_text(TypeId::of::<T>(), ranges, style)
14011        });
14012        cx.notify();
14013    }
14014
14015    pub(crate) fn highlight_inlays<T: 'static>(
14016        &mut self,
14017        highlights: Vec<InlayHighlight>,
14018        style: HighlightStyle,
14019        cx: &mut Context<Self>,
14020    ) {
14021        self.display_map.update(cx, |map, _| {
14022            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14023        });
14024        cx.notify();
14025    }
14026
14027    pub fn text_highlights<'a, T: 'static>(
14028        &'a self,
14029        cx: &'a App,
14030    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14031        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14032    }
14033
14034    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14035        let cleared = self
14036            .display_map
14037            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14038        if cleared {
14039            cx.notify();
14040        }
14041    }
14042
14043    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14044        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14045            && self.focus_handle.is_focused(window)
14046    }
14047
14048    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14049        self.show_cursor_when_unfocused = is_enabled;
14050        cx.notify();
14051    }
14052
14053    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14054        self.project
14055            .as_ref()
14056            .map(|project| project.read(cx).lsp_store())
14057    }
14058
14059    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14060        cx.notify();
14061    }
14062
14063    fn on_buffer_event(
14064        &mut self,
14065        multibuffer: &Entity<MultiBuffer>,
14066        event: &multi_buffer::Event,
14067        window: &mut Window,
14068        cx: &mut Context<Self>,
14069    ) {
14070        match event {
14071            multi_buffer::Event::Edited {
14072                singleton_buffer_edited,
14073                edited_buffer: buffer_edited,
14074            } => {
14075                self.scrollbar_marker_state.dirty = true;
14076                self.active_indent_guides_state.dirty = true;
14077                self.refresh_active_diagnostics(cx);
14078                self.refresh_code_actions(window, cx);
14079                if self.has_active_inline_completion() {
14080                    self.update_visible_inline_completion(window, cx);
14081                }
14082                if let Some(buffer) = buffer_edited {
14083                    let buffer_id = buffer.read(cx).remote_id();
14084                    if !self.registered_buffers.contains_key(&buffer_id) {
14085                        if let Some(lsp_store) = self.lsp_store(cx) {
14086                            lsp_store.update(cx, |lsp_store, cx| {
14087                                self.registered_buffers.insert(
14088                                    buffer_id,
14089                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14090                                );
14091                            })
14092                        }
14093                    }
14094                }
14095                cx.emit(EditorEvent::BufferEdited);
14096                cx.emit(SearchEvent::MatchesInvalidated);
14097                if *singleton_buffer_edited {
14098                    if let Some(project) = &self.project {
14099                        let project = project.read(cx);
14100                        #[allow(clippy::mutable_key_type)]
14101                        let languages_affected = multibuffer
14102                            .read(cx)
14103                            .all_buffers()
14104                            .into_iter()
14105                            .filter_map(|buffer| {
14106                                let buffer = buffer.read(cx);
14107                                let language = buffer.language()?;
14108                                if project.is_local()
14109                                    && project
14110                                        .language_servers_for_local_buffer(buffer, cx)
14111                                        .count()
14112                                        == 0
14113                                {
14114                                    None
14115                                } else {
14116                                    Some(language)
14117                                }
14118                            })
14119                            .cloned()
14120                            .collect::<HashSet<_>>();
14121                        if !languages_affected.is_empty() {
14122                            self.refresh_inlay_hints(
14123                                InlayHintRefreshReason::BufferEdited(languages_affected),
14124                                cx,
14125                            );
14126                        }
14127                    }
14128                }
14129
14130                let Some(project) = &self.project else { return };
14131                let (telemetry, is_via_ssh) = {
14132                    let project = project.read(cx);
14133                    let telemetry = project.client().telemetry().clone();
14134                    let is_via_ssh = project.is_via_ssh();
14135                    (telemetry, is_via_ssh)
14136                };
14137                refresh_linked_ranges(self, window, cx);
14138                telemetry.log_edit_event("editor", is_via_ssh);
14139            }
14140            multi_buffer::Event::ExcerptsAdded {
14141                buffer,
14142                predecessor,
14143                excerpts,
14144            } => {
14145                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14146                let buffer_id = buffer.read(cx).remote_id();
14147                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14148                    if let Some(project) = &self.project {
14149                        get_uncommitted_diff_for_buffer(
14150                            project,
14151                            [buffer.clone()],
14152                            self.buffer.clone(),
14153                            cx,
14154                        );
14155                    }
14156                }
14157                cx.emit(EditorEvent::ExcerptsAdded {
14158                    buffer: buffer.clone(),
14159                    predecessor: *predecessor,
14160                    excerpts: excerpts.clone(),
14161                });
14162                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14163            }
14164            multi_buffer::Event::ExcerptsRemoved { ids } => {
14165                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14166                let buffer = self.buffer.read(cx);
14167                self.registered_buffers
14168                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14169                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14170            }
14171            multi_buffer::Event::ExcerptsEdited { ids } => {
14172                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14173            }
14174            multi_buffer::Event::ExcerptsExpanded { ids } => {
14175                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14176                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14177            }
14178            multi_buffer::Event::Reparsed(buffer_id) => {
14179                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14180
14181                cx.emit(EditorEvent::Reparsed(*buffer_id));
14182            }
14183            multi_buffer::Event::DiffHunksToggled => {
14184                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14185            }
14186            multi_buffer::Event::LanguageChanged(buffer_id) => {
14187                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14188                cx.emit(EditorEvent::Reparsed(*buffer_id));
14189                cx.notify();
14190            }
14191            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14192            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14193            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14194                cx.emit(EditorEvent::TitleChanged)
14195            }
14196            // multi_buffer::Event::DiffBaseChanged => {
14197            //     self.scrollbar_marker_state.dirty = true;
14198            //     cx.emit(EditorEvent::DiffBaseChanged);
14199            //     cx.notify();
14200            // }
14201            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14202            multi_buffer::Event::DiagnosticsUpdated => {
14203                self.refresh_active_diagnostics(cx);
14204                self.scrollbar_marker_state.dirty = true;
14205                cx.notify();
14206            }
14207            _ => {}
14208        };
14209    }
14210
14211    fn on_display_map_changed(
14212        &mut self,
14213        _: Entity<DisplayMap>,
14214        _: &mut Window,
14215        cx: &mut Context<Self>,
14216    ) {
14217        cx.notify();
14218    }
14219
14220    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14221        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14222        self.refresh_inline_completion(true, false, window, cx);
14223        self.refresh_inlay_hints(
14224            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14225                self.selections.newest_anchor().head(),
14226                &self.buffer.read(cx).snapshot(cx),
14227                cx,
14228            )),
14229            cx,
14230        );
14231
14232        let old_cursor_shape = self.cursor_shape;
14233
14234        {
14235            let editor_settings = EditorSettings::get_global(cx);
14236            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14237            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14238            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14239        }
14240
14241        if old_cursor_shape != self.cursor_shape {
14242            cx.emit(EditorEvent::CursorShapeChanged);
14243        }
14244
14245        let project_settings = ProjectSettings::get_global(cx);
14246        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14247
14248        if self.mode == EditorMode::Full {
14249            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14250            if self.git_blame_inline_enabled != inline_blame_enabled {
14251                self.toggle_git_blame_inline_internal(false, window, cx);
14252            }
14253        }
14254
14255        cx.notify();
14256    }
14257
14258    pub fn set_searchable(&mut self, searchable: bool) {
14259        self.searchable = searchable;
14260    }
14261
14262    pub fn searchable(&self) -> bool {
14263        self.searchable
14264    }
14265
14266    fn open_proposed_changes_editor(
14267        &mut self,
14268        _: &OpenProposedChangesEditor,
14269        window: &mut Window,
14270        cx: &mut Context<Self>,
14271    ) {
14272        let Some(workspace) = self.workspace() else {
14273            cx.propagate();
14274            return;
14275        };
14276
14277        let selections = self.selections.all::<usize>(cx);
14278        let multi_buffer = self.buffer.read(cx);
14279        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14280        let mut new_selections_by_buffer = HashMap::default();
14281        for selection in selections {
14282            for (buffer, range, _) in
14283                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14284            {
14285                let mut range = range.to_point(buffer);
14286                range.start.column = 0;
14287                range.end.column = buffer.line_len(range.end.row);
14288                new_selections_by_buffer
14289                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14290                    .or_insert(Vec::new())
14291                    .push(range)
14292            }
14293        }
14294
14295        let proposed_changes_buffers = new_selections_by_buffer
14296            .into_iter()
14297            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14298            .collect::<Vec<_>>();
14299        let proposed_changes_editor = cx.new(|cx| {
14300            ProposedChangesEditor::new(
14301                "Proposed changes",
14302                proposed_changes_buffers,
14303                self.project.clone(),
14304                window,
14305                cx,
14306            )
14307        });
14308
14309        window.defer(cx, move |window, cx| {
14310            workspace.update(cx, |workspace, cx| {
14311                workspace.active_pane().update(cx, |pane, cx| {
14312                    pane.add_item(
14313                        Box::new(proposed_changes_editor),
14314                        true,
14315                        true,
14316                        None,
14317                        window,
14318                        cx,
14319                    );
14320                });
14321            });
14322        });
14323    }
14324
14325    pub fn open_excerpts_in_split(
14326        &mut self,
14327        _: &OpenExcerptsSplit,
14328        window: &mut Window,
14329        cx: &mut Context<Self>,
14330    ) {
14331        self.open_excerpts_common(None, true, window, cx)
14332    }
14333
14334    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14335        self.open_excerpts_common(None, false, window, cx)
14336    }
14337
14338    fn open_excerpts_common(
14339        &mut self,
14340        jump_data: Option<JumpData>,
14341        split: bool,
14342        window: &mut Window,
14343        cx: &mut Context<Self>,
14344    ) {
14345        let Some(workspace) = self.workspace() else {
14346            cx.propagate();
14347            return;
14348        };
14349
14350        if self.buffer.read(cx).is_singleton() {
14351            cx.propagate();
14352            return;
14353        }
14354
14355        let mut new_selections_by_buffer = HashMap::default();
14356        match &jump_data {
14357            Some(JumpData::MultiBufferPoint {
14358                excerpt_id,
14359                position,
14360                anchor,
14361                line_offset_from_top,
14362            }) => {
14363                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14364                if let Some(buffer) = multi_buffer_snapshot
14365                    .buffer_id_for_excerpt(*excerpt_id)
14366                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14367                {
14368                    let buffer_snapshot = buffer.read(cx).snapshot();
14369                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14370                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14371                    } else {
14372                        buffer_snapshot.clip_point(*position, Bias::Left)
14373                    };
14374                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14375                    new_selections_by_buffer.insert(
14376                        buffer,
14377                        (
14378                            vec![jump_to_offset..jump_to_offset],
14379                            Some(*line_offset_from_top),
14380                        ),
14381                    );
14382                }
14383            }
14384            Some(JumpData::MultiBufferRow {
14385                row,
14386                line_offset_from_top,
14387            }) => {
14388                let point = MultiBufferPoint::new(row.0, 0);
14389                if let Some((buffer, buffer_point, _)) =
14390                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14391                {
14392                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14393                    new_selections_by_buffer
14394                        .entry(buffer)
14395                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14396                        .0
14397                        .push(buffer_offset..buffer_offset)
14398                }
14399            }
14400            None => {
14401                let selections = self.selections.all::<usize>(cx);
14402                let multi_buffer = self.buffer.read(cx);
14403                for selection in selections {
14404                    for (buffer, mut range, _) in multi_buffer
14405                        .snapshot(cx)
14406                        .range_to_buffer_ranges(selection.range())
14407                    {
14408                        // When editing branch buffers, jump to the corresponding location
14409                        // in their base buffer.
14410                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14411                        let buffer = buffer_handle.read(cx);
14412                        if let Some(base_buffer) = buffer.base_buffer() {
14413                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14414                            buffer_handle = base_buffer;
14415                        }
14416
14417                        if selection.reversed {
14418                            mem::swap(&mut range.start, &mut range.end);
14419                        }
14420                        new_selections_by_buffer
14421                            .entry(buffer_handle)
14422                            .or_insert((Vec::new(), None))
14423                            .0
14424                            .push(range)
14425                    }
14426                }
14427            }
14428        }
14429
14430        if new_selections_by_buffer.is_empty() {
14431            return;
14432        }
14433
14434        // We defer the pane interaction because we ourselves are a workspace item
14435        // and activating a new item causes the pane to call a method on us reentrantly,
14436        // which panics if we're on the stack.
14437        window.defer(cx, move |window, cx| {
14438            workspace.update(cx, |workspace, cx| {
14439                let pane = if split {
14440                    workspace.adjacent_pane(window, cx)
14441                } else {
14442                    workspace.active_pane().clone()
14443                };
14444
14445                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14446                    let editor = buffer
14447                        .read(cx)
14448                        .file()
14449                        .is_none()
14450                        .then(|| {
14451                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14452                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14453                            // Instead, we try to activate the existing editor in the pane first.
14454                            let (editor, pane_item_index) =
14455                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14456                                    let editor = item.downcast::<Editor>()?;
14457                                    let singleton_buffer =
14458                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14459                                    if singleton_buffer == buffer {
14460                                        Some((editor, i))
14461                                    } else {
14462                                        None
14463                                    }
14464                                })?;
14465                            pane.update(cx, |pane, cx| {
14466                                pane.activate_item(pane_item_index, true, true, window, cx)
14467                            });
14468                            Some(editor)
14469                        })
14470                        .flatten()
14471                        .unwrap_or_else(|| {
14472                            workspace.open_project_item::<Self>(
14473                                pane.clone(),
14474                                buffer,
14475                                true,
14476                                true,
14477                                window,
14478                                cx,
14479                            )
14480                        });
14481
14482                    editor.update(cx, |editor, cx| {
14483                        let autoscroll = match scroll_offset {
14484                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14485                            None => Autoscroll::newest(),
14486                        };
14487                        let nav_history = editor.nav_history.take();
14488                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14489                            s.select_ranges(ranges);
14490                        });
14491                        editor.nav_history = nav_history;
14492                    });
14493                }
14494            })
14495        });
14496    }
14497
14498    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14499        let snapshot = self.buffer.read(cx).read(cx);
14500        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14501        Some(
14502            ranges
14503                .iter()
14504                .map(move |range| {
14505                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14506                })
14507                .collect(),
14508        )
14509    }
14510
14511    fn selection_replacement_ranges(
14512        &self,
14513        range: Range<OffsetUtf16>,
14514        cx: &mut App,
14515    ) -> Vec<Range<OffsetUtf16>> {
14516        let selections = self.selections.all::<OffsetUtf16>(cx);
14517        let newest_selection = selections
14518            .iter()
14519            .max_by_key(|selection| selection.id)
14520            .unwrap();
14521        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14522        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14523        let snapshot = self.buffer.read(cx).read(cx);
14524        selections
14525            .into_iter()
14526            .map(|mut selection| {
14527                selection.start.0 =
14528                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14529                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14530                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14531                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14532            })
14533            .collect()
14534    }
14535
14536    fn report_editor_event(
14537        &self,
14538        event_type: &'static str,
14539        file_extension: Option<String>,
14540        cx: &App,
14541    ) {
14542        if cfg!(any(test, feature = "test-support")) {
14543            return;
14544        }
14545
14546        let Some(project) = &self.project else { return };
14547
14548        // If None, we are in a file without an extension
14549        let file = self
14550            .buffer
14551            .read(cx)
14552            .as_singleton()
14553            .and_then(|b| b.read(cx).file());
14554        let file_extension = file_extension.or(file
14555            .as_ref()
14556            .and_then(|file| Path::new(file.file_name(cx)).extension())
14557            .and_then(|e| e.to_str())
14558            .map(|a| a.to_string()));
14559
14560        let vim_mode = cx
14561            .global::<SettingsStore>()
14562            .raw_user_settings()
14563            .get("vim_mode")
14564            == Some(&serde_json::Value::Bool(true));
14565
14566        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14567        let copilot_enabled = edit_predictions_provider
14568            == language::language_settings::EditPredictionProvider::Copilot;
14569        let copilot_enabled_for_language = self
14570            .buffer
14571            .read(cx)
14572            .settings_at(0, cx)
14573            .show_edit_predictions;
14574
14575        let project = project.read(cx);
14576        telemetry::event!(
14577            event_type,
14578            file_extension,
14579            vim_mode,
14580            copilot_enabled,
14581            copilot_enabled_for_language,
14582            edit_predictions_provider,
14583            is_via_ssh = project.is_via_ssh(),
14584        );
14585    }
14586
14587    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14588    /// with each line being an array of {text, highlight} objects.
14589    fn copy_highlight_json(
14590        &mut self,
14591        _: &CopyHighlightJson,
14592        window: &mut Window,
14593        cx: &mut Context<Self>,
14594    ) {
14595        #[derive(Serialize)]
14596        struct Chunk<'a> {
14597            text: String,
14598            highlight: Option<&'a str>,
14599        }
14600
14601        let snapshot = self.buffer.read(cx).snapshot(cx);
14602        let range = self
14603            .selected_text_range(false, window, cx)
14604            .and_then(|selection| {
14605                if selection.range.is_empty() {
14606                    None
14607                } else {
14608                    Some(selection.range)
14609                }
14610            })
14611            .unwrap_or_else(|| 0..snapshot.len());
14612
14613        let chunks = snapshot.chunks(range, true);
14614        let mut lines = Vec::new();
14615        let mut line: VecDeque<Chunk> = VecDeque::new();
14616
14617        let Some(style) = self.style.as_ref() else {
14618            return;
14619        };
14620
14621        for chunk in chunks {
14622            let highlight = chunk
14623                .syntax_highlight_id
14624                .and_then(|id| id.name(&style.syntax));
14625            let mut chunk_lines = chunk.text.split('\n').peekable();
14626            while let Some(text) = chunk_lines.next() {
14627                let mut merged_with_last_token = false;
14628                if let Some(last_token) = line.back_mut() {
14629                    if last_token.highlight == highlight {
14630                        last_token.text.push_str(text);
14631                        merged_with_last_token = true;
14632                    }
14633                }
14634
14635                if !merged_with_last_token {
14636                    line.push_back(Chunk {
14637                        text: text.into(),
14638                        highlight,
14639                    });
14640                }
14641
14642                if chunk_lines.peek().is_some() {
14643                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14644                        line.pop_front();
14645                    }
14646                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14647                        line.pop_back();
14648                    }
14649
14650                    lines.push(mem::take(&mut line));
14651                }
14652            }
14653        }
14654
14655        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14656            return;
14657        };
14658        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14659    }
14660
14661    pub fn open_context_menu(
14662        &mut self,
14663        _: &OpenContextMenu,
14664        window: &mut Window,
14665        cx: &mut Context<Self>,
14666    ) {
14667        self.request_autoscroll(Autoscroll::newest(), cx);
14668        let position = self.selections.newest_display(cx).start;
14669        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14670    }
14671
14672    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14673        &self.inlay_hint_cache
14674    }
14675
14676    pub fn replay_insert_event(
14677        &mut self,
14678        text: &str,
14679        relative_utf16_range: Option<Range<isize>>,
14680        window: &mut Window,
14681        cx: &mut Context<Self>,
14682    ) {
14683        if !self.input_enabled {
14684            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14685            return;
14686        }
14687        if let Some(relative_utf16_range) = relative_utf16_range {
14688            let selections = self.selections.all::<OffsetUtf16>(cx);
14689            self.change_selections(None, window, cx, |s| {
14690                let new_ranges = selections.into_iter().map(|range| {
14691                    let start = OffsetUtf16(
14692                        range
14693                            .head()
14694                            .0
14695                            .saturating_add_signed(relative_utf16_range.start),
14696                    );
14697                    let end = OffsetUtf16(
14698                        range
14699                            .head()
14700                            .0
14701                            .saturating_add_signed(relative_utf16_range.end),
14702                    );
14703                    start..end
14704                });
14705                s.select_ranges(new_ranges);
14706            });
14707        }
14708
14709        self.handle_input(text, window, cx);
14710    }
14711
14712    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14713        let Some(provider) = self.semantics_provider.as_ref() else {
14714            return false;
14715        };
14716
14717        let mut supports = false;
14718        self.buffer().read(cx).for_each_buffer(|buffer| {
14719            supports |= provider.supports_inlay_hints(buffer, cx);
14720        });
14721        supports
14722    }
14723
14724    pub fn is_focused(&self, window: &Window) -> bool {
14725        self.focus_handle.is_focused(window)
14726    }
14727
14728    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14729        cx.emit(EditorEvent::Focused);
14730
14731        if let Some(descendant) = self
14732            .last_focused_descendant
14733            .take()
14734            .and_then(|descendant| descendant.upgrade())
14735        {
14736            window.focus(&descendant);
14737        } else {
14738            if let Some(blame) = self.blame.as_ref() {
14739                blame.update(cx, GitBlame::focus)
14740            }
14741
14742            self.blink_manager.update(cx, BlinkManager::enable);
14743            self.show_cursor_names(window, cx);
14744            self.buffer.update(cx, |buffer, cx| {
14745                buffer.finalize_last_transaction(cx);
14746                if self.leader_peer_id.is_none() {
14747                    buffer.set_active_selections(
14748                        &self.selections.disjoint_anchors(),
14749                        self.selections.line_mode,
14750                        self.cursor_shape,
14751                        cx,
14752                    );
14753                }
14754            });
14755        }
14756    }
14757
14758    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14759        cx.emit(EditorEvent::FocusedIn)
14760    }
14761
14762    fn handle_focus_out(
14763        &mut self,
14764        event: FocusOutEvent,
14765        _window: &mut Window,
14766        _cx: &mut Context<Self>,
14767    ) {
14768        if event.blurred != self.focus_handle {
14769            self.last_focused_descendant = Some(event.blurred);
14770        }
14771    }
14772
14773    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14774        self.blink_manager.update(cx, BlinkManager::disable);
14775        self.buffer
14776            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14777
14778        if let Some(blame) = self.blame.as_ref() {
14779            blame.update(cx, GitBlame::blur)
14780        }
14781        if !self.hover_state.focused(window, cx) {
14782            hide_hover(self, cx);
14783        }
14784
14785        self.hide_context_menu(window, cx);
14786        self.discard_inline_completion(false, cx);
14787        cx.emit(EditorEvent::Blurred);
14788        cx.notify();
14789    }
14790
14791    pub fn register_action<A: Action>(
14792        &mut self,
14793        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14794    ) -> Subscription {
14795        let id = self.next_editor_action_id.post_inc();
14796        let listener = Arc::new(listener);
14797        self.editor_actions.borrow_mut().insert(
14798            id,
14799            Box::new(move |window, _| {
14800                let listener = listener.clone();
14801                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14802                    let action = action.downcast_ref().unwrap();
14803                    if phase == DispatchPhase::Bubble {
14804                        listener(action, window, cx)
14805                    }
14806                })
14807            }),
14808        );
14809
14810        let editor_actions = self.editor_actions.clone();
14811        Subscription::new(move || {
14812            editor_actions.borrow_mut().remove(&id);
14813        })
14814    }
14815
14816    pub fn file_header_size(&self) -> u32 {
14817        FILE_HEADER_HEIGHT
14818    }
14819
14820    pub fn revert(
14821        &mut self,
14822        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14823        window: &mut Window,
14824        cx: &mut Context<Self>,
14825    ) {
14826        self.buffer().update(cx, |multi_buffer, cx| {
14827            for (buffer_id, changes) in revert_changes {
14828                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14829                    buffer.update(cx, |buffer, cx| {
14830                        buffer.edit(
14831                            changes.into_iter().map(|(range, text)| {
14832                                (range, text.to_string().map(Arc::<str>::from))
14833                            }),
14834                            None,
14835                            cx,
14836                        );
14837                    });
14838                }
14839            }
14840        });
14841        self.change_selections(None, window, cx, |selections| selections.refresh());
14842    }
14843
14844    pub fn to_pixel_point(
14845        &self,
14846        source: multi_buffer::Anchor,
14847        editor_snapshot: &EditorSnapshot,
14848        window: &mut Window,
14849    ) -> Option<gpui::Point<Pixels>> {
14850        let source_point = source.to_display_point(editor_snapshot);
14851        self.display_to_pixel_point(source_point, editor_snapshot, window)
14852    }
14853
14854    pub fn display_to_pixel_point(
14855        &self,
14856        source: DisplayPoint,
14857        editor_snapshot: &EditorSnapshot,
14858        window: &mut Window,
14859    ) -> Option<gpui::Point<Pixels>> {
14860        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14861        let text_layout_details = self.text_layout_details(window);
14862        let scroll_top = text_layout_details
14863            .scroll_anchor
14864            .scroll_position(editor_snapshot)
14865            .y;
14866
14867        if source.row().as_f32() < scroll_top.floor() {
14868            return None;
14869        }
14870        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14871        let source_y = line_height * (source.row().as_f32() - scroll_top);
14872        Some(gpui::Point::new(source_x, source_y))
14873    }
14874
14875    pub fn has_visible_completions_menu(&self) -> bool {
14876        !self.edit_prediction_preview_is_active()
14877            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14878                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14879            })
14880    }
14881
14882    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14883        self.addons
14884            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14885    }
14886
14887    pub fn unregister_addon<T: Addon>(&mut self) {
14888        self.addons.remove(&std::any::TypeId::of::<T>());
14889    }
14890
14891    pub fn addon<T: Addon>(&self) -> Option<&T> {
14892        let type_id = std::any::TypeId::of::<T>();
14893        self.addons
14894            .get(&type_id)
14895            .and_then(|item| item.to_any().downcast_ref::<T>())
14896    }
14897
14898    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14899        let text_layout_details = self.text_layout_details(window);
14900        let style = &text_layout_details.editor_style;
14901        let font_id = window.text_system().resolve_font(&style.text.font());
14902        let font_size = style.text.font_size.to_pixels(window.rem_size());
14903        let line_height = style.text.line_height_in_pixels(window.rem_size());
14904        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14905
14906        gpui::Size::new(em_width, line_height)
14907    }
14908}
14909
14910fn get_uncommitted_diff_for_buffer(
14911    project: &Entity<Project>,
14912    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14913    buffer: Entity<MultiBuffer>,
14914    cx: &mut App,
14915) {
14916    let mut tasks = Vec::new();
14917    project.update(cx, |project, cx| {
14918        for buffer in buffers {
14919            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14920        }
14921    });
14922    cx.spawn(|mut cx| async move {
14923        let diffs = futures::future::join_all(tasks).await;
14924        buffer
14925            .update(&mut cx, |buffer, cx| {
14926                for diff in diffs.into_iter().flatten() {
14927                    buffer.add_diff(diff, cx);
14928                }
14929            })
14930            .ok();
14931    })
14932    .detach();
14933}
14934
14935fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14936    let tab_size = tab_size.get() as usize;
14937    let mut width = offset;
14938
14939    for ch in text.chars() {
14940        width += if ch == '\t' {
14941            tab_size - (width % tab_size)
14942        } else {
14943            1
14944        };
14945    }
14946
14947    width - offset
14948}
14949
14950#[cfg(test)]
14951mod tests {
14952    use super::*;
14953
14954    #[test]
14955    fn test_string_size_with_expanded_tabs() {
14956        let nz = |val| NonZeroU32::new(val).unwrap();
14957        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14958        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14959        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14960        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14961        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14962        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14963        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14964        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14965    }
14966}
14967
14968/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14969struct WordBreakingTokenizer<'a> {
14970    input: &'a str,
14971}
14972
14973impl<'a> WordBreakingTokenizer<'a> {
14974    fn new(input: &'a str) -> Self {
14975        Self { input }
14976    }
14977}
14978
14979fn is_char_ideographic(ch: char) -> bool {
14980    use unicode_script::Script::*;
14981    use unicode_script::UnicodeScript;
14982    matches!(ch.script(), Han | Tangut | Yi)
14983}
14984
14985fn is_grapheme_ideographic(text: &str) -> bool {
14986    text.chars().any(is_char_ideographic)
14987}
14988
14989fn is_grapheme_whitespace(text: &str) -> bool {
14990    text.chars().any(|x| x.is_whitespace())
14991}
14992
14993fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14994    text.chars().next().map_or(false, |ch| {
14995        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14996    })
14997}
14998
14999#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15000struct WordBreakToken<'a> {
15001    token: &'a str,
15002    grapheme_len: usize,
15003    is_whitespace: bool,
15004}
15005
15006impl<'a> Iterator for WordBreakingTokenizer<'a> {
15007    /// Yields a span, the count of graphemes in the token, and whether it was
15008    /// whitespace. Note that it also breaks at word boundaries.
15009    type Item = WordBreakToken<'a>;
15010
15011    fn next(&mut self) -> Option<Self::Item> {
15012        use unicode_segmentation::UnicodeSegmentation;
15013        if self.input.is_empty() {
15014            return None;
15015        }
15016
15017        let mut iter = self.input.graphemes(true).peekable();
15018        let mut offset = 0;
15019        let mut graphemes = 0;
15020        if let Some(first_grapheme) = iter.next() {
15021            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15022            offset += first_grapheme.len();
15023            graphemes += 1;
15024            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15025                if let Some(grapheme) = iter.peek().copied() {
15026                    if should_stay_with_preceding_ideograph(grapheme) {
15027                        offset += grapheme.len();
15028                        graphemes += 1;
15029                    }
15030                }
15031            } else {
15032                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15033                let mut next_word_bound = words.peek().copied();
15034                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15035                    next_word_bound = words.next();
15036                }
15037                while let Some(grapheme) = iter.peek().copied() {
15038                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15039                        break;
15040                    };
15041                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15042                        break;
15043                    };
15044                    offset += grapheme.len();
15045                    graphemes += 1;
15046                    iter.next();
15047                }
15048            }
15049            let token = &self.input[..offset];
15050            self.input = &self.input[offset..];
15051            if is_whitespace {
15052                Some(WordBreakToken {
15053                    token: " ",
15054                    grapheme_len: 1,
15055                    is_whitespace: true,
15056                })
15057            } else {
15058                Some(WordBreakToken {
15059                    token,
15060                    grapheme_len: graphemes,
15061                    is_whitespace: false,
15062                })
15063            }
15064        } else {
15065            None
15066        }
15067    }
15068}
15069
15070#[test]
15071fn test_word_breaking_tokenizer() {
15072    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15073        ("", &[]),
15074        ("  ", &[(" ", 1, true)]),
15075        ("Ʒ", &[("Ʒ", 1, false)]),
15076        ("Ǽ", &[("Ǽ", 1, false)]),
15077        ("", &[("", 1, false)]),
15078        ("⋑⋑", &[("⋑⋑", 2, false)]),
15079        (
15080            "原理,进而",
15081            &[
15082                ("", 1, false),
15083                ("理,", 2, false),
15084                ("", 1, false),
15085                ("", 1, false),
15086            ],
15087        ),
15088        (
15089            "hello world",
15090            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15091        ),
15092        (
15093            "hello, world",
15094            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15095        ),
15096        (
15097            "  hello world",
15098            &[
15099                (" ", 1, true),
15100                ("hello", 5, false),
15101                (" ", 1, true),
15102                ("world", 5, false),
15103            ],
15104        ),
15105        (
15106            "这是什么 \n 钢笔",
15107            &[
15108                ("", 1, false),
15109                ("", 1, false),
15110                ("", 1, false),
15111                ("", 1, false),
15112                (" ", 1, true),
15113                ("", 1, false),
15114                ("", 1, false),
15115            ],
15116        ),
15117        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15118    ];
15119
15120    for (input, result) in tests {
15121        assert_eq!(
15122            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15123            result
15124                .iter()
15125                .copied()
15126                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15127                    token,
15128                    grapheme_len,
15129                    is_whitespace,
15130                })
15131                .collect::<Vec<_>>()
15132        );
15133    }
15134}
15135
15136fn wrap_with_prefix(
15137    line_prefix: String,
15138    unwrapped_text: String,
15139    wrap_column: usize,
15140    tab_size: NonZeroU32,
15141) -> String {
15142    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15143    let mut wrapped_text = String::new();
15144    let mut current_line = line_prefix.clone();
15145
15146    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15147    let mut current_line_len = line_prefix_len;
15148    for WordBreakToken {
15149        token,
15150        grapheme_len,
15151        is_whitespace,
15152    } in tokenizer
15153    {
15154        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15155            wrapped_text.push_str(current_line.trim_end());
15156            wrapped_text.push('\n');
15157            current_line.truncate(line_prefix.len());
15158            current_line_len = line_prefix_len;
15159            if !is_whitespace {
15160                current_line.push_str(token);
15161                current_line_len += grapheme_len;
15162            }
15163        } else if !is_whitespace {
15164            current_line.push_str(token);
15165            current_line_len += grapheme_len;
15166        } else if current_line_len != line_prefix_len {
15167            current_line.push(' ');
15168            current_line_len += 1;
15169        }
15170    }
15171
15172    if !current_line.is_empty() {
15173        wrapped_text.push_str(&current_line);
15174    }
15175    wrapped_text
15176}
15177
15178#[test]
15179fn test_wrap_with_prefix() {
15180    assert_eq!(
15181        wrap_with_prefix(
15182            "# ".to_string(),
15183            "abcdefg".to_string(),
15184            4,
15185            NonZeroU32::new(4).unwrap()
15186        ),
15187        "# abcdefg"
15188    );
15189    assert_eq!(
15190        wrap_with_prefix(
15191            "".to_string(),
15192            "\thello world".to_string(),
15193            8,
15194            NonZeroU32::new(4).unwrap()
15195        ),
15196        "hello\nworld"
15197    );
15198    assert_eq!(
15199        wrap_with_prefix(
15200            "// ".to_string(),
15201            "xx \nyy zz aa bb cc".to_string(),
15202            12,
15203            NonZeroU32::new(4).unwrap()
15204        ),
15205        "// xx yy zz\n// aa bb cc"
15206    );
15207    assert_eq!(
15208        wrap_with_prefix(
15209            String::new(),
15210            "这是什么 \n 钢笔".to_string(),
15211            3,
15212            NonZeroU32::new(4).unwrap()
15213        ),
15214        "这是什\n么 钢\n"
15215    );
15216}
15217
15218pub trait CollaborationHub {
15219    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15220    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15221    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15222}
15223
15224impl CollaborationHub for Entity<Project> {
15225    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15226        self.read(cx).collaborators()
15227    }
15228
15229    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15230        self.read(cx).user_store().read(cx).participant_indices()
15231    }
15232
15233    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15234        let this = self.read(cx);
15235        let user_ids = this.collaborators().values().map(|c| c.user_id);
15236        this.user_store().read_with(cx, |user_store, cx| {
15237            user_store.participant_names(user_ids, cx)
15238        })
15239    }
15240}
15241
15242pub trait SemanticsProvider {
15243    fn hover(
15244        &self,
15245        buffer: &Entity<Buffer>,
15246        position: text::Anchor,
15247        cx: &mut App,
15248    ) -> Option<Task<Vec<project::Hover>>>;
15249
15250    fn inlay_hints(
15251        &self,
15252        buffer_handle: Entity<Buffer>,
15253        range: Range<text::Anchor>,
15254        cx: &mut App,
15255    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15256
15257    fn resolve_inlay_hint(
15258        &self,
15259        hint: InlayHint,
15260        buffer_handle: Entity<Buffer>,
15261        server_id: LanguageServerId,
15262        cx: &mut App,
15263    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15264
15265    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15266
15267    fn document_highlights(
15268        &self,
15269        buffer: &Entity<Buffer>,
15270        position: text::Anchor,
15271        cx: &mut App,
15272    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15273
15274    fn definitions(
15275        &self,
15276        buffer: &Entity<Buffer>,
15277        position: text::Anchor,
15278        kind: GotoDefinitionKind,
15279        cx: &mut App,
15280    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15281
15282    fn range_for_rename(
15283        &self,
15284        buffer: &Entity<Buffer>,
15285        position: text::Anchor,
15286        cx: &mut App,
15287    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15288
15289    fn perform_rename(
15290        &self,
15291        buffer: &Entity<Buffer>,
15292        position: text::Anchor,
15293        new_name: String,
15294        cx: &mut App,
15295    ) -> Option<Task<Result<ProjectTransaction>>>;
15296}
15297
15298pub trait CompletionProvider {
15299    fn completions(
15300        &self,
15301        buffer: &Entity<Buffer>,
15302        buffer_position: text::Anchor,
15303        trigger: CompletionContext,
15304        window: &mut Window,
15305        cx: &mut Context<Editor>,
15306    ) -> Task<Result<Vec<Completion>>>;
15307
15308    fn resolve_completions(
15309        &self,
15310        buffer: Entity<Buffer>,
15311        completion_indices: Vec<usize>,
15312        completions: Rc<RefCell<Box<[Completion]>>>,
15313        cx: &mut Context<Editor>,
15314    ) -> Task<Result<bool>>;
15315
15316    fn apply_additional_edits_for_completion(
15317        &self,
15318        _buffer: Entity<Buffer>,
15319        _completions: Rc<RefCell<Box<[Completion]>>>,
15320        _completion_index: usize,
15321        _push_to_history: bool,
15322        _cx: &mut Context<Editor>,
15323    ) -> Task<Result<Option<language::Transaction>>> {
15324        Task::ready(Ok(None))
15325    }
15326
15327    fn is_completion_trigger(
15328        &self,
15329        buffer: &Entity<Buffer>,
15330        position: language::Anchor,
15331        text: &str,
15332        trigger_in_words: bool,
15333        cx: &mut Context<Editor>,
15334    ) -> bool;
15335
15336    fn sort_completions(&self) -> bool {
15337        true
15338    }
15339}
15340
15341pub trait CodeActionProvider {
15342    fn id(&self) -> Arc<str>;
15343
15344    fn code_actions(
15345        &self,
15346        buffer: &Entity<Buffer>,
15347        range: Range<text::Anchor>,
15348        window: &mut Window,
15349        cx: &mut App,
15350    ) -> Task<Result<Vec<CodeAction>>>;
15351
15352    fn apply_code_action(
15353        &self,
15354        buffer_handle: Entity<Buffer>,
15355        action: CodeAction,
15356        excerpt_id: ExcerptId,
15357        push_to_history: bool,
15358        window: &mut Window,
15359        cx: &mut App,
15360    ) -> Task<Result<ProjectTransaction>>;
15361}
15362
15363impl CodeActionProvider for Entity<Project> {
15364    fn id(&self) -> Arc<str> {
15365        "project".into()
15366    }
15367
15368    fn code_actions(
15369        &self,
15370        buffer: &Entity<Buffer>,
15371        range: Range<text::Anchor>,
15372        _window: &mut Window,
15373        cx: &mut App,
15374    ) -> Task<Result<Vec<CodeAction>>> {
15375        self.update(cx, |project, cx| {
15376            project.code_actions(buffer, range, None, cx)
15377        })
15378    }
15379
15380    fn apply_code_action(
15381        &self,
15382        buffer_handle: Entity<Buffer>,
15383        action: CodeAction,
15384        _excerpt_id: ExcerptId,
15385        push_to_history: bool,
15386        _window: &mut Window,
15387        cx: &mut App,
15388    ) -> Task<Result<ProjectTransaction>> {
15389        self.update(cx, |project, cx| {
15390            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15391        })
15392    }
15393}
15394
15395fn snippet_completions(
15396    project: &Project,
15397    buffer: &Entity<Buffer>,
15398    buffer_position: text::Anchor,
15399    cx: &mut App,
15400) -> Task<Result<Vec<Completion>>> {
15401    let language = buffer.read(cx).language_at(buffer_position);
15402    let language_name = language.as_ref().map(|language| language.lsp_id());
15403    let snippet_store = project.snippets().read(cx);
15404    let snippets = snippet_store.snippets_for(language_name, cx);
15405
15406    if snippets.is_empty() {
15407        return Task::ready(Ok(vec![]));
15408    }
15409    let snapshot = buffer.read(cx).text_snapshot();
15410    let chars: String = snapshot
15411        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15412        .collect();
15413
15414    let scope = language.map(|language| language.default_scope());
15415    let executor = cx.background_executor().clone();
15416
15417    cx.background_executor().spawn(async move {
15418        let classifier = CharClassifier::new(scope).for_completion(true);
15419        let mut last_word = chars
15420            .chars()
15421            .take_while(|c| classifier.is_word(*c))
15422            .collect::<String>();
15423        last_word = last_word.chars().rev().collect();
15424
15425        if last_word.is_empty() {
15426            return Ok(vec![]);
15427        }
15428
15429        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15430        let to_lsp = |point: &text::Anchor| {
15431            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15432            point_to_lsp(end)
15433        };
15434        let lsp_end = to_lsp(&buffer_position);
15435
15436        let candidates = snippets
15437            .iter()
15438            .enumerate()
15439            .flat_map(|(ix, snippet)| {
15440                snippet
15441                    .prefix
15442                    .iter()
15443                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15444            })
15445            .collect::<Vec<StringMatchCandidate>>();
15446
15447        let mut matches = fuzzy::match_strings(
15448            &candidates,
15449            &last_word,
15450            last_word.chars().any(|c| c.is_uppercase()),
15451            100,
15452            &Default::default(),
15453            executor,
15454        )
15455        .await;
15456
15457        // Remove all candidates where the query's start does not match the start of any word in the candidate
15458        if let Some(query_start) = last_word.chars().next() {
15459            matches.retain(|string_match| {
15460                split_words(&string_match.string).any(|word| {
15461                    // Check that the first codepoint of the word as lowercase matches the first
15462                    // codepoint of the query as lowercase
15463                    word.chars()
15464                        .flat_map(|codepoint| codepoint.to_lowercase())
15465                        .zip(query_start.to_lowercase())
15466                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15467                })
15468            });
15469        }
15470
15471        let matched_strings = matches
15472            .into_iter()
15473            .map(|m| m.string)
15474            .collect::<HashSet<_>>();
15475
15476        let result: Vec<Completion> = snippets
15477            .into_iter()
15478            .filter_map(|snippet| {
15479                let matching_prefix = snippet
15480                    .prefix
15481                    .iter()
15482                    .find(|prefix| matched_strings.contains(*prefix))?;
15483                let start = as_offset - last_word.len();
15484                let start = snapshot.anchor_before(start);
15485                let range = start..buffer_position;
15486                let lsp_start = to_lsp(&start);
15487                let lsp_range = lsp::Range {
15488                    start: lsp_start,
15489                    end: lsp_end,
15490                };
15491                Some(Completion {
15492                    old_range: range,
15493                    new_text: snippet.body.clone(),
15494                    resolved: false,
15495                    label: CodeLabel {
15496                        text: matching_prefix.clone(),
15497                        runs: vec![],
15498                        filter_range: 0..matching_prefix.len(),
15499                    },
15500                    server_id: LanguageServerId(usize::MAX),
15501                    documentation: snippet
15502                        .description
15503                        .clone()
15504                        .map(CompletionDocumentation::SingleLine),
15505                    lsp_completion: lsp::CompletionItem {
15506                        label: snippet.prefix.first().unwrap().clone(),
15507                        kind: Some(CompletionItemKind::SNIPPET),
15508                        label_details: snippet.description.as_ref().map(|description| {
15509                            lsp::CompletionItemLabelDetails {
15510                                detail: Some(description.clone()),
15511                                description: None,
15512                            }
15513                        }),
15514                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15515                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15516                            lsp::InsertReplaceEdit {
15517                                new_text: snippet.body.clone(),
15518                                insert: lsp_range,
15519                                replace: lsp_range,
15520                            },
15521                        )),
15522                        filter_text: Some(snippet.body.clone()),
15523                        sort_text: Some(char::MAX.to_string()),
15524                        ..Default::default()
15525                    },
15526                    confirm: None,
15527                })
15528            })
15529            .collect();
15530
15531        Ok(result)
15532    })
15533}
15534
15535impl CompletionProvider for Entity<Project> {
15536    fn completions(
15537        &self,
15538        buffer: &Entity<Buffer>,
15539        buffer_position: text::Anchor,
15540        options: CompletionContext,
15541        _window: &mut Window,
15542        cx: &mut Context<Editor>,
15543    ) -> Task<Result<Vec<Completion>>> {
15544        self.update(cx, |project, cx| {
15545            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15546            let project_completions = project.completions(buffer, buffer_position, options, cx);
15547            cx.background_executor().spawn(async move {
15548                let mut completions = project_completions.await?;
15549                let snippets_completions = snippets.await?;
15550                completions.extend(snippets_completions);
15551                Ok(completions)
15552            })
15553        })
15554    }
15555
15556    fn resolve_completions(
15557        &self,
15558        buffer: Entity<Buffer>,
15559        completion_indices: Vec<usize>,
15560        completions: Rc<RefCell<Box<[Completion]>>>,
15561        cx: &mut Context<Editor>,
15562    ) -> Task<Result<bool>> {
15563        self.update(cx, |project, cx| {
15564            project.lsp_store().update(cx, |lsp_store, cx| {
15565                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15566            })
15567        })
15568    }
15569
15570    fn apply_additional_edits_for_completion(
15571        &self,
15572        buffer: Entity<Buffer>,
15573        completions: Rc<RefCell<Box<[Completion]>>>,
15574        completion_index: usize,
15575        push_to_history: bool,
15576        cx: &mut Context<Editor>,
15577    ) -> Task<Result<Option<language::Transaction>>> {
15578        self.update(cx, |project, cx| {
15579            project.lsp_store().update(cx, |lsp_store, cx| {
15580                lsp_store.apply_additional_edits_for_completion(
15581                    buffer,
15582                    completions,
15583                    completion_index,
15584                    push_to_history,
15585                    cx,
15586                )
15587            })
15588        })
15589    }
15590
15591    fn is_completion_trigger(
15592        &self,
15593        buffer: &Entity<Buffer>,
15594        position: language::Anchor,
15595        text: &str,
15596        trigger_in_words: bool,
15597        cx: &mut Context<Editor>,
15598    ) -> bool {
15599        let mut chars = text.chars();
15600        let char = if let Some(char) = chars.next() {
15601            char
15602        } else {
15603            return false;
15604        };
15605        if chars.next().is_some() {
15606            return false;
15607        }
15608
15609        let buffer = buffer.read(cx);
15610        let snapshot = buffer.snapshot();
15611        if !snapshot.settings_at(position, cx).show_completions_on_input {
15612            return false;
15613        }
15614        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15615        if trigger_in_words && classifier.is_word(char) {
15616            return true;
15617        }
15618
15619        buffer.completion_triggers().contains(text)
15620    }
15621}
15622
15623impl SemanticsProvider for Entity<Project> {
15624    fn hover(
15625        &self,
15626        buffer: &Entity<Buffer>,
15627        position: text::Anchor,
15628        cx: &mut App,
15629    ) -> Option<Task<Vec<project::Hover>>> {
15630        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15631    }
15632
15633    fn document_highlights(
15634        &self,
15635        buffer: &Entity<Buffer>,
15636        position: text::Anchor,
15637        cx: &mut App,
15638    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15639        Some(self.update(cx, |project, cx| {
15640            project.document_highlights(buffer, position, cx)
15641        }))
15642    }
15643
15644    fn definitions(
15645        &self,
15646        buffer: &Entity<Buffer>,
15647        position: text::Anchor,
15648        kind: GotoDefinitionKind,
15649        cx: &mut App,
15650    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15651        Some(self.update(cx, |project, cx| match kind {
15652            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15653            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15654            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15655            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15656        }))
15657    }
15658
15659    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15660        // TODO: make this work for remote projects
15661        self.read(cx)
15662            .language_servers_for_local_buffer(buffer.read(cx), cx)
15663            .any(
15664                |(_, server)| match server.capabilities().inlay_hint_provider {
15665                    Some(lsp::OneOf::Left(enabled)) => enabled,
15666                    Some(lsp::OneOf::Right(_)) => true,
15667                    None => false,
15668                },
15669            )
15670    }
15671
15672    fn inlay_hints(
15673        &self,
15674        buffer_handle: Entity<Buffer>,
15675        range: Range<text::Anchor>,
15676        cx: &mut App,
15677    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15678        Some(self.update(cx, |project, cx| {
15679            project.inlay_hints(buffer_handle, range, cx)
15680        }))
15681    }
15682
15683    fn resolve_inlay_hint(
15684        &self,
15685        hint: InlayHint,
15686        buffer_handle: Entity<Buffer>,
15687        server_id: LanguageServerId,
15688        cx: &mut App,
15689    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15690        Some(self.update(cx, |project, cx| {
15691            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15692        }))
15693    }
15694
15695    fn range_for_rename(
15696        &self,
15697        buffer: &Entity<Buffer>,
15698        position: text::Anchor,
15699        cx: &mut App,
15700    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15701        Some(self.update(cx, |project, cx| {
15702            let buffer = buffer.clone();
15703            let task = project.prepare_rename(buffer.clone(), position, cx);
15704            cx.spawn(|_, mut cx| async move {
15705                Ok(match task.await? {
15706                    PrepareRenameResponse::Success(range) => Some(range),
15707                    PrepareRenameResponse::InvalidPosition => None,
15708                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15709                        // Fallback on using TreeSitter info to determine identifier range
15710                        buffer.update(&mut cx, |buffer, _| {
15711                            let snapshot = buffer.snapshot();
15712                            let (range, kind) = snapshot.surrounding_word(position);
15713                            if kind != Some(CharKind::Word) {
15714                                return None;
15715                            }
15716                            Some(
15717                                snapshot.anchor_before(range.start)
15718                                    ..snapshot.anchor_after(range.end),
15719                            )
15720                        })?
15721                    }
15722                })
15723            })
15724        }))
15725    }
15726
15727    fn perform_rename(
15728        &self,
15729        buffer: &Entity<Buffer>,
15730        position: text::Anchor,
15731        new_name: String,
15732        cx: &mut App,
15733    ) -> Option<Task<Result<ProjectTransaction>>> {
15734        Some(self.update(cx, |project, cx| {
15735            project.perform_rename(buffer.clone(), position, new_name, cx)
15736        }))
15737    }
15738}
15739
15740fn inlay_hint_settings(
15741    location: Anchor,
15742    snapshot: &MultiBufferSnapshot,
15743    cx: &mut Context<Editor>,
15744) -> InlayHintSettings {
15745    let file = snapshot.file_at(location);
15746    let language = snapshot.language_at(location).map(|l| l.name());
15747    language_settings(language, file, cx).inlay_hints
15748}
15749
15750fn consume_contiguous_rows(
15751    contiguous_row_selections: &mut Vec<Selection<Point>>,
15752    selection: &Selection<Point>,
15753    display_map: &DisplaySnapshot,
15754    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15755) -> (MultiBufferRow, MultiBufferRow) {
15756    contiguous_row_selections.push(selection.clone());
15757    let start_row = MultiBufferRow(selection.start.row);
15758    let mut end_row = ending_row(selection, display_map);
15759
15760    while let Some(next_selection) = selections.peek() {
15761        if next_selection.start.row <= end_row.0 {
15762            end_row = ending_row(next_selection, display_map);
15763            contiguous_row_selections.push(selections.next().unwrap().clone());
15764        } else {
15765            break;
15766        }
15767    }
15768    (start_row, end_row)
15769}
15770
15771fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15772    if next_selection.end.column > 0 || next_selection.is_empty() {
15773        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15774    } else {
15775        MultiBufferRow(next_selection.end.row)
15776    }
15777}
15778
15779impl EditorSnapshot {
15780    pub fn remote_selections_in_range<'a>(
15781        &'a self,
15782        range: &'a Range<Anchor>,
15783        collaboration_hub: &dyn CollaborationHub,
15784        cx: &'a App,
15785    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15786        let participant_names = collaboration_hub.user_names(cx);
15787        let participant_indices = collaboration_hub.user_participant_indices(cx);
15788        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15789        let collaborators_by_replica_id = collaborators_by_peer_id
15790            .iter()
15791            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15792            .collect::<HashMap<_, _>>();
15793        self.buffer_snapshot
15794            .selections_in_range(range, false)
15795            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15796                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15797                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15798                let user_name = participant_names.get(&collaborator.user_id).cloned();
15799                Some(RemoteSelection {
15800                    replica_id,
15801                    selection,
15802                    cursor_shape,
15803                    line_mode,
15804                    participant_index,
15805                    peer_id: collaborator.peer_id,
15806                    user_name,
15807                })
15808            })
15809    }
15810
15811    pub fn hunks_for_ranges(
15812        &self,
15813        ranges: impl Iterator<Item = Range<Point>>,
15814    ) -> Vec<MultiBufferDiffHunk> {
15815        let mut hunks = Vec::new();
15816        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15817            HashMap::default();
15818        for query_range in ranges {
15819            let query_rows =
15820                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15821            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15822                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15823            ) {
15824                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15825                // when the caret is just above or just below the deleted hunk.
15826                let allow_adjacent = hunk.status().is_removed();
15827                let related_to_selection = if allow_adjacent {
15828                    hunk.row_range.overlaps(&query_rows)
15829                        || hunk.row_range.start == query_rows.end
15830                        || hunk.row_range.end == query_rows.start
15831                } else {
15832                    hunk.row_range.overlaps(&query_rows)
15833                };
15834                if related_to_selection {
15835                    if !processed_buffer_rows
15836                        .entry(hunk.buffer_id)
15837                        .or_default()
15838                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15839                    {
15840                        continue;
15841                    }
15842                    hunks.push(hunk);
15843                }
15844            }
15845        }
15846
15847        hunks
15848    }
15849
15850    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15851        self.display_snapshot.buffer_snapshot.language_at(position)
15852    }
15853
15854    pub fn is_focused(&self) -> bool {
15855        self.is_focused
15856    }
15857
15858    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15859        self.placeholder_text.as_ref()
15860    }
15861
15862    pub fn scroll_position(&self) -> gpui::Point<f32> {
15863        self.scroll_anchor.scroll_position(&self.display_snapshot)
15864    }
15865
15866    fn gutter_dimensions(
15867        &self,
15868        font_id: FontId,
15869        font_size: Pixels,
15870        max_line_number_width: Pixels,
15871        cx: &App,
15872    ) -> Option<GutterDimensions> {
15873        if !self.show_gutter {
15874            return None;
15875        }
15876
15877        let descent = cx.text_system().descent(font_id, font_size);
15878        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15879        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15880
15881        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15882            matches!(
15883                ProjectSettings::get_global(cx).git.git_gutter,
15884                Some(GitGutterSetting::TrackedFiles)
15885            )
15886        });
15887        let gutter_settings = EditorSettings::get_global(cx).gutter;
15888        let show_line_numbers = self
15889            .show_line_numbers
15890            .unwrap_or(gutter_settings.line_numbers);
15891        let line_gutter_width = if show_line_numbers {
15892            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15893            let min_width_for_number_on_gutter = em_advance * 4.0;
15894            max_line_number_width.max(min_width_for_number_on_gutter)
15895        } else {
15896            0.0.into()
15897        };
15898
15899        let show_code_actions = self
15900            .show_code_actions
15901            .unwrap_or(gutter_settings.code_actions);
15902
15903        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15904
15905        let git_blame_entries_width =
15906            self.git_blame_gutter_max_author_length
15907                .map(|max_author_length| {
15908                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15909
15910                    /// The number of characters to dedicate to gaps and margins.
15911                    const SPACING_WIDTH: usize = 4;
15912
15913                    let max_char_count = max_author_length
15914                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15915                        + ::git::SHORT_SHA_LENGTH
15916                        + MAX_RELATIVE_TIMESTAMP.len()
15917                        + SPACING_WIDTH;
15918
15919                    em_advance * max_char_count
15920                });
15921
15922        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15923        left_padding += if show_code_actions || show_runnables {
15924            em_width * 3.0
15925        } else if show_git_gutter && show_line_numbers {
15926            em_width * 2.0
15927        } else if show_git_gutter || show_line_numbers {
15928            em_width
15929        } else {
15930            px(0.)
15931        };
15932
15933        let right_padding = if gutter_settings.folds && show_line_numbers {
15934            em_width * 4.0
15935        } else if gutter_settings.folds {
15936            em_width * 3.0
15937        } else if show_line_numbers {
15938            em_width
15939        } else {
15940            px(0.)
15941        };
15942
15943        Some(GutterDimensions {
15944            left_padding,
15945            right_padding,
15946            width: line_gutter_width + left_padding + right_padding,
15947            margin: -descent,
15948            git_blame_entries_width,
15949        })
15950    }
15951
15952    pub fn render_crease_toggle(
15953        &self,
15954        buffer_row: MultiBufferRow,
15955        row_contains_cursor: bool,
15956        editor: Entity<Editor>,
15957        window: &mut Window,
15958        cx: &mut App,
15959    ) -> Option<AnyElement> {
15960        let folded = self.is_line_folded(buffer_row);
15961        let mut is_foldable = false;
15962
15963        if let Some(crease) = self
15964            .crease_snapshot
15965            .query_row(buffer_row, &self.buffer_snapshot)
15966        {
15967            is_foldable = true;
15968            match crease {
15969                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15970                    if let Some(render_toggle) = render_toggle {
15971                        let toggle_callback =
15972                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15973                                if folded {
15974                                    editor.update(cx, |editor, cx| {
15975                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15976                                    });
15977                                } else {
15978                                    editor.update(cx, |editor, cx| {
15979                                        editor.unfold_at(
15980                                            &crate::UnfoldAt { buffer_row },
15981                                            window,
15982                                            cx,
15983                                        )
15984                                    });
15985                                }
15986                            });
15987                        return Some((render_toggle)(
15988                            buffer_row,
15989                            folded,
15990                            toggle_callback,
15991                            window,
15992                            cx,
15993                        ));
15994                    }
15995                }
15996            }
15997        }
15998
15999        is_foldable |= self.starts_indent(buffer_row);
16000
16001        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16002            Some(
16003                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16004                    .toggle_state(folded)
16005                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16006                        if folded {
16007                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16008                        } else {
16009                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16010                        }
16011                    }))
16012                    .into_any_element(),
16013            )
16014        } else {
16015            None
16016        }
16017    }
16018
16019    pub fn render_crease_trailer(
16020        &self,
16021        buffer_row: MultiBufferRow,
16022        window: &mut Window,
16023        cx: &mut App,
16024    ) -> Option<AnyElement> {
16025        let folded = self.is_line_folded(buffer_row);
16026        if let Crease::Inline { render_trailer, .. } = self
16027            .crease_snapshot
16028            .query_row(buffer_row, &self.buffer_snapshot)?
16029        {
16030            let render_trailer = render_trailer.as_ref()?;
16031            Some(render_trailer(buffer_row, folded, window, cx))
16032        } else {
16033            None
16034        }
16035    }
16036}
16037
16038impl Deref for EditorSnapshot {
16039    type Target = DisplaySnapshot;
16040
16041    fn deref(&self) -> &Self::Target {
16042        &self.display_snapshot
16043    }
16044}
16045
16046#[derive(Clone, Debug, PartialEq, Eq)]
16047pub enum EditorEvent {
16048    InputIgnored {
16049        text: Arc<str>,
16050    },
16051    InputHandled {
16052        utf16_range_to_replace: Option<Range<isize>>,
16053        text: Arc<str>,
16054    },
16055    ExcerptsAdded {
16056        buffer: Entity<Buffer>,
16057        predecessor: ExcerptId,
16058        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16059    },
16060    ExcerptsRemoved {
16061        ids: Vec<ExcerptId>,
16062    },
16063    BufferFoldToggled {
16064        ids: Vec<ExcerptId>,
16065        folded: bool,
16066    },
16067    ExcerptsEdited {
16068        ids: Vec<ExcerptId>,
16069    },
16070    ExcerptsExpanded {
16071        ids: Vec<ExcerptId>,
16072    },
16073    BufferEdited,
16074    Edited {
16075        transaction_id: clock::Lamport,
16076    },
16077    Reparsed(BufferId),
16078    Focused,
16079    FocusedIn,
16080    Blurred,
16081    DirtyChanged,
16082    Saved,
16083    TitleChanged,
16084    DiffBaseChanged,
16085    SelectionsChanged {
16086        local: bool,
16087    },
16088    ScrollPositionChanged {
16089        local: bool,
16090        autoscroll: bool,
16091    },
16092    Closed,
16093    TransactionUndone {
16094        transaction_id: clock::Lamport,
16095    },
16096    TransactionBegun {
16097        transaction_id: clock::Lamport,
16098    },
16099    Reloaded,
16100    CursorShapeChanged,
16101}
16102
16103impl EventEmitter<EditorEvent> for Editor {}
16104
16105impl Focusable for Editor {
16106    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16107        self.focus_handle.clone()
16108    }
16109}
16110
16111impl Render for Editor {
16112    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16113        let settings = ThemeSettings::get_global(cx);
16114
16115        let mut text_style = match self.mode {
16116            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16117                color: cx.theme().colors().editor_foreground,
16118                font_family: settings.ui_font.family.clone(),
16119                font_features: settings.ui_font.features.clone(),
16120                font_fallbacks: settings.ui_font.fallbacks.clone(),
16121                font_size: rems(0.875).into(),
16122                font_weight: settings.ui_font.weight,
16123                line_height: relative(settings.buffer_line_height.value()),
16124                ..Default::default()
16125            },
16126            EditorMode::Full => TextStyle {
16127                color: cx.theme().colors().editor_foreground,
16128                font_family: settings.buffer_font.family.clone(),
16129                font_features: settings.buffer_font.features.clone(),
16130                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16131                font_size: settings.buffer_font_size().into(),
16132                font_weight: settings.buffer_font.weight,
16133                line_height: relative(settings.buffer_line_height.value()),
16134                ..Default::default()
16135            },
16136        };
16137        if let Some(text_style_refinement) = &self.text_style_refinement {
16138            text_style.refine(text_style_refinement)
16139        }
16140
16141        let background = match self.mode {
16142            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16143            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16144            EditorMode::Full => cx.theme().colors().editor_background,
16145        };
16146
16147        EditorElement::new(
16148            &cx.entity(),
16149            EditorStyle {
16150                background,
16151                local_player: cx.theme().players().local(),
16152                text: text_style,
16153                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16154                syntax: cx.theme().syntax().clone(),
16155                status: cx.theme().status().clone(),
16156                inlay_hints_style: make_inlay_hints_style(cx),
16157                inline_completion_styles: make_suggestion_styles(cx),
16158                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16159            },
16160        )
16161    }
16162}
16163
16164impl EntityInputHandler for Editor {
16165    fn text_for_range(
16166        &mut self,
16167        range_utf16: Range<usize>,
16168        adjusted_range: &mut Option<Range<usize>>,
16169        _: &mut Window,
16170        cx: &mut Context<Self>,
16171    ) -> Option<String> {
16172        let snapshot = self.buffer.read(cx).read(cx);
16173        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16174        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16175        if (start.0..end.0) != range_utf16 {
16176            adjusted_range.replace(start.0..end.0);
16177        }
16178        Some(snapshot.text_for_range(start..end).collect())
16179    }
16180
16181    fn selected_text_range(
16182        &mut self,
16183        ignore_disabled_input: bool,
16184        _: &mut Window,
16185        cx: &mut Context<Self>,
16186    ) -> Option<UTF16Selection> {
16187        // Prevent the IME menu from appearing when holding down an alphabetic key
16188        // while input is disabled.
16189        if !ignore_disabled_input && !self.input_enabled {
16190            return None;
16191        }
16192
16193        let selection = self.selections.newest::<OffsetUtf16>(cx);
16194        let range = selection.range();
16195
16196        Some(UTF16Selection {
16197            range: range.start.0..range.end.0,
16198            reversed: selection.reversed,
16199        })
16200    }
16201
16202    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16203        let snapshot = self.buffer.read(cx).read(cx);
16204        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16205        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16206    }
16207
16208    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16209        self.clear_highlights::<InputComposition>(cx);
16210        self.ime_transaction.take();
16211    }
16212
16213    fn replace_text_in_range(
16214        &mut self,
16215        range_utf16: Option<Range<usize>>,
16216        text: &str,
16217        window: &mut Window,
16218        cx: &mut Context<Self>,
16219    ) {
16220        if !self.input_enabled {
16221            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16222            return;
16223        }
16224
16225        self.transact(window, cx, |this, window, cx| {
16226            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16227                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16228                Some(this.selection_replacement_ranges(range_utf16, cx))
16229            } else {
16230                this.marked_text_ranges(cx)
16231            };
16232
16233            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16234                let newest_selection_id = this.selections.newest_anchor().id;
16235                this.selections
16236                    .all::<OffsetUtf16>(cx)
16237                    .iter()
16238                    .zip(ranges_to_replace.iter())
16239                    .find_map(|(selection, range)| {
16240                        if selection.id == newest_selection_id {
16241                            Some(
16242                                (range.start.0 as isize - selection.head().0 as isize)
16243                                    ..(range.end.0 as isize - selection.head().0 as isize),
16244                            )
16245                        } else {
16246                            None
16247                        }
16248                    })
16249            });
16250
16251            cx.emit(EditorEvent::InputHandled {
16252                utf16_range_to_replace: range_to_replace,
16253                text: text.into(),
16254            });
16255
16256            if let Some(new_selected_ranges) = new_selected_ranges {
16257                this.change_selections(None, window, cx, |selections| {
16258                    selections.select_ranges(new_selected_ranges)
16259                });
16260                this.backspace(&Default::default(), window, cx);
16261            }
16262
16263            this.handle_input(text, window, cx);
16264        });
16265
16266        if let Some(transaction) = self.ime_transaction {
16267            self.buffer.update(cx, |buffer, cx| {
16268                buffer.group_until_transaction(transaction, cx);
16269            });
16270        }
16271
16272        self.unmark_text(window, cx);
16273    }
16274
16275    fn replace_and_mark_text_in_range(
16276        &mut self,
16277        range_utf16: Option<Range<usize>>,
16278        text: &str,
16279        new_selected_range_utf16: Option<Range<usize>>,
16280        window: &mut Window,
16281        cx: &mut Context<Self>,
16282    ) {
16283        if !self.input_enabled {
16284            return;
16285        }
16286
16287        let transaction = self.transact(window, cx, |this, window, cx| {
16288            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16289                let snapshot = this.buffer.read(cx).read(cx);
16290                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16291                    for marked_range in &mut marked_ranges {
16292                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16293                        marked_range.start.0 += relative_range_utf16.start;
16294                        marked_range.start =
16295                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16296                        marked_range.end =
16297                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16298                    }
16299                }
16300                Some(marked_ranges)
16301            } else if let Some(range_utf16) = range_utf16 {
16302                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16303                Some(this.selection_replacement_ranges(range_utf16, cx))
16304            } else {
16305                None
16306            };
16307
16308            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16309                let newest_selection_id = this.selections.newest_anchor().id;
16310                this.selections
16311                    .all::<OffsetUtf16>(cx)
16312                    .iter()
16313                    .zip(ranges_to_replace.iter())
16314                    .find_map(|(selection, range)| {
16315                        if selection.id == newest_selection_id {
16316                            Some(
16317                                (range.start.0 as isize - selection.head().0 as isize)
16318                                    ..(range.end.0 as isize - selection.head().0 as isize),
16319                            )
16320                        } else {
16321                            None
16322                        }
16323                    })
16324            });
16325
16326            cx.emit(EditorEvent::InputHandled {
16327                utf16_range_to_replace: range_to_replace,
16328                text: text.into(),
16329            });
16330
16331            if let Some(ranges) = ranges_to_replace {
16332                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16333            }
16334
16335            let marked_ranges = {
16336                let snapshot = this.buffer.read(cx).read(cx);
16337                this.selections
16338                    .disjoint_anchors()
16339                    .iter()
16340                    .map(|selection| {
16341                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16342                    })
16343                    .collect::<Vec<_>>()
16344            };
16345
16346            if text.is_empty() {
16347                this.unmark_text(window, cx);
16348            } else {
16349                this.highlight_text::<InputComposition>(
16350                    marked_ranges.clone(),
16351                    HighlightStyle {
16352                        underline: Some(UnderlineStyle {
16353                            thickness: px(1.),
16354                            color: None,
16355                            wavy: false,
16356                        }),
16357                        ..Default::default()
16358                    },
16359                    cx,
16360                );
16361            }
16362
16363            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16364            let use_autoclose = this.use_autoclose;
16365            let use_auto_surround = this.use_auto_surround;
16366            this.set_use_autoclose(false);
16367            this.set_use_auto_surround(false);
16368            this.handle_input(text, window, cx);
16369            this.set_use_autoclose(use_autoclose);
16370            this.set_use_auto_surround(use_auto_surround);
16371
16372            if let Some(new_selected_range) = new_selected_range_utf16 {
16373                let snapshot = this.buffer.read(cx).read(cx);
16374                let new_selected_ranges = marked_ranges
16375                    .into_iter()
16376                    .map(|marked_range| {
16377                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16378                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16379                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16380                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16381                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16382                    })
16383                    .collect::<Vec<_>>();
16384
16385                drop(snapshot);
16386                this.change_selections(None, window, cx, |selections| {
16387                    selections.select_ranges(new_selected_ranges)
16388                });
16389            }
16390        });
16391
16392        self.ime_transaction = self.ime_transaction.or(transaction);
16393        if let Some(transaction) = self.ime_transaction {
16394            self.buffer.update(cx, |buffer, cx| {
16395                buffer.group_until_transaction(transaction, cx);
16396            });
16397        }
16398
16399        if self.text_highlights::<InputComposition>(cx).is_none() {
16400            self.ime_transaction.take();
16401        }
16402    }
16403
16404    fn bounds_for_range(
16405        &mut self,
16406        range_utf16: Range<usize>,
16407        element_bounds: gpui::Bounds<Pixels>,
16408        window: &mut Window,
16409        cx: &mut Context<Self>,
16410    ) -> Option<gpui::Bounds<Pixels>> {
16411        let text_layout_details = self.text_layout_details(window);
16412        let gpui::Size {
16413            width: em_width,
16414            height: line_height,
16415        } = self.character_size(window);
16416
16417        let snapshot = self.snapshot(window, cx);
16418        let scroll_position = snapshot.scroll_position();
16419        let scroll_left = scroll_position.x * em_width;
16420
16421        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16422        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16423            + self.gutter_dimensions.width
16424            + self.gutter_dimensions.margin;
16425        let y = line_height * (start.row().as_f32() - scroll_position.y);
16426
16427        Some(Bounds {
16428            origin: element_bounds.origin + point(x, y),
16429            size: size(em_width, line_height),
16430        })
16431    }
16432
16433    fn character_index_for_point(
16434        &mut self,
16435        point: gpui::Point<Pixels>,
16436        _window: &mut Window,
16437        _cx: &mut Context<Self>,
16438    ) -> Option<usize> {
16439        let position_map = self.last_position_map.as_ref()?;
16440        if !position_map.text_hitbox.contains(&point) {
16441            return None;
16442        }
16443        let display_point = position_map.point_for_position(point).previous_valid;
16444        let anchor = position_map
16445            .snapshot
16446            .display_point_to_anchor(display_point, Bias::Left);
16447        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16448        Some(utf16_offset.0)
16449    }
16450}
16451
16452trait SelectionExt {
16453    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16454    fn spanned_rows(
16455        &self,
16456        include_end_if_at_line_start: bool,
16457        map: &DisplaySnapshot,
16458    ) -> Range<MultiBufferRow>;
16459}
16460
16461impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16462    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16463        let start = self
16464            .start
16465            .to_point(&map.buffer_snapshot)
16466            .to_display_point(map);
16467        let end = self
16468            .end
16469            .to_point(&map.buffer_snapshot)
16470            .to_display_point(map);
16471        if self.reversed {
16472            end..start
16473        } else {
16474            start..end
16475        }
16476    }
16477
16478    fn spanned_rows(
16479        &self,
16480        include_end_if_at_line_start: bool,
16481        map: &DisplaySnapshot,
16482    ) -> Range<MultiBufferRow> {
16483        let start = self.start.to_point(&map.buffer_snapshot);
16484        let mut end = self.end.to_point(&map.buffer_snapshot);
16485        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16486            end.row -= 1;
16487        }
16488
16489        let buffer_start = map.prev_line_boundary(start).0;
16490        let buffer_end = map.next_line_boundary(end).0;
16491        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16492    }
16493}
16494
16495impl<T: InvalidationRegion> InvalidationStack<T> {
16496    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16497    where
16498        S: Clone + ToOffset,
16499    {
16500        while let Some(region) = self.last() {
16501            let all_selections_inside_invalidation_ranges =
16502                if selections.len() == region.ranges().len() {
16503                    selections
16504                        .iter()
16505                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16506                        .all(|(selection, invalidation_range)| {
16507                            let head = selection.head().to_offset(buffer);
16508                            invalidation_range.start <= head && invalidation_range.end >= head
16509                        })
16510                } else {
16511                    false
16512                };
16513
16514            if all_selections_inside_invalidation_ranges {
16515                break;
16516            } else {
16517                self.pop();
16518            }
16519        }
16520    }
16521}
16522
16523impl<T> Default for InvalidationStack<T> {
16524    fn default() -> Self {
16525        Self(Default::default())
16526    }
16527}
16528
16529impl<T> Deref for InvalidationStack<T> {
16530    type Target = Vec<T>;
16531
16532    fn deref(&self) -> &Self::Target {
16533        &self.0
16534    }
16535}
16536
16537impl<T> DerefMut for InvalidationStack<T> {
16538    fn deref_mut(&mut self) -> &mut Self::Target {
16539        &mut self.0
16540    }
16541}
16542
16543impl InvalidationRegion for SnippetState {
16544    fn ranges(&self) -> &[Range<Anchor>] {
16545        &self.ranges[self.active_index]
16546    }
16547}
16548
16549pub fn diagnostic_block_renderer(
16550    diagnostic: Diagnostic,
16551    max_message_rows: Option<u8>,
16552    allow_closing: bool,
16553    _is_valid: bool,
16554) -> RenderBlock {
16555    let (text_without_backticks, code_ranges) =
16556        highlight_diagnostic_message(&diagnostic, max_message_rows);
16557
16558    Arc::new(move |cx: &mut BlockContext| {
16559        let group_id: SharedString = cx.block_id.to_string().into();
16560
16561        let mut text_style = cx.window.text_style().clone();
16562        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16563        let theme_settings = ThemeSettings::get_global(cx);
16564        text_style.font_family = theme_settings.buffer_font.family.clone();
16565        text_style.font_style = theme_settings.buffer_font.style;
16566        text_style.font_features = theme_settings.buffer_font.features.clone();
16567        text_style.font_weight = theme_settings.buffer_font.weight;
16568
16569        let multi_line_diagnostic = diagnostic.message.contains('\n');
16570
16571        let buttons = |diagnostic: &Diagnostic| {
16572            if multi_line_diagnostic {
16573                v_flex()
16574            } else {
16575                h_flex()
16576            }
16577            .when(allow_closing, |div| {
16578                div.children(diagnostic.is_primary.then(|| {
16579                    IconButton::new("close-block", IconName::XCircle)
16580                        .icon_color(Color::Muted)
16581                        .size(ButtonSize::Compact)
16582                        .style(ButtonStyle::Transparent)
16583                        .visible_on_hover(group_id.clone())
16584                        .on_click(move |_click, window, cx| {
16585                            window.dispatch_action(Box::new(Cancel), cx)
16586                        })
16587                        .tooltip(|window, cx| {
16588                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16589                        })
16590                }))
16591            })
16592            .child(
16593                IconButton::new("copy-block", IconName::Copy)
16594                    .icon_color(Color::Muted)
16595                    .size(ButtonSize::Compact)
16596                    .style(ButtonStyle::Transparent)
16597                    .visible_on_hover(group_id.clone())
16598                    .on_click({
16599                        let message = diagnostic.message.clone();
16600                        move |_click, _, cx| {
16601                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16602                        }
16603                    })
16604                    .tooltip(Tooltip::text("Copy diagnostic message")),
16605            )
16606        };
16607
16608        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16609            AvailableSpace::min_size(),
16610            cx.window,
16611            cx.app,
16612        );
16613
16614        h_flex()
16615            .id(cx.block_id)
16616            .group(group_id.clone())
16617            .relative()
16618            .size_full()
16619            .block_mouse_down()
16620            .pl(cx.gutter_dimensions.width)
16621            .w(cx.max_width - cx.gutter_dimensions.full_width())
16622            .child(
16623                div()
16624                    .flex()
16625                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16626                    .flex_shrink(),
16627            )
16628            .child(buttons(&diagnostic))
16629            .child(div().flex().flex_shrink_0().child(
16630                StyledText::new(text_without_backticks.clone()).with_highlights(
16631                    &text_style,
16632                    code_ranges.iter().map(|range| {
16633                        (
16634                            range.clone(),
16635                            HighlightStyle {
16636                                font_weight: Some(FontWeight::BOLD),
16637                                ..Default::default()
16638                            },
16639                        )
16640                    }),
16641                ),
16642            ))
16643            .into_any_element()
16644    })
16645}
16646
16647fn inline_completion_edit_text(
16648    current_snapshot: &BufferSnapshot,
16649    edits: &[(Range<Anchor>, String)],
16650    edit_preview: &EditPreview,
16651    include_deletions: bool,
16652    cx: &App,
16653) -> HighlightedText {
16654    let edits = edits
16655        .iter()
16656        .map(|(anchor, text)| {
16657            (
16658                anchor.start.text_anchor..anchor.end.text_anchor,
16659                text.clone(),
16660            )
16661        })
16662        .collect::<Vec<_>>();
16663
16664    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16665}
16666
16667pub fn highlight_diagnostic_message(
16668    diagnostic: &Diagnostic,
16669    mut max_message_rows: Option<u8>,
16670) -> (SharedString, Vec<Range<usize>>) {
16671    let mut text_without_backticks = String::new();
16672    let mut code_ranges = Vec::new();
16673
16674    if let Some(source) = &diagnostic.source {
16675        text_without_backticks.push_str(source);
16676        code_ranges.push(0..source.len());
16677        text_without_backticks.push_str(": ");
16678    }
16679
16680    let mut prev_offset = 0;
16681    let mut in_code_block = false;
16682    let has_row_limit = max_message_rows.is_some();
16683    let mut newline_indices = diagnostic
16684        .message
16685        .match_indices('\n')
16686        .filter(|_| has_row_limit)
16687        .map(|(ix, _)| ix)
16688        .fuse()
16689        .peekable();
16690
16691    for (quote_ix, _) in diagnostic
16692        .message
16693        .match_indices('`')
16694        .chain([(diagnostic.message.len(), "")])
16695    {
16696        let mut first_newline_ix = None;
16697        let mut last_newline_ix = None;
16698        while let Some(newline_ix) = newline_indices.peek() {
16699            if *newline_ix < quote_ix {
16700                if first_newline_ix.is_none() {
16701                    first_newline_ix = Some(*newline_ix);
16702                }
16703                last_newline_ix = Some(*newline_ix);
16704
16705                if let Some(rows_left) = &mut max_message_rows {
16706                    if *rows_left == 0 {
16707                        break;
16708                    } else {
16709                        *rows_left -= 1;
16710                    }
16711                }
16712                let _ = newline_indices.next();
16713            } else {
16714                break;
16715            }
16716        }
16717        let prev_len = text_without_backticks.len();
16718        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16719        text_without_backticks.push_str(new_text);
16720        if in_code_block {
16721            code_ranges.push(prev_len..text_without_backticks.len());
16722        }
16723        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16724        in_code_block = !in_code_block;
16725        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16726            text_without_backticks.push_str("...");
16727            break;
16728        }
16729    }
16730
16731    (text_without_backticks.into(), code_ranges)
16732}
16733
16734fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16735    match severity {
16736        DiagnosticSeverity::ERROR => colors.error,
16737        DiagnosticSeverity::WARNING => colors.warning,
16738        DiagnosticSeverity::INFORMATION => colors.info,
16739        DiagnosticSeverity::HINT => colors.info,
16740        _ => colors.ignored,
16741    }
16742}
16743
16744pub fn styled_runs_for_code_label<'a>(
16745    label: &'a CodeLabel,
16746    syntax_theme: &'a theme::SyntaxTheme,
16747) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16748    let fade_out = HighlightStyle {
16749        fade_out: Some(0.35),
16750        ..Default::default()
16751    };
16752
16753    let mut prev_end = label.filter_range.end;
16754    label
16755        .runs
16756        .iter()
16757        .enumerate()
16758        .flat_map(move |(ix, (range, highlight_id))| {
16759            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16760                style
16761            } else {
16762                return Default::default();
16763            };
16764            let mut muted_style = style;
16765            muted_style.highlight(fade_out);
16766
16767            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16768            if range.start >= label.filter_range.end {
16769                if range.start > prev_end {
16770                    runs.push((prev_end..range.start, fade_out));
16771                }
16772                runs.push((range.clone(), muted_style));
16773            } else if range.end <= label.filter_range.end {
16774                runs.push((range.clone(), style));
16775            } else {
16776                runs.push((range.start..label.filter_range.end, style));
16777                runs.push((label.filter_range.end..range.end, muted_style));
16778            }
16779            prev_end = cmp::max(prev_end, range.end);
16780
16781            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16782                runs.push((prev_end..label.text.len(), fade_out));
16783            }
16784
16785            runs
16786        })
16787}
16788
16789pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16790    let mut prev_index = 0;
16791    let mut prev_codepoint: Option<char> = None;
16792    text.char_indices()
16793        .chain([(text.len(), '\0')])
16794        .filter_map(move |(index, codepoint)| {
16795            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16796            let is_boundary = index == text.len()
16797                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16798                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16799            if is_boundary {
16800                let chunk = &text[prev_index..index];
16801                prev_index = index;
16802                Some(chunk)
16803            } else {
16804                None
16805            }
16806        })
16807}
16808
16809pub trait RangeToAnchorExt: Sized {
16810    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16811
16812    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16813        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16814        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16815    }
16816}
16817
16818impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16819    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16820        let start_offset = self.start.to_offset(snapshot);
16821        let end_offset = self.end.to_offset(snapshot);
16822        if start_offset == end_offset {
16823            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16824        } else {
16825            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16826        }
16827    }
16828}
16829
16830pub trait RowExt {
16831    fn as_f32(&self) -> f32;
16832
16833    fn next_row(&self) -> Self;
16834
16835    fn previous_row(&self) -> Self;
16836
16837    fn minus(&self, other: Self) -> u32;
16838}
16839
16840impl RowExt for DisplayRow {
16841    fn as_f32(&self) -> f32 {
16842        self.0 as f32
16843    }
16844
16845    fn next_row(&self) -> Self {
16846        Self(self.0 + 1)
16847    }
16848
16849    fn previous_row(&self) -> Self {
16850        Self(self.0.saturating_sub(1))
16851    }
16852
16853    fn minus(&self, other: Self) -> u32 {
16854        self.0 - other.0
16855    }
16856}
16857
16858impl RowExt for MultiBufferRow {
16859    fn as_f32(&self) -> f32 {
16860        self.0 as f32
16861    }
16862
16863    fn next_row(&self) -> Self {
16864        Self(self.0 + 1)
16865    }
16866
16867    fn previous_row(&self) -> Self {
16868        Self(self.0.saturating_sub(1))
16869    }
16870
16871    fn minus(&self, other: Self) -> u32 {
16872        self.0 - other.0
16873    }
16874}
16875
16876trait RowRangeExt {
16877    type Row;
16878
16879    fn len(&self) -> usize;
16880
16881    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16882}
16883
16884impl RowRangeExt for Range<MultiBufferRow> {
16885    type Row = MultiBufferRow;
16886
16887    fn len(&self) -> usize {
16888        (self.end.0 - self.start.0) as usize
16889    }
16890
16891    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16892        (self.start.0..self.end.0).map(MultiBufferRow)
16893    }
16894}
16895
16896impl RowRangeExt for Range<DisplayRow> {
16897    type Row = DisplayRow;
16898
16899    fn len(&self) -> usize {
16900        (self.end.0 - self.start.0) as usize
16901    }
16902
16903    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16904        (self.start.0..self.end.0).map(DisplayRow)
16905    }
16906}
16907
16908/// If select range has more than one line, we
16909/// just point the cursor to range.start.
16910fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16911    if range.start.row == range.end.row {
16912        range
16913    } else {
16914        range.start..range.start
16915    }
16916}
16917pub struct KillRing(ClipboardItem);
16918impl Global for KillRing {}
16919
16920const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16921
16922fn all_edits_insertions_or_deletions(
16923    edits: &Vec<(Range<Anchor>, String)>,
16924    snapshot: &MultiBufferSnapshot,
16925) -> bool {
16926    let mut all_insertions = true;
16927    let mut all_deletions = true;
16928
16929    for (range, new_text) in edits.iter() {
16930        let range_is_empty = range.to_offset(&snapshot).is_empty();
16931        let text_is_empty = new_text.is_empty();
16932
16933        if range_is_empty != text_is_empty {
16934            if range_is_empty {
16935                all_deletions = false;
16936            } else {
16937                all_insertions = false;
16938            }
16939        } else {
16940            return false;
16941        }
16942
16943        if !all_insertions && !all_deletions {
16944            return false;
16945        }
16946    }
16947    all_insertions || all_deletions
16948}