editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50use ::git::diff::DiffHunkStatus;
   51pub(crate) use actions::*;
   52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   53use aho_corasick::AhoCorasick;
   54use anyhow::{anyhow, Context as _, Result};
   55use blink_manager::BlinkManager;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72
   73use code_context_menus::{
   74    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   75    CompletionsMenu, ContextMenuOrigin,
   76};
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
   80    px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
   81    AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
   82    Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
   84    MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
   85    StyledText, Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
  100    IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  101    TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  167use workspace::item::{ItemHandle, PreviewTabsSettings};
  168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  169use workspace::{
  170    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  171};
  172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  173
  174use crate::hover_links::{find_url, find_url_from_range};
  175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  176
  177pub const FILE_HEADER_HEIGHT: u32 = 2;
  178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  182const MAX_LINE_LEN: usize = 1024;
  183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  186#[doc(hidden)]
  187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  188
  189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  191
  192pub fn render_parsed_markdown(
  193    element_id: impl Into<ElementId>,
  194    parsed: &language::ParsedMarkdown,
  195    editor_style: &EditorStyle,
  196    workspace: Option<WeakEntity<Workspace>>,
  197    cx: &mut App,
  198) -> InteractiveText {
  199    let code_span_background_color = cx
  200        .theme()
  201        .colors()
  202        .editor_document_highlight_read_background;
  203
  204    let highlights = gpui::combine_highlights(
  205        parsed.highlights.iter().filter_map(|(range, highlight)| {
  206            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  207            Some((range.clone(), highlight))
  208        }),
  209        parsed
  210            .regions
  211            .iter()
  212            .zip(&parsed.region_ranges)
  213            .filter_map(|(region, range)| {
  214                if region.code {
  215                    Some((
  216                        range.clone(),
  217                        HighlightStyle {
  218                            background_color: Some(code_span_background_color),
  219                            ..Default::default()
  220                        },
  221                    ))
  222                } else {
  223                    None
  224                }
  225            }),
  226    );
  227
  228    let mut links = Vec::new();
  229    let mut link_ranges = Vec::new();
  230    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  231        if let Some(link) = region.link.clone() {
  232            links.push(link);
  233            link_ranges.push(range.clone());
  234        }
  235    }
  236
  237    InteractiveText::new(
  238        element_id,
  239        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  240    )
  241    .on_click(
  242        link_ranges,
  243        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  244            markdown::Link::Web { url } => cx.open_url(url),
  245            markdown::Link::Path { path } => {
  246                if let Some(workspace) = &workspace {
  247                    _ = workspace.update(cx, |workspace, cx| {
  248                        workspace
  249                            .open_abs_path(path.clone(), false, window, cx)
  250                            .detach();
  251                    });
  252                }
  253            }
  254        },
  255    )
  256}
  257
  258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  259pub enum InlayId {
  260    InlineCompletion(usize),
  261    Hint(usize),
  262}
  263
  264impl InlayId {
  265    fn id(&self) -> usize {
  266        match self {
  267            Self::InlineCompletion(id) => *id,
  268            Self::Hint(id) => *id,
  269        }
  270    }
  271}
  272
  273enum DocumentHighlightRead {}
  274enum DocumentHighlightWrite {}
  275enum InputComposition {}
  276
  277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  278pub enum Navigated {
  279    Yes,
  280    No,
  281}
  282
  283impl Navigated {
  284    pub fn from_bool(yes: bool) -> Navigated {
  285        if yes {
  286            Navigated::Yes
  287        } else {
  288            Navigated::No
  289        }
  290    }
  291}
  292
  293pub fn init_settings(cx: &mut App) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut App) {
  298    init_settings(cx);
  299
  300    workspace::register_project_item::<Editor>(cx);
  301    workspace::FollowableViewRegistry::register::<Editor>(cx);
  302    workspace::register_serializable_item::<Editor>(cx);
  303
  304    cx.observe_new(
  305        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  306            workspace.register_action(Editor::new_file);
  307            workspace.register_action(Editor::new_file_vertical);
  308            workspace.register_action(Editor::new_file_horizontal);
  309        },
  310    )
  311    .detach();
  312
  313    cx.on_action(move |_: &workspace::NewFile, cx| {
  314        let app_state = workspace::AppState::global(cx);
  315        if let Some(app_state) = app_state.upgrade() {
  316            workspace::open_new(
  317                Default::default(),
  318                app_state,
  319                cx,
  320                |workspace, window, cx| {
  321                    Editor::new_file(workspace, &Default::default(), window, cx)
  322                },
  323            )
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(
  331                Default::default(),
  332                app_state,
  333                cx,
  334                |workspace, window, cx| {
  335                    cx.activate(true);
  336                    Editor::new_file(workspace, &Default::default(), window, cx)
  337                },
  338            )
  339            .detach();
  340        }
  341    });
  342}
  343
  344pub struct SearchWithinRange;
  345
  346trait InvalidationRegion {
  347    fn ranges(&self) -> &[Range<Anchor>];
  348}
  349
  350#[derive(Clone, Debug, PartialEq)]
  351pub enum SelectPhase {
  352    Begin {
  353        position: DisplayPoint,
  354        add: bool,
  355        click_count: usize,
  356    },
  357    BeginColumnar {
  358        position: DisplayPoint,
  359        reset: bool,
  360        goal_column: u32,
  361    },
  362    Extend {
  363        position: DisplayPoint,
  364        click_count: usize,
  365    },
  366    Update {
  367        position: DisplayPoint,
  368        goal_column: u32,
  369        scroll_delta: gpui::Point<f32>,
  370    },
  371    End,
  372}
  373
  374#[derive(Clone, Debug)]
  375pub enum SelectMode {
  376    Character,
  377    Word(Range<Anchor>),
  378    Line(Range<Anchor>),
  379    All,
  380}
  381
  382#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  383pub enum EditorMode {
  384    SingleLine { auto_width: bool },
  385    AutoHeight { max_lines: usize },
  386    Full,
  387}
  388
  389#[derive(Copy, Clone, Debug)]
  390pub enum SoftWrap {
  391    /// Prefer not to wrap at all.
  392    ///
  393    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  394    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  395    GitDiff,
  396    /// Prefer a single line generally, unless an overly long line is encountered.
  397    None,
  398    /// Soft wrap lines that exceed the editor width.
  399    EditorWidth,
  400    /// Soft wrap lines at the preferred line length.
  401    Column(u32),
  402    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  403    Bounded(u32),
  404}
  405
  406#[derive(Clone)]
  407pub struct EditorStyle {
  408    pub background: Hsla,
  409    pub local_player: PlayerColor,
  410    pub text: TextStyle,
  411    pub scrollbar_width: Pixels,
  412    pub syntax: Arc<SyntaxTheme>,
  413    pub status: StatusColors,
  414    pub inlay_hints_style: HighlightStyle,
  415    pub inline_completion_styles: InlineCompletionStyles,
  416    pub unnecessary_code_fade: f32,
  417}
  418
  419impl Default for EditorStyle {
  420    fn default() -> Self {
  421        Self {
  422            background: Hsla::default(),
  423            local_player: PlayerColor::default(),
  424            text: TextStyle::default(),
  425            scrollbar_width: Pixels::default(),
  426            syntax: Default::default(),
  427            // HACK: Status colors don't have a real default.
  428            // We should look into removing the status colors from the editor
  429            // style and retrieve them directly from the theme.
  430            status: StatusColors::dark(),
  431            inlay_hints_style: HighlightStyle::default(),
  432            inline_completion_styles: InlineCompletionStyles {
  433                insertion: HighlightStyle::default(),
  434                whitespace: HighlightStyle::default(),
  435            },
  436            unnecessary_code_fade: Default::default(),
  437        }
  438    }
  439}
  440
  441pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  442    let show_background = language_settings::language_settings(None, None, cx)
  443        .inlay_hints
  444        .show_background;
  445
  446    HighlightStyle {
  447        color: Some(cx.theme().status().hint),
  448        background_color: show_background.then(|| cx.theme().status().hint_background),
  449        ..HighlightStyle::default()
  450    }
  451}
  452
  453pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  454    InlineCompletionStyles {
  455        insertion: HighlightStyle {
  456            color: Some(cx.theme().status().predictive),
  457            ..HighlightStyle::default()
  458        },
  459        whitespace: HighlightStyle {
  460            background_color: Some(cx.theme().status().created_background),
  461            ..HighlightStyle::default()
  462        },
  463    }
  464}
  465
  466type CompletionId = usize;
  467
  468pub(crate) enum EditDisplayMode {
  469    TabAccept(bool),
  470    DiffPopover,
  471    Inline,
  472}
  473
  474enum InlineCompletion {
  475    Edit {
  476        edits: Vec<(Range<Anchor>, String)>,
  477        edit_preview: Option<EditPreview>,
  478        display_mode: EditDisplayMode,
  479        snapshot: BufferSnapshot,
  480    },
  481    Move {
  482        target: Anchor,
  483        range_around_target: Range<text::Anchor>,
  484        snapshot: BufferSnapshot,
  485    },
  486}
  487
  488struct InlineCompletionState {
  489    inlay_ids: Vec<InlayId>,
  490    completion: InlineCompletion,
  491    invalidation_range: Range<Anchor>,
  492}
  493
  494impl InlineCompletionState {
  495    pub fn is_move(&self) -> bool {
  496        match &self.completion {
  497            InlineCompletion::Move { .. } => true,
  498            _ => false,
  499        }
  500    }
  501}
  502
  503enum InlineCompletionHighlight {}
  504
  505pub enum MenuInlineCompletionsPolicy {
  506    Never,
  507    ByProvider,
  508}
  509
  510#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  511struct EditorActionId(usize);
  512
  513impl EditorActionId {
  514    pub fn post_inc(&mut self) -> Self {
  515        let answer = self.0;
  516
  517        *self = Self(answer + 1);
  518
  519        Self(answer)
  520    }
  521}
  522
  523// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  524// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  525
  526type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  527type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  528
  529#[derive(Default)]
  530struct ScrollbarMarkerState {
  531    scrollbar_size: Size<Pixels>,
  532    dirty: bool,
  533    markers: Arc<[PaintQuad]>,
  534    pending_refresh: Option<Task<Result<()>>>,
  535}
  536
  537impl ScrollbarMarkerState {
  538    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  539        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  540    }
  541}
  542
  543#[derive(Clone, Debug)]
  544struct RunnableTasks {
  545    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  546    offset: MultiBufferOffset,
  547    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  548    column: u32,
  549    // Values of all named captures, including those starting with '_'
  550    extra_variables: HashMap<String, String>,
  551    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  552    context_range: Range<BufferOffset>,
  553}
  554
  555impl RunnableTasks {
  556    fn resolve<'a>(
  557        &'a self,
  558        cx: &'a task::TaskContext,
  559    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  560        self.templates.iter().filter_map(|(kind, template)| {
  561            template
  562                .resolve_task(&kind.to_id_base(), cx)
  563                .map(|task| (kind.clone(), task))
  564        })
  565    }
  566}
  567
  568#[derive(Clone)]
  569struct ResolvedTasks {
  570    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  571    position: Anchor,
  572}
  573#[derive(Copy, Clone, Debug)]
  574struct MultiBufferOffset(usize);
  575#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  576struct BufferOffset(usize);
  577
  578// Addons allow storing per-editor state in other crates (e.g. Vim)
  579pub trait Addon: 'static {
  580    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  581
  582    fn to_any(&self) -> &dyn std::any::Any;
  583}
  584
  585#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  586pub enum IsVimMode {
  587    Yes,
  588    No,
  589}
  590
  591/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  592///
  593/// See the [module level documentation](self) for more information.
  594pub struct Editor {
  595    focus_handle: FocusHandle,
  596    last_focused_descendant: Option<WeakFocusHandle>,
  597    /// The text buffer being edited
  598    buffer: Entity<MultiBuffer>,
  599    /// Map of how text in the buffer should be displayed.
  600    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  601    pub display_map: Entity<DisplayMap>,
  602    pub selections: SelectionsCollection,
  603    pub scroll_manager: ScrollManager,
  604    /// When inline assist editors are linked, they all render cursors because
  605    /// typing enters text into each of them, even the ones that aren't focused.
  606    pub(crate) show_cursor_when_unfocused: bool,
  607    columnar_selection_tail: Option<Anchor>,
  608    add_selections_state: Option<AddSelectionsState>,
  609    select_next_state: Option<SelectNextState>,
  610    select_prev_state: Option<SelectNextState>,
  611    selection_history: SelectionHistory,
  612    autoclose_regions: Vec<AutocloseRegion>,
  613    snippet_stack: InvalidationStack<SnippetState>,
  614    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  615    ime_transaction: Option<TransactionId>,
  616    active_diagnostics: Option<ActiveDiagnosticGroup>,
  617    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  618
  619    // TODO: make this a access method
  620    pub project: Option<Entity<Project>>,
  621    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  622    completion_provider: Option<Box<dyn CompletionProvider>>,
  623    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  624    blink_manager: Entity<BlinkManager>,
  625    show_cursor_names: bool,
  626    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  627    pub show_local_selections: bool,
  628    mode: EditorMode,
  629    show_breadcrumbs: bool,
  630    show_gutter: bool,
  631    show_scrollbars: bool,
  632    show_line_numbers: Option<bool>,
  633    use_relative_line_numbers: Option<bool>,
  634    show_git_diff_gutter: Option<bool>,
  635    show_code_actions: Option<bool>,
  636    show_runnables: Option<bool>,
  637    show_wrap_guides: Option<bool>,
  638    show_indent_guides: Option<bool>,
  639    placeholder_text: Option<Arc<str>>,
  640    highlight_order: usize,
  641    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  642    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  643    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  644    scrollbar_marker_state: ScrollbarMarkerState,
  645    active_indent_guides_state: ActiveIndentGuidesState,
  646    nav_history: Option<ItemNavHistory>,
  647    context_menu: RefCell<Option<CodeContextMenu>>,
  648    mouse_context_menu: Option<MouseContextMenu>,
  649    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  650    signature_help_state: SignatureHelpState,
  651    auto_signature_help: Option<bool>,
  652    find_all_references_task_sources: Vec<Anchor>,
  653    next_completion_id: CompletionId,
  654    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  655    code_actions_task: Option<Task<Result<()>>>,
  656    document_highlights_task: Option<Task<()>>,
  657    linked_editing_range_task: Option<Task<Option<()>>>,
  658    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  659    pending_rename: Option<RenameState>,
  660    searchable: bool,
  661    cursor_shape: CursorShape,
  662    current_line_highlight: Option<CurrentLineHighlight>,
  663    collapse_matches: bool,
  664    autoindent_mode: Option<AutoindentMode>,
  665    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  666    input_enabled: bool,
  667    use_modal_editing: bool,
  668    read_only: bool,
  669    leader_peer_id: Option<PeerId>,
  670    remote_id: Option<ViewId>,
  671    hover_state: HoverState,
  672    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  673    gutter_hovered: bool,
  674    hovered_link_state: Option<HoveredLinkState>,
  675    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  676    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  677    active_inline_completion: Option<InlineCompletionState>,
  678    /// Used to prevent flickering as the user types while the menu is open
  679    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  680    // enable_inline_completions is a switch that Vim can use to disable
  681    // inline completions based on its mode.
  682    enable_inline_completions: bool,
  683    show_inline_completions_override: Option<bool>,
  684    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  685    inlay_hint_cache: InlayHintCache,
  686    next_inlay_id: usize,
  687    _subscriptions: Vec<Subscription>,
  688    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  689    gutter_dimensions: GutterDimensions,
  690    style: Option<EditorStyle>,
  691    text_style_refinement: Option<TextStyleRefinement>,
  692    next_editor_action_id: EditorActionId,
  693    editor_actions:
  694        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  695    use_autoclose: bool,
  696    use_auto_surround: bool,
  697    auto_replace_emoji_shortcode: bool,
  698    show_git_blame_gutter: bool,
  699    show_git_blame_inline: bool,
  700    show_git_blame_inline_delay_task: Option<Task<()>>,
  701    git_blame_inline_enabled: bool,
  702    serialize_dirty_buffers: bool,
  703    show_selection_menu: Option<bool>,
  704    blame: Option<Entity<GitBlame>>,
  705    blame_subscription: Option<Subscription>,
  706    custom_context_menu: Option<
  707        Box<
  708            dyn 'static
  709                + Fn(
  710                    &mut Self,
  711                    DisplayPoint,
  712                    &mut Window,
  713                    &mut Context<Self>,
  714                ) -> Option<Entity<ui::ContextMenu>>,
  715        >,
  716    >,
  717    last_bounds: Option<Bounds<Pixels>>,
  718    expect_bounds_change: Option<Bounds<Pixels>>,
  719    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  720    tasks_update_task: Option<Task<()>>,
  721    in_project_search: bool,
  722    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  723    breadcrumb_header: Option<String>,
  724    focused_block: Option<FocusedBlock>,
  725    next_scroll_position: NextScrollCursorCenterTopBottom,
  726    addons: HashMap<TypeId, Box<dyn Addon>>,
  727    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  728    selection_mark_mode: bool,
  729    toggle_fold_multiple_buffers: Task<()>,
  730    _scroll_cursor_center_top_bottom_task: Task<()>,
  731}
  732
  733#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  734enum NextScrollCursorCenterTopBottom {
  735    #[default]
  736    Center,
  737    Top,
  738    Bottom,
  739}
  740
  741impl NextScrollCursorCenterTopBottom {
  742    fn next(&self) -> Self {
  743        match self {
  744            Self::Center => Self::Top,
  745            Self::Top => Self::Bottom,
  746            Self::Bottom => Self::Center,
  747        }
  748    }
  749}
  750
  751#[derive(Clone)]
  752pub struct EditorSnapshot {
  753    pub mode: EditorMode,
  754    show_gutter: bool,
  755    show_line_numbers: Option<bool>,
  756    show_git_diff_gutter: Option<bool>,
  757    show_code_actions: Option<bool>,
  758    show_runnables: Option<bool>,
  759    git_blame_gutter_max_author_length: Option<usize>,
  760    pub display_snapshot: DisplaySnapshot,
  761    pub placeholder_text: Option<Arc<str>>,
  762    is_focused: bool,
  763    scroll_anchor: ScrollAnchor,
  764    ongoing_scroll: OngoingScroll,
  765    current_line_highlight: CurrentLineHighlight,
  766    gutter_hovered: bool,
  767}
  768
  769const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  770
  771#[derive(Default, Debug, Clone, Copy)]
  772pub struct GutterDimensions {
  773    pub left_padding: Pixels,
  774    pub right_padding: Pixels,
  775    pub width: Pixels,
  776    pub margin: Pixels,
  777    pub git_blame_entries_width: Option<Pixels>,
  778}
  779
  780impl GutterDimensions {
  781    /// The full width of the space taken up by the gutter.
  782    pub fn full_width(&self) -> Pixels {
  783        self.margin + self.width
  784    }
  785
  786    /// The width of the space reserved for the fold indicators,
  787    /// use alongside 'justify_end' and `gutter_width` to
  788    /// right align content with the line numbers
  789    pub fn fold_area_width(&self) -> Pixels {
  790        self.margin + self.right_padding
  791    }
  792}
  793
  794#[derive(Debug)]
  795pub struct RemoteSelection {
  796    pub replica_id: ReplicaId,
  797    pub selection: Selection<Anchor>,
  798    pub cursor_shape: CursorShape,
  799    pub peer_id: PeerId,
  800    pub line_mode: bool,
  801    pub participant_index: Option<ParticipantIndex>,
  802    pub user_name: Option<SharedString>,
  803}
  804
  805#[derive(Clone, Debug)]
  806struct SelectionHistoryEntry {
  807    selections: Arc<[Selection<Anchor>]>,
  808    select_next_state: Option<SelectNextState>,
  809    select_prev_state: Option<SelectNextState>,
  810    add_selections_state: Option<AddSelectionsState>,
  811}
  812
  813enum SelectionHistoryMode {
  814    Normal,
  815    Undoing,
  816    Redoing,
  817}
  818
  819#[derive(Clone, PartialEq, Eq, Hash)]
  820struct HoveredCursor {
  821    replica_id: u16,
  822    selection_id: usize,
  823}
  824
  825impl Default for SelectionHistoryMode {
  826    fn default() -> Self {
  827        Self::Normal
  828    }
  829}
  830
  831#[derive(Default)]
  832struct SelectionHistory {
  833    #[allow(clippy::type_complexity)]
  834    selections_by_transaction:
  835        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  836    mode: SelectionHistoryMode,
  837    undo_stack: VecDeque<SelectionHistoryEntry>,
  838    redo_stack: VecDeque<SelectionHistoryEntry>,
  839}
  840
  841impl SelectionHistory {
  842    fn insert_transaction(
  843        &mut self,
  844        transaction_id: TransactionId,
  845        selections: Arc<[Selection<Anchor>]>,
  846    ) {
  847        self.selections_by_transaction
  848            .insert(transaction_id, (selections, None));
  849    }
  850
  851    #[allow(clippy::type_complexity)]
  852    fn transaction(
  853        &self,
  854        transaction_id: TransactionId,
  855    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  856        self.selections_by_transaction.get(&transaction_id)
  857    }
  858
  859    #[allow(clippy::type_complexity)]
  860    fn transaction_mut(
  861        &mut self,
  862        transaction_id: TransactionId,
  863    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  864        self.selections_by_transaction.get_mut(&transaction_id)
  865    }
  866
  867    fn push(&mut self, entry: SelectionHistoryEntry) {
  868        if !entry.selections.is_empty() {
  869            match self.mode {
  870                SelectionHistoryMode::Normal => {
  871                    self.push_undo(entry);
  872                    self.redo_stack.clear();
  873                }
  874                SelectionHistoryMode::Undoing => self.push_redo(entry),
  875                SelectionHistoryMode::Redoing => self.push_undo(entry),
  876            }
  877        }
  878    }
  879
  880    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  881        if self
  882            .undo_stack
  883            .back()
  884            .map_or(true, |e| e.selections != entry.selections)
  885        {
  886            self.undo_stack.push_back(entry);
  887            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  888                self.undo_stack.pop_front();
  889            }
  890        }
  891    }
  892
  893    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  894        if self
  895            .redo_stack
  896            .back()
  897            .map_or(true, |e| e.selections != entry.selections)
  898        {
  899            self.redo_stack.push_back(entry);
  900            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  901                self.redo_stack.pop_front();
  902            }
  903        }
  904    }
  905}
  906
  907struct RowHighlight {
  908    index: usize,
  909    range: Range<Anchor>,
  910    color: Hsla,
  911    should_autoscroll: bool,
  912}
  913
  914#[derive(Clone, Debug)]
  915struct AddSelectionsState {
  916    above: bool,
  917    stack: Vec<usize>,
  918}
  919
  920#[derive(Clone)]
  921struct SelectNextState {
  922    query: AhoCorasick,
  923    wordwise: bool,
  924    done: bool,
  925}
  926
  927impl std::fmt::Debug for SelectNextState {
  928    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  929        f.debug_struct(std::any::type_name::<Self>())
  930            .field("wordwise", &self.wordwise)
  931            .field("done", &self.done)
  932            .finish()
  933    }
  934}
  935
  936#[derive(Debug)]
  937struct AutocloseRegion {
  938    selection_id: usize,
  939    range: Range<Anchor>,
  940    pair: BracketPair,
  941}
  942
  943#[derive(Debug)]
  944struct SnippetState {
  945    ranges: Vec<Vec<Range<Anchor>>>,
  946    active_index: usize,
  947    choices: Vec<Option<Vec<String>>>,
  948}
  949
  950#[doc(hidden)]
  951pub struct RenameState {
  952    pub range: Range<Anchor>,
  953    pub old_name: Arc<str>,
  954    pub editor: Entity<Editor>,
  955    block_id: CustomBlockId,
  956}
  957
  958struct InvalidationStack<T>(Vec<T>);
  959
  960struct RegisteredInlineCompletionProvider {
  961    provider: Arc<dyn InlineCompletionProviderHandle>,
  962    _subscription: Subscription,
  963}
  964
  965#[derive(Debug)]
  966struct ActiveDiagnosticGroup {
  967    primary_range: Range<Anchor>,
  968    primary_message: String,
  969    group_id: usize,
  970    blocks: HashMap<CustomBlockId, Diagnostic>,
  971    is_valid: bool,
  972}
  973
  974#[derive(Serialize, Deserialize, Clone, Debug)]
  975pub struct ClipboardSelection {
  976    pub len: usize,
  977    pub is_entire_line: bool,
  978    pub first_line_indent: u32,
  979}
  980
  981#[derive(Debug)]
  982pub(crate) struct NavigationData {
  983    cursor_anchor: Anchor,
  984    cursor_position: Point,
  985    scroll_anchor: ScrollAnchor,
  986    scroll_top_row: u32,
  987}
  988
  989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  990pub enum GotoDefinitionKind {
  991    Symbol,
  992    Declaration,
  993    Type,
  994    Implementation,
  995}
  996
  997#[derive(Debug, Clone)]
  998enum InlayHintRefreshReason {
  999    Toggle(bool),
 1000    SettingsChange(InlayHintSettings),
 1001    NewLinesShown,
 1002    BufferEdited(HashSet<Arc<Language>>),
 1003    RefreshRequested,
 1004    ExcerptsRemoved(Vec<ExcerptId>),
 1005}
 1006
 1007impl InlayHintRefreshReason {
 1008    fn description(&self) -> &'static str {
 1009        match self {
 1010            Self::Toggle(_) => "toggle",
 1011            Self::SettingsChange(_) => "settings change",
 1012            Self::NewLinesShown => "new lines shown",
 1013            Self::BufferEdited(_) => "buffer edited",
 1014            Self::RefreshRequested => "refresh requested",
 1015            Self::ExcerptsRemoved(_) => "excerpts removed",
 1016        }
 1017    }
 1018}
 1019
 1020pub enum FormatTarget {
 1021    Buffers,
 1022    Ranges(Vec<Range<MultiBufferPoint>>),
 1023}
 1024
 1025pub(crate) struct FocusedBlock {
 1026    id: BlockId,
 1027    focus_handle: WeakFocusHandle,
 1028}
 1029
 1030#[derive(Clone)]
 1031enum JumpData {
 1032    MultiBufferRow {
 1033        row: MultiBufferRow,
 1034        line_offset_from_top: u32,
 1035    },
 1036    MultiBufferPoint {
 1037        excerpt_id: ExcerptId,
 1038        position: Point,
 1039        anchor: text::Anchor,
 1040        line_offset_from_top: u32,
 1041    },
 1042}
 1043
 1044pub enum MultibufferSelectionMode {
 1045    First,
 1046    All,
 1047}
 1048
 1049impl Editor {
 1050    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1051        let buffer = cx.new(|cx| Buffer::local("", cx));
 1052        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1053        Self::new(
 1054            EditorMode::SingleLine { auto_width: false },
 1055            buffer,
 1056            None,
 1057            false,
 1058            window,
 1059            cx,
 1060        )
 1061    }
 1062
 1063    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1064        let buffer = cx.new(|cx| Buffer::local("", cx));
 1065        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1066        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1067    }
 1068
 1069    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1070        let buffer = cx.new(|cx| Buffer::local("", cx));
 1071        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1072        Self::new(
 1073            EditorMode::SingleLine { auto_width: true },
 1074            buffer,
 1075            None,
 1076            false,
 1077            window,
 1078            cx,
 1079        )
 1080    }
 1081
 1082    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1083        let buffer = cx.new(|cx| Buffer::local("", cx));
 1084        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1085        Self::new(
 1086            EditorMode::AutoHeight { max_lines },
 1087            buffer,
 1088            None,
 1089            false,
 1090            window,
 1091            cx,
 1092        )
 1093    }
 1094
 1095    pub fn for_buffer(
 1096        buffer: Entity<Buffer>,
 1097        project: Option<Entity<Project>>,
 1098        window: &mut Window,
 1099        cx: &mut Context<Self>,
 1100    ) -> Self {
 1101        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1102        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1103    }
 1104
 1105    pub fn for_multibuffer(
 1106        buffer: Entity<MultiBuffer>,
 1107        project: Option<Entity<Project>>,
 1108        show_excerpt_controls: bool,
 1109        window: &mut Window,
 1110        cx: &mut Context<Self>,
 1111    ) -> Self {
 1112        Self::new(
 1113            EditorMode::Full,
 1114            buffer,
 1115            project,
 1116            show_excerpt_controls,
 1117            window,
 1118            cx,
 1119        )
 1120    }
 1121
 1122    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1123        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1124        let mut clone = Self::new(
 1125            self.mode,
 1126            self.buffer.clone(),
 1127            self.project.clone(),
 1128            show_excerpt_controls,
 1129            window,
 1130            cx,
 1131        );
 1132        self.display_map.update(cx, |display_map, cx| {
 1133            let snapshot = display_map.snapshot(cx);
 1134            clone.display_map.update(cx, |display_map, cx| {
 1135                display_map.set_state(&snapshot, cx);
 1136            });
 1137        });
 1138        clone.selections.clone_state(&self.selections);
 1139        clone.scroll_manager.clone_state(&self.scroll_manager);
 1140        clone.searchable = self.searchable;
 1141        clone
 1142    }
 1143
 1144    pub fn new(
 1145        mode: EditorMode,
 1146        buffer: Entity<MultiBuffer>,
 1147        project: Option<Entity<Project>>,
 1148        show_excerpt_controls: bool,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let style = window.text_style();
 1153        let font_size = style.font_size.to_pixels(window.rem_size());
 1154        let editor = cx.entity().downgrade();
 1155        let fold_placeholder = FoldPlaceholder {
 1156            constrain_width: true,
 1157            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1158                let editor = editor.clone();
 1159                div()
 1160                    .id(fold_id)
 1161                    .bg(cx.theme().colors().ghost_element_background)
 1162                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1163                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1164                    .rounded_sm()
 1165                    .size_full()
 1166                    .cursor_pointer()
 1167                    .child("")
 1168                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1169                    .on_click(move |_, _window, cx| {
 1170                        editor
 1171                            .update(cx, |editor, cx| {
 1172                                editor.unfold_ranges(
 1173                                    &[fold_range.start..fold_range.end],
 1174                                    true,
 1175                                    false,
 1176                                    cx,
 1177                                );
 1178                                cx.stop_propagation();
 1179                            })
 1180                            .ok();
 1181                    })
 1182                    .into_any()
 1183            }),
 1184            merge_adjacent: true,
 1185            ..Default::default()
 1186        };
 1187        let display_map = cx.new(|cx| {
 1188            DisplayMap::new(
 1189                buffer.clone(),
 1190                style.font(),
 1191                font_size,
 1192                None,
 1193                show_excerpt_controls,
 1194                FILE_HEADER_HEIGHT,
 1195                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1196                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1197                fold_placeholder,
 1198                cx,
 1199            )
 1200        });
 1201
 1202        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1203
 1204        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1205
 1206        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1207            .then(|| language_settings::SoftWrap::None);
 1208
 1209        let mut project_subscriptions = Vec::new();
 1210        if mode == EditorMode::Full {
 1211            if let Some(project) = project.as_ref() {
 1212                if buffer.read(cx).is_singleton() {
 1213                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1214                        cx.emit(EditorEvent::TitleChanged);
 1215                    }));
 1216                }
 1217                project_subscriptions.push(cx.subscribe_in(
 1218                    project,
 1219                    window,
 1220                    |editor, _, event, window, cx| {
 1221                        if let project::Event::RefreshInlayHints = event {
 1222                            editor
 1223                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1224                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1225                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1226                                let focus_handle = editor.focus_handle(cx);
 1227                                if focus_handle.is_focused(window) {
 1228                                    let snapshot = buffer.read(cx).snapshot();
 1229                                    for (range, snippet) in snippet_edits {
 1230                                        let editor_range =
 1231                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1232                                        editor
 1233                                            .insert_snippet(
 1234                                                &[editor_range],
 1235                                                snippet.clone(),
 1236                                                window,
 1237                                                cx,
 1238                                            )
 1239                                            .ok();
 1240                                    }
 1241                                }
 1242                            }
 1243                        }
 1244                    },
 1245                ));
 1246                if let Some(task_inventory) = project
 1247                    .read(cx)
 1248                    .task_store()
 1249                    .read(cx)
 1250                    .task_inventory()
 1251                    .cloned()
 1252                {
 1253                    project_subscriptions.push(cx.observe_in(
 1254                        &task_inventory,
 1255                        window,
 1256                        |editor, _, window, cx| {
 1257                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1258                        },
 1259                    ));
 1260                }
 1261            }
 1262        }
 1263
 1264        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1265
 1266        let inlay_hint_settings =
 1267            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1268        let focus_handle = cx.focus_handle();
 1269        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1270            .detach();
 1271        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1272            .detach();
 1273        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1274            .detach();
 1275        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1276            .detach();
 1277
 1278        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1279            Some(false)
 1280        } else {
 1281            None
 1282        };
 1283
 1284        let mut code_action_providers = Vec::new();
 1285        if let Some(project) = project.clone() {
 1286            get_unstaged_changes_for_buffers(
 1287                &project,
 1288                buffer.read(cx).all_buffers(),
 1289                buffer.clone(),
 1290                cx,
 1291            );
 1292            code_action_providers.push(Rc::new(project) as Rc<_>);
 1293        }
 1294
 1295        let mut this = Self {
 1296            focus_handle,
 1297            show_cursor_when_unfocused: false,
 1298            last_focused_descendant: None,
 1299            buffer: buffer.clone(),
 1300            display_map: display_map.clone(),
 1301            selections,
 1302            scroll_manager: ScrollManager::new(cx),
 1303            columnar_selection_tail: None,
 1304            add_selections_state: None,
 1305            select_next_state: None,
 1306            select_prev_state: None,
 1307            selection_history: Default::default(),
 1308            autoclose_regions: Default::default(),
 1309            snippet_stack: Default::default(),
 1310            select_larger_syntax_node_stack: Vec::new(),
 1311            ime_transaction: Default::default(),
 1312            active_diagnostics: None,
 1313            soft_wrap_mode_override,
 1314            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1315            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1316            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1317            project,
 1318            blink_manager: blink_manager.clone(),
 1319            show_local_selections: true,
 1320            show_scrollbars: true,
 1321            mode,
 1322            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1323            show_gutter: mode == EditorMode::Full,
 1324            show_line_numbers: None,
 1325            use_relative_line_numbers: None,
 1326            show_git_diff_gutter: None,
 1327            show_code_actions: None,
 1328            show_runnables: None,
 1329            show_wrap_guides: None,
 1330            show_indent_guides,
 1331            placeholder_text: None,
 1332            highlight_order: 0,
 1333            highlighted_rows: HashMap::default(),
 1334            background_highlights: Default::default(),
 1335            gutter_highlights: TreeMap::default(),
 1336            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1337            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1338            nav_history: None,
 1339            context_menu: RefCell::new(None),
 1340            mouse_context_menu: None,
 1341            completion_tasks: Default::default(),
 1342            signature_help_state: SignatureHelpState::default(),
 1343            auto_signature_help: None,
 1344            find_all_references_task_sources: Vec::new(),
 1345            next_completion_id: 0,
 1346            next_inlay_id: 0,
 1347            code_action_providers,
 1348            available_code_actions: Default::default(),
 1349            code_actions_task: Default::default(),
 1350            document_highlights_task: Default::default(),
 1351            linked_editing_range_task: Default::default(),
 1352            pending_rename: Default::default(),
 1353            searchable: true,
 1354            cursor_shape: EditorSettings::get_global(cx)
 1355                .cursor_shape
 1356                .unwrap_or_default(),
 1357            current_line_highlight: None,
 1358            autoindent_mode: Some(AutoindentMode::EachLine),
 1359            collapse_matches: false,
 1360            workspace: None,
 1361            input_enabled: true,
 1362            use_modal_editing: mode == EditorMode::Full,
 1363            read_only: false,
 1364            use_autoclose: true,
 1365            use_auto_surround: true,
 1366            auto_replace_emoji_shortcode: false,
 1367            leader_peer_id: None,
 1368            remote_id: None,
 1369            hover_state: Default::default(),
 1370            pending_mouse_down: None,
 1371            hovered_link_state: Default::default(),
 1372            inline_completion_provider: None,
 1373            active_inline_completion: None,
 1374            stale_inline_completion_in_menu: None,
 1375            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1376
 1377            gutter_hovered: false,
 1378            pixel_position_of_newest_cursor: None,
 1379            last_bounds: None,
 1380            expect_bounds_change: None,
 1381            gutter_dimensions: GutterDimensions::default(),
 1382            style: None,
 1383            show_cursor_names: false,
 1384            hovered_cursors: Default::default(),
 1385            next_editor_action_id: EditorActionId::default(),
 1386            editor_actions: Rc::default(),
 1387            show_inline_completions_override: None,
 1388            enable_inline_completions: true,
 1389            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1390            custom_context_menu: None,
 1391            show_git_blame_gutter: false,
 1392            show_git_blame_inline: false,
 1393            show_selection_menu: None,
 1394            show_git_blame_inline_delay_task: None,
 1395            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1396            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1397                .session
 1398                .restore_unsaved_buffers,
 1399            blame: None,
 1400            blame_subscription: None,
 1401            tasks: Default::default(),
 1402            _subscriptions: vec![
 1403                cx.observe(&buffer, Self::on_buffer_changed),
 1404                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1405                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1406                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1407                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1408                cx.observe_window_activation(window, |editor, window, cx| {
 1409                    let active = window.is_window_active();
 1410                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1411                        if active {
 1412                            blink_manager.enable(cx);
 1413                        } else {
 1414                            blink_manager.disable(cx);
 1415                        }
 1416                    });
 1417                }),
 1418            ],
 1419            tasks_update_task: None,
 1420            linked_edit_ranges: Default::default(),
 1421            in_project_search: false,
 1422            previous_search_ranges: None,
 1423            breadcrumb_header: None,
 1424            focused_block: None,
 1425            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1426            addons: HashMap::default(),
 1427            registered_buffers: HashMap::default(),
 1428            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1429            selection_mark_mode: false,
 1430            toggle_fold_multiple_buffers: Task::ready(()),
 1431            text_style_refinement: None,
 1432        };
 1433        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1434        this._subscriptions.extend(project_subscriptions);
 1435
 1436        this.end_selection(window, cx);
 1437        this.scroll_manager.show_scrollbar(window, cx);
 1438
 1439        if mode == EditorMode::Full {
 1440            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1441            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1442
 1443            if this.git_blame_inline_enabled {
 1444                this.git_blame_inline_enabled = true;
 1445                this.start_git_blame_inline(false, window, cx);
 1446            }
 1447
 1448            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1449                if let Some(project) = this.project.as_ref() {
 1450                    let lsp_store = project.read(cx).lsp_store();
 1451                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1452                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1453                    });
 1454                    this.registered_buffers
 1455                        .insert(buffer.read(cx).remote_id(), handle);
 1456                }
 1457            }
 1458        }
 1459
 1460        this.report_editor_event("Editor Opened", None, cx);
 1461        this
 1462    }
 1463
 1464    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1465        self.mouse_context_menu
 1466            .as_ref()
 1467            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1468    }
 1469
 1470    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1471        let mut key_context = KeyContext::new_with_defaults();
 1472        key_context.add("Editor");
 1473        let mode = match self.mode {
 1474            EditorMode::SingleLine { .. } => "single_line",
 1475            EditorMode::AutoHeight { .. } => "auto_height",
 1476            EditorMode::Full => "full",
 1477        };
 1478
 1479        if EditorSettings::jupyter_enabled(cx) {
 1480            key_context.add("jupyter");
 1481        }
 1482
 1483        key_context.set("mode", mode);
 1484        if self.pending_rename.is_some() {
 1485            key_context.add("renaming");
 1486        }
 1487        match self.context_menu.borrow().as_ref() {
 1488            Some(CodeContextMenu::Completions(_)) => {
 1489                key_context.add("menu");
 1490                key_context.add("showing_completions");
 1491            }
 1492            Some(CodeContextMenu::CodeActions(_)) => {
 1493                key_context.add("menu");
 1494                key_context.add("showing_code_actions")
 1495            }
 1496            None => {}
 1497        }
 1498
 1499        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1500        if !self.focus_handle(cx).contains_focused(window, cx)
 1501            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1502        {
 1503            for addon in self.addons.values() {
 1504                addon.extend_key_context(&mut key_context, cx)
 1505            }
 1506        }
 1507
 1508        if let Some(extension) = self
 1509            .buffer
 1510            .read(cx)
 1511            .as_singleton()
 1512            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1513        {
 1514            key_context.set("extension", extension.to_string());
 1515        }
 1516
 1517        if self.has_active_inline_completion() {
 1518            key_context.add("copilot_suggestion");
 1519            key_context.add("inline_completion");
 1520        }
 1521
 1522        if self.selection_mark_mode {
 1523            key_context.add("selection_mode");
 1524        }
 1525
 1526        key_context
 1527    }
 1528
 1529    pub fn new_file(
 1530        workspace: &mut Workspace,
 1531        _: &workspace::NewFile,
 1532        window: &mut Window,
 1533        cx: &mut Context<Workspace>,
 1534    ) {
 1535        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1536            "Failed to create buffer",
 1537            window,
 1538            cx,
 1539            |e, _, _| match e.error_code() {
 1540                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1541                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1542                e.error_tag("required").unwrap_or("the latest version")
 1543            )),
 1544                _ => None,
 1545            },
 1546        );
 1547    }
 1548
 1549    pub fn new_in_workspace(
 1550        workspace: &mut Workspace,
 1551        window: &mut Window,
 1552        cx: &mut Context<Workspace>,
 1553    ) -> Task<Result<Entity<Editor>>> {
 1554        let project = workspace.project().clone();
 1555        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1556
 1557        cx.spawn_in(window, |workspace, mut cx| async move {
 1558            let buffer = create.await?;
 1559            workspace.update_in(&mut cx, |workspace, window, cx| {
 1560                let editor =
 1561                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1562                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1563                editor
 1564            })
 1565        })
 1566    }
 1567
 1568    fn new_file_vertical(
 1569        workspace: &mut Workspace,
 1570        _: &workspace::NewFileSplitVertical,
 1571        window: &mut Window,
 1572        cx: &mut Context<Workspace>,
 1573    ) {
 1574        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1575    }
 1576
 1577    fn new_file_horizontal(
 1578        workspace: &mut Workspace,
 1579        _: &workspace::NewFileSplitHorizontal,
 1580        window: &mut Window,
 1581        cx: &mut Context<Workspace>,
 1582    ) {
 1583        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1584    }
 1585
 1586    fn new_file_in_direction(
 1587        workspace: &mut Workspace,
 1588        direction: SplitDirection,
 1589        window: &mut Window,
 1590        cx: &mut Context<Workspace>,
 1591    ) {
 1592        let project = workspace.project().clone();
 1593        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1594
 1595        cx.spawn_in(window, |workspace, mut cx| async move {
 1596            let buffer = create.await?;
 1597            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1598                workspace.split_item(
 1599                    direction,
 1600                    Box::new(
 1601                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1602                    ),
 1603                    window,
 1604                    cx,
 1605                )
 1606            })?;
 1607            anyhow::Ok(())
 1608        })
 1609        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1610            match e.error_code() {
 1611                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1612                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1613                e.error_tag("required").unwrap_or("the latest version")
 1614            )),
 1615                _ => None,
 1616            }
 1617        });
 1618    }
 1619
 1620    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1621        self.leader_peer_id
 1622    }
 1623
 1624    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1625        &self.buffer
 1626    }
 1627
 1628    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1629        self.workspace.as_ref()?.0.upgrade()
 1630    }
 1631
 1632    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1633        self.buffer().read(cx).title(cx)
 1634    }
 1635
 1636    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1637        let git_blame_gutter_max_author_length = self
 1638            .render_git_blame_gutter(cx)
 1639            .then(|| {
 1640                if let Some(blame) = self.blame.as_ref() {
 1641                    let max_author_length =
 1642                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1643                    Some(max_author_length)
 1644                } else {
 1645                    None
 1646                }
 1647            })
 1648            .flatten();
 1649
 1650        EditorSnapshot {
 1651            mode: self.mode,
 1652            show_gutter: self.show_gutter,
 1653            show_line_numbers: self.show_line_numbers,
 1654            show_git_diff_gutter: self.show_git_diff_gutter,
 1655            show_code_actions: self.show_code_actions,
 1656            show_runnables: self.show_runnables,
 1657            git_blame_gutter_max_author_length,
 1658            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1659            scroll_anchor: self.scroll_manager.anchor(),
 1660            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1661            placeholder_text: self.placeholder_text.clone(),
 1662            is_focused: self.focus_handle.is_focused(window),
 1663            current_line_highlight: self
 1664                .current_line_highlight
 1665                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1666            gutter_hovered: self.gutter_hovered,
 1667        }
 1668    }
 1669
 1670    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1671        self.buffer.read(cx).language_at(point, cx)
 1672    }
 1673
 1674    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1675        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1676    }
 1677
 1678    pub fn active_excerpt(
 1679        &self,
 1680        cx: &App,
 1681    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1682        self.buffer
 1683            .read(cx)
 1684            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1685    }
 1686
 1687    pub fn mode(&self) -> EditorMode {
 1688        self.mode
 1689    }
 1690
 1691    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1692        self.collaboration_hub.as_deref()
 1693    }
 1694
 1695    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1696        self.collaboration_hub = Some(hub);
 1697    }
 1698
 1699    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1700        self.in_project_search = in_project_search;
 1701    }
 1702
 1703    pub fn set_custom_context_menu(
 1704        &mut self,
 1705        f: impl 'static
 1706            + Fn(
 1707                &mut Self,
 1708                DisplayPoint,
 1709                &mut Window,
 1710                &mut Context<Self>,
 1711            ) -> Option<Entity<ui::ContextMenu>>,
 1712    ) {
 1713        self.custom_context_menu = Some(Box::new(f))
 1714    }
 1715
 1716    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1717        self.completion_provider = provider;
 1718    }
 1719
 1720    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1721        self.semantics_provider.clone()
 1722    }
 1723
 1724    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1725        self.semantics_provider = provider;
 1726    }
 1727
 1728    pub fn set_inline_completion_provider<T>(
 1729        &mut self,
 1730        provider: Option<Entity<T>>,
 1731        window: &mut Window,
 1732        cx: &mut Context<Self>,
 1733    ) where
 1734        T: InlineCompletionProvider,
 1735    {
 1736        self.inline_completion_provider =
 1737            provider.map(|provider| RegisteredInlineCompletionProvider {
 1738                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1739                    if this.focus_handle.is_focused(window) {
 1740                        this.update_visible_inline_completion(window, cx);
 1741                    }
 1742                }),
 1743                provider: Arc::new(provider),
 1744            });
 1745        self.refresh_inline_completion(false, false, window, cx);
 1746    }
 1747
 1748    pub fn placeholder_text(&self) -> Option<&str> {
 1749        self.placeholder_text.as_deref()
 1750    }
 1751
 1752    pub fn set_placeholder_text(
 1753        &mut self,
 1754        placeholder_text: impl Into<Arc<str>>,
 1755        cx: &mut Context<Self>,
 1756    ) {
 1757        let placeholder_text = Some(placeholder_text.into());
 1758        if self.placeholder_text != placeholder_text {
 1759            self.placeholder_text = placeholder_text;
 1760            cx.notify();
 1761        }
 1762    }
 1763
 1764    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1765        self.cursor_shape = cursor_shape;
 1766
 1767        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1768        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1769
 1770        cx.notify();
 1771    }
 1772
 1773    pub fn set_current_line_highlight(
 1774        &mut self,
 1775        current_line_highlight: Option<CurrentLineHighlight>,
 1776    ) {
 1777        self.current_line_highlight = current_line_highlight;
 1778    }
 1779
 1780    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1781        self.collapse_matches = collapse_matches;
 1782    }
 1783
 1784    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1785        let buffers = self.buffer.read(cx).all_buffers();
 1786        let Some(lsp_store) = self.lsp_store(cx) else {
 1787            return;
 1788        };
 1789        lsp_store.update(cx, |lsp_store, cx| {
 1790            for buffer in buffers {
 1791                self.registered_buffers
 1792                    .entry(buffer.read(cx).remote_id())
 1793                    .or_insert_with(|| {
 1794                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1795                    });
 1796            }
 1797        })
 1798    }
 1799
 1800    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1801        if self.collapse_matches {
 1802            return range.start..range.start;
 1803        }
 1804        range.clone()
 1805    }
 1806
 1807    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1808        if self.display_map.read(cx).clip_at_line_ends != clip {
 1809            self.display_map
 1810                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1811        }
 1812    }
 1813
 1814    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1815        self.input_enabled = input_enabled;
 1816    }
 1817
 1818    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1819        self.enable_inline_completions = enabled;
 1820        if !self.enable_inline_completions {
 1821            self.take_active_inline_completion(cx);
 1822            cx.notify();
 1823        }
 1824    }
 1825
 1826    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1827        self.menu_inline_completions_policy = value;
 1828    }
 1829
 1830    pub fn set_autoindent(&mut self, autoindent: bool) {
 1831        if autoindent {
 1832            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1833        } else {
 1834            self.autoindent_mode = None;
 1835        }
 1836    }
 1837
 1838    pub fn read_only(&self, cx: &App) -> bool {
 1839        self.read_only || self.buffer.read(cx).read_only()
 1840    }
 1841
 1842    pub fn set_read_only(&mut self, read_only: bool) {
 1843        self.read_only = read_only;
 1844    }
 1845
 1846    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1847        self.use_autoclose = autoclose;
 1848    }
 1849
 1850    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1851        self.use_auto_surround = auto_surround;
 1852    }
 1853
 1854    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1855        self.auto_replace_emoji_shortcode = auto_replace;
 1856    }
 1857
 1858    pub fn toggle_inline_completions(
 1859        &mut self,
 1860        _: &ToggleInlineCompletions,
 1861        window: &mut Window,
 1862        cx: &mut Context<Self>,
 1863    ) {
 1864        if self.show_inline_completions_override.is_some() {
 1865            self.set_show_inline_completions(None, window, cx);
 1866        } else {
 1867            let cursor = self.selections.newest_anchor().head();
 1868            if let Some((buffer, cursor_buffer_position)) =
 1869                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1870            {
 1871                let show_inline_completions =
 1872                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1873                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1874            }
 1875        }
 1876    }
 1877
 1878    pub fn set_show_inline_completions(
 1879        &mut self,
 1880        show_inline_completions: Option<bool>,
 1881        window: &mut Window,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        self.show_inline_completions_override = show_inline_completions;
 1885        self.refresh_inline_completion(false, true, window, cx);
 1886    }
 1887
 1888    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1889        let cursor = self.selections.newest_anchor().head();
 1890        if let Some((buffer, buffer_position)) =
 1891            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1892        {
 1893            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1894        } else {
 1895            false
 1896        }
 1897    }
 1898
 1899    fn should_show_inline_completions(
 1900        &self,
 1901        buffer: &Entity<Buffer>,
 1902        buffer_position: language::Anchor,
 1903        cx: &App,
 1904    ) -> bool {
 1905        if !self.snippet_stack.is_empty() {
 1906            return false;
 1907        }
 1908
 1909        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1910            return false;
 1911        }
 1912
 1913        if let Some(provider) = self.inline_completion_provider() {
 1914            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1915                show_inline_completions
 1916            } else {
 1917                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1918            }
 1919        } else {
 1920            false
 1921        }
 1922    }
 1923
 1924    fn inline_completions_disabled_in_scope(
 1925        &self,
 1926        buffer: &Entity<Buffer>,
 1927        buffer_position: language::Anchor,
 1928        cx: &App,
 1929    ) -> bool {
 1930        let snapshot = buffer.read(cx).snapshot();
 1931        let settings = snapshot.settings_at(buffer_position, cx);
 1932
 1933        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1934            return false;
 1935        };
 1936
 1937        scope.override_name().map_or(false, |scope_name| {
 1938            settings
 1939                .inline_completions_disabled_in
 1940                .iter()
 1941                .any(|s| s == scope_name)
 1942        })
 1943    }
 1944
 1945    pub fn set_use_modal_editing(&mut self, to: bool) {
 1946        self.use_modal_editing = to;
 1947    }
 1948
 1949    pub fn use_modal_editing(&self) -> bool {
 1950        self.use_modal_editing
 1951    }
 1952
 1953    fn selections_did_change(
 1954        &mut self,
 1955        local: bool,
 1956        old_cursor_position: &Anchor,
 1957        show_completions: bool,
 1958        window: &mut Window,
 1959        cx: &mut Context<Self>,
 1960    ) {
 1961        window.invalidate_character_coordinates();
 1962
 1963        // Copy selections to primary selection buffer
 1964        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1965        if local {
 1966            let selections = self.selections.all::<usize>(cx);
 1967            let buffer_handle = self.buffer.read(cx).read(cx);
 1968
 1969            let mut text = String::new();
 1970            for (index, selection) in selections.iter().enumerate() {
 1971                let text_for_selection = buffer_handle
 1972                    .text_for_range(selection.start..selection.end)
 1973                    .collect::<String>();
 1974
 1975                text.push_str(&text_for_selection);
 1976                if index != selections.len() - 1 {
 1977                    text.push('\n');
 1978                }
 1979            }
 1980
 1981            if !text.is_empty() {
 1982                cx.write_to_primary(ClipboardItem::new_string(text));
 1983            }
 1984        }
 1985
 1986        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1987            self.buffer.update(cx, |buffer, cx| {
 1988                buffer.set_active_selections(
 1989                    &self.selections.disjoint_anchors(),
 1990                    self.selections.line_mode,
 1991                    self.cursor_shape,
 1992                    cx,
 1993                )
 1994            });
 1995        }
 1996        let display_map = self
 1997            .display_map
 1998            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1999        let buffer = &display_map.buffer_snapshot;
 2000        self.add_selections_state = None;
 2001        self.select_next_state = None;
 2002        self.select_prev_state = None;
 2003        self.select_larger_syntax_node_stack.clear();
 2004        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2005        self.snippet_stack
 2006            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2007        self.take_rename(false, window, cx);
 2008
 2009        let new_cursor_position = self.selections.newest_anchor().head();
 2010
 2011        self.push_to_nav_history(
 2012            *old_cursor_position,
 2013            Some(new_cursor_position.to_point(buffer)),
 2014            cx,
 2015        );
 2016
 2017        if local {
 2018            let new_cursor_position = self.selections.newest_anchor().head();
 2019            let mut context_menu = self.context_menu.borrow_mut();
 2020            let completion_menu = match context_menu.as_ref() {
 2021                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2022                _ => {
 2023                    *context_menu = None;
 2024                    None
 2025                }
 2026            };
 2027
 2028            if let Some(completion_menu) = completion_menu {
 2029                let cursor_position = new_cursor_position.to_offset(buffer);
 2030                let (word_range, kind) =
 2031                    buffer.surrounding_word(completion_menu.initial_position, true);
 2032                if kind == Some(CharKind::Word)
 2033                    && word_range.to_inclusive().contains(&cursor_position)
 2034                {
 2035                    let mut completion_menu = completion_menu.clone();
 2036                    drop(context_menu);
 2037
 2038                    let query = Self::completion_query(buffer, cursor_position);
 2039                    cx.spawn(move |this, mut cx| async move {
 2040                        completion_menu
 2041                            .filter(query.as_deref(), cx.background_executor().clone())
 2042                            .await;
 2043
 2044                        this.update(&mut cx, |this, cx| {
 2045                            let mut context_menu = this.context_menu.borrow_mut();
 2046                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2047                            else {
 2048                                return;
 2049                            };
 2050
 2051                            if menu.id > completion_menu.id {
 2052                                return;
 2053                            }
 2054
 2055                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2056                            drop(context_menu);
 2057                            cx.notify();
 2058                        })
 2059                    })
 2060                    .detach();
 2061
 2062                    if show_completions {
 2063                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2064                    }
 2065                } else {
 2066                    drop(context_menu);
 2067                    self.hide_context_menu(window, cx);
 2068                }
 2069            } else {
 2070                drop(context_menu);
 2071            }
 2072
 2073            hide_hover(self, cx);
 2074
 2075            if old_cursor_position.to_display_point(&display_map).row()
 2076                != new_cursor_position.to_display_point(&display_map).row()
 2077            {
 2078                self.available_code_actions.take();
 2079            }
 2080            self.refresh_code_actions(window, cx);
 2081            self.refresh_document_highlights(cx);
 2082            refresh_matching_bracket_highlights(self, window, cx);
 2083            self.update_visible_inline_completion(window, cx);
 2084            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2085            if self.git_blame_inline_enabled {
 2086                self.start_inline_blame_timer(window, cx);
 2087            }
 2088        }
 2089
 2090        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2091        cx.emit(EditorEvent::SelectionsChanged { local });
 2092
 2093        if self.selections.disjoint_anchors().len() == 1 {
 2094            cx.emit(SearchEvent::ActiveMatchChanged)
 2095        }
 2096        cx.notify();
 2097    }
 2098
 2099    pub fn change_selections<R>(
 2100        &mut self,
 2101        autoscroll: Option<Autoscroll>,
 2102        window: &mut Window,
 2103        cx: &mut Context<Self>,
 2104        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2105    ) -> R {
 2106        self.change_selections_inner(autoscroll, true, window, cx, change)
 2107    }
 2108
 2109    pub fn change_selections_inner<R>(
 2110        &mut self,
 2111        autoscroll: Option<Autoscroll>,
 2112        request_completions: bool,
 2113        window: &mut Window,
 2114        cx: &mut Context<Self>,
 2115        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2116    ) -> R {
 2117        let old_cursor_position = self.selections.newest_anchor().head();
 2118        self.push_to_selection_history();
 2119
 2120        let (changed, result) = self.selections.change_with(cx, change);
 2121
 2122        if changed {
 2123            if let Some(autoscroll) = autoscroll {
 2124                self.request_autoscroll(autoscroll, cx);
 2125            }
 2126            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2127
 2128            if self.should_open_signature_help_automatically(
 2129                &old_cursor_position,
 2130                self.signature_help_state.backspace_pressed(),
 2131                cx,
 2132            ) {
 2133                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2134            }
 2135            self.signature_help_state.set_backspace_pressed(false);
 2136        }
 2137
 2138        result
 2139    }
 2140
 2141    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2142    where
 2143        I: IntoIterator<Item = (Range<S>, T)>,
 2144        S: ToOffset,
 2145        T: Into<Arc<str>>,
 2146    {
 2147        if self.read_only(cx) {
 2148            return;
 2149        }
 2150
 2151        self.buffer
 2152            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2153    }
 2154
 2155    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2156    where
 2157        I: IntoIterator<Item = (Range<S>, T)>,
 2158        S: ToOffset,
 2159        T: Into<Arc<str>>,
 2160    {
 2161        if self.read_only(cx) {
 2162            return;
 2163        }
 2164
 2165        self.buffer.update(cx, |buffer, cx| {
 2166            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2167        });
 2168    }
 2169
 2170    pub fn edit_with_block_indent<I, S, T>(
 2171        &mut self,
 2172        edits: I,
 2173        original_indent_columns: Vec<u32>,
 2174        cx: &mut Context<Self>,
 2175    ) where
 2176        I: IntoIterator<Item = (Range<S>, T)>,
 2177        S: ToOffset,
 2178        T: Into<Arc<str>>,
 2179    {
 2180        if self.read_only(cx) {
 2181            return;
 2182        }
 2183
 2184        self.buffer.update(cx, |buffer, cx| {
 2185            buffer.edit(
 2186                edits,
 2187                Some(AutoindentMode::Block {
 2188                    original_indent_columns,
 2189                }),
 2190                cx,
 2191            )
 2192        });
 2193    }
 2194
 2195    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2196        self.hide_context_menu(window, cx);
 2197
 2198        match phase {
 2199            SelectPhase::Begin {
 2200                position,
 2201                add,
 2202                click_count,
 2203            } => self.begin_selection(position, add, click_count, window, cx),
 2204            SelectPhase::BeginColumnar {
 2205                position,
 2206                goal_column,
 2207                reset,
 2208            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2209            SelectPhase::Extend {
 2210                position,
 2211                click_count,
 2212            } => self.extend_selection(position, click_count, window, cx),
 2213            SelectPhase::Update {
 2214                position,
 2215                goal_column,
 2216                scroll_delta,
 2217            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2218            SelectPhase::End => self.end_selection(window, cx),
 2219        }
 2220    }
 2221
 2222    fn extend_selection(
 2223        &mut self,
 2224        position: DisplayPoint,
 2225        click_count: usize,
 2226        window: &mut Window,
 2227        cx: &mut Context<Self>,
 2228    ) {
 2229        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2230        let tail = self.selections.newest::<usize>(cx).tail();
 2231        self.begin_selection(position, false, click_count, window, cx);
 2232
 2233        let position = position.to_offset(&display_map, Bias::Left);
 2234        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2235
 2236        let mut pending_selection = self
 2237            .selections
 2238            .pending_anchor()
 2239            .expect("extend_selection not called with pending selection");
 2240        if position >= tail {
 2241            pending_selection.start = tail_anchor;
 2242        } else {
 2243            pending_selection.end = tail_anchor;
 2244            pending_selection.reversed = true;
 2245        }
 2246
 2247        let mut pending_mode = self.selections.pending_mode().unwrap();
 2248        match &mut pending_mode {
 2249            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2250            _ => {}
 2251        }
 2252
 2253        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2254            s.set_pending(pending_selection, pending_mode)
 2255        });
 2256    }
 2257
 2258    fn begin_selection(
 2259        &mut self,
 2260        position: DisplayPoint,
 2261        add: bool,
 2262        click_count: usize,
 2263        window: &mut Window,
 2264        cx: &mut Context<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(window) {
 2267            self.last_focused_descendant = None;
 2268            window.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272        let buffer = &display_map.buffer_snapshot;
 2273        let newest_selection = self.selections.newest_anchor().clone();
 2274        let position = display_map.clip_point(position, Bias::Left);
 2275
 2276        let start;
 2277        let end;
 2278        let mode;
 2279        let mut auto_scroll;
 2280        match click_count {
 2281            1 => {
 2282                start = buffer.anchor_before(position.to_point(&display_map));
 2283                end = start;
 2284                mode = SelectMode::Character;
 2285                auto_scroll = true;
 2286            }
 2287            2 => {
 2288                let range = movement::surrounding_word(&display_map, position);
 2289                start = buffer.anchor_before(range.start.to_point(&display_map));
 2290                end = buffer.anchor_before(range.end.to_point(&display_map));
 2291                mode = SelectMode::Word(start..end);
 2292                auto_scroll = true;
 2293            }
 2294            3 => {
 2295                let position = display_map
 2296                    .clip_point(position, Bias::Left)
 2297                    .to_point(&display_map);
 2298                let line_start = display_map.prev_line_boundary(position).0;
 2299                let next_line_start = buffer.clip_point(
 2300                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2301                    Bias::Left,
 2302                );
 2303                start = buffer.anchor_before(line_start);
 2304                end = buffer.anchor_before(next_line_start);
 2305                mode = SelectMode::Line(start..end);
 2306                auto_scroll = true;
 2307            }
 2308            _ => {
 2309                start = buffer.anchor_before(0);
 2310                end = buffer.anchor_before(buffer.len());
 2311                mode = SelectMode::All;
 2312                auto_scroll = false;
 2313            }
 2314        }
 2315        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2316
 2317        let point_to_delete: Option<usize> = {
 2318            let selected_points: Vec<Selection<Point>> =
 2319                self.selections.disjoint_in_range(start..end, cx);
 2320
 2321            if !add || click_count > 1 {
 2322                None
 2323            } else if !selected_points.is_empty() {
 2324                Some(selected_points[0].id)
 2325            } else {
 2326                let clicked_point_already_selected =
 2327                    self.selections.disjoint.iter().find(|selection| {
 2328                        selection.start.to_point(buffer) == start.to_point(buffer)
 2329                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2330                    });
 2331
 2332                clicked_point_already_selected.map(|selection| selection.id)
 2333            }
 2334        };
 2335
 2336        let selections_count = self.selections.count();
 2337
 2338        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2339            if let Some(point_to_delete) = point_to_delete {
 2340                s.delete(point_to_delete);
 2341
 2342                if selections_count == 1 {
 2343                    s.set_pending_anchor_range(start..end, mode);
 2344                }
 2345            } else {
 2346                if !add {
 2347                    s.clear_disjoint();
 2348                } else if click_count > 1 {
 2349                    s.delete(newest_selection.id)
 2350                }
 2351
 2352                s.set_pending_anchor_range(start..end, mode);
 2353            }
 2354        });
 2355    }
 2356
 2357    fn begin_columnar_selection(
 2358        &mut self,
 2359        position: DisplayPoint,
 2360        goal_column: u32,
 2361        reset: bool,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        if !self.focus_handle.is_focused(window) {
 2366            self.last_focused_descendant = None;
 2367            window.focus(&self.focus_handle);
 2368        }
 2369
 2370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2371
 2372        if reset {
 2373            let pointer_position = display_map
 2374                .buffer_snapshot
 2375                .anchor_before(position.to_point(&display_map));
 2376
 2377            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2378                s.clear_disjoint();
 2379                s.set_pending_anchor_range(
 2380                    pointer_position..pointer_position,
 2381                    SelectMode::Character,
 2382                );
 2383            });
 2384        }
 2385
 2386        let tail = self.selections.newest::<Point>(cx).tail();
 2387        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2388
 2389        if !reset {
 2390            self.select_columns(
 2391                tail.to_display_point(&display_map),
 2392                position,
 2393                goal_column,
 2394                &display_map,
 2395                window,
 2396                cx,
 2397            );
 2398        }
 2399    }
 2400
 2401    fn update_selection(
 2402        &mut self,
 2403        position: DisplayPoint,
 2404        goal_column: u32,
 2405        scroll_delta: gpui::Point<f32>,
 2406        window: &mut Window,
 2407        cx: &mut Context<Self>,
 2408    ) {
 2409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2410
 2411        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2412            let tail = tail.to_display_point(&display_map);
 2413            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2414        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2415            let buffer = self.buffer.read(cx).snapshot(cx);
 2416            let head;
 2417            let tail;
 2418            let mode = self.selections.pending_mode().unwrap();
 2419            match &mode {
 2420                SelectMode::Character => {
 2421                    head = position.to_point(&display_map);
 2422                    tail = pending.tail().to_point(&buffer);
 2423                }
 2424                SelectMode::Word(original_range) => {
 2425                    let original_display_range = original_range.start.to_display_point(&display_map)
 2426                        ..original_range.end.to_display_point(&display_map);
 2427                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2428                        ..original_display_range.end.to_point(&display_map);
 2429                    if movement::is_inside_word(&display_map, position)
 2430                        || original_display_range.contains(&position)
 2431                    {
 2432                        let word_range = movement::surrounding_word(&display_map, position);
 2433                        if word_range.start < original_display_range.start {
 2434                            head = word_range.start.to_point(&display_map);
 2435                        } else {
 2436                            head = word_range.end.to_point(&display_map);
 2437                        }
 2438                    } else {
 2439                        head = position.to_point(&display_map);
 2440                    }
 2441
 2442                    if head <= original_buffer_range.start {
 2443                        tail = original_buffer_range.end;
 2444                    } else {
 2445                        tail = original_buffer_range.start;
 2446                    }
 2447                }
 2448                SelectMode::Line(original_range) => {
 2449                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2450
 2451                    let position = display_map
 2452                        .clip_point(position, Bias::Left)
 2453                        .to_point(&display_map);
 2454                    let line_start = display_map.prev_line_boundary(position).0;
 2455                    let next_line_start = buffer.clip_point(
 2456                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2457                        Bias::Left,
 2458                    );
 2459
 2460                    if line_start < original_range.start {
 2461                        head = line_start
 2462                    } else {
 2463                        head = next_line_start
 2464                    }
 2465
 2466                    if head <= original_range.start {
 2467                        tail = original_range.end;
 2468                    } else {
 2469                        tail = original_range.start;
 2470                    }
 2471                }
 2472                SelectMode::All => {
 2473                    return;
 2474                }
 2475            };
 2476
 2477            if head < tail {
 2478                pending.start = buffer.anchor_before(head);
 2479                pending.end = buffer.anchor_before(tail);
 2480                pending.reversed = true;
 2481            } else {
 2482                pending.start = buffer.anchor_before(tail);
 2483                pending.end = buffer.anchor_before(head);
 2484                pending.reversed = false;
 2485            }
 2486
 2487            self.change_selections(None, window, cx, |s| {
 2488                s.set_pending(pending, mode);
 2489            });
 2490        } else {
 2491            log::error!("update_selection dispatched with no pending selection");
 2492            return;
 2493        }
 2494
 2495        self.apply_scroll_delta(scroll_delta, window, cx);
 2496        cx.notify();
 2497    }
 2498
 2499    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2500        self.columnar_selection_tail.take();
 2501        if self.selections.pending_anchor().is_some() {
 2502            let selections = self.selections.all::<usize>(cx);
 2503            self.change_selections(None, window, cx, |s| {
 2504                s.select(selections);
 2505                s.clear_pending();
 2506            });
 2507        }
 2508    }
 2509
 2510    fn select_columns(
 2511        &mut self,
 2512        tail: DisplayPoint,
 2513        head: DisplayPoint,
 2514        goal_column: u32,
 2515        display_map: &DisplaySnapshot,
 2516        window: &mut Window,
 2517        cx: &mut Context<Self>,
 2518    ) {
 2519        let start_row = cmp::min(tail.row(), head.row());
 2520        let end_row = cmp::max(tail.row(), head.row());
 2521        let start_column = cmp::min(tail.column(), goal_column);
 2522        let end_column = cmp::max(tail.column(), goal_column);
 2523        let reversed = start_column < tail.column();
 2524
 2525        let selection_ranges = (start_row.0..=end_row.0)
 2526            .map(DisplayRow)
 2527            .filter_map(|row| {
 2528                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2529                    let start = display_map
 2530                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2531                        .to_point(display_map);
 2532                    let end = display_map
 2533                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2534                        .to_point(display_map);
 2535                    if reversed {
 2536                        Some(end..start)
 2537                    } else {
 2538                        Some(start..end)
 2539                    }
 2540                } else {
 2541                    None
 2542                }
 2543            })
 2544            .collect::<Vec<_>>();
 2545
 2546        self.change_selections(None, window, cx, |s| {
 2547            s.select_ranges(selection_ranges);
 2548        });
 2549        cx.notify();
 2550    }
 2551
 2552    pub fn has_pending_nonempty_selection(&self) -> bool {
 2553        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2554            Some(Selection { start, end, .. }) => start != end,
 2555            None => false,
 2556        };
 2557
 2558        pending_nonempty_selection
 2559            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2560    }
 2561
 2562    pub fn has_pending_selection(&self) -> bool {
 2563        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2564    }
 2565
 2566    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2567        self.selection_mark_mode = false;
 2568
 2569        if self.clear_expanded_diff_hunks(cx) {
 2570            cx.notify();
 2571            return;
 2572        }
 2573        if self.dismiss_menus_and_popups(true, window, cx) {
 2574            return;
 2575        }
 2576
 2577        if self.mode == EditorMode::Full
 2578            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2579        {
 2580            return;
 2581        }
 2582
 2583        cx.propagate();
 2584    }
 2585
 2586    pub fn dismiss_menus_and_popups(
 2587        &mut self,
 2588        should_report_inline_completion_event: bool,
 2589        window: &mut Window,
 2590        cx: &mut Context<Self>,
 2591    ) -> bool {
 2592        if self.take_rename(false, window, cx).is_some() {
 2593            return true;
 2594        }
 2595
 2596        if hide_hover(self, cx) {
 2597            return true;
 2598        }
 2599
 2600        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2601            return true;
 2602        }
 2603
 2604        if self.hide_context_menu(window, cx).is_some() {
 2605            return true;
 2606        }
 2607
 2608        if self.mouse_context_menu.take().is_some() {
 2609            return true;
 2610        }
 2611
 2612        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2613            return true;
 2614        }
 2615
 2616        if self.snippet_stack.pop().is_some() {
 2617            return true;
 2618        }
 2619
 2620        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2621            self.dismiss_diagnostics(cx);
 2622            return true;
 2623        }
 2624
 2625        false
 2626    }
 2627
 2628    fn linked_editing_ranges_for(
 2629        &self,
 2630        selection: Range<text::Anchor>,
 2631        cx: &App,
 2632    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2633        if self.linked_edit_ranges.is_empty() {
 2634            return None;
 2635        }
 2636        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2637            selection.end.buffer_id.and_then(|end_buffer_id| {
 2638                if selection.start.buffer_id != Some(end_buffer_id) {
 2639                    return None;
 2640                }
 2641                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2642                let snapshot = buffer.read(cx).snapshot();
 2643                self.linked_edit_ranges
 2644                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2645                    .map(|ranges| (ranges, snapshot, buffer))
 2646            })?;
 2647        use text::ToOffset as TO;
 2648        // find offset from the start of current range to current cursor position
 2649        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2650
 2651        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2652        let start_difference = start_offset - start_byte_offset;
 2653        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2654        let end_difference = end_offset - start_byte_offset;
 2655        // Current range has associated linked ranges.
 2656        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2657        for range in linked_ranges.iter() {
 2658            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2659            let end_offset = start_offset + end_difference;
 2660            let start_offset = start_offset + start_difference;
 2661            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2662                continue;
 2663            }
 2664            if self.selections.disjoint_anchor_ranges().any(|s| {
 2665                if s.start.buffer_id != selection.start.buffer_id
 2666                    || s.end.buffer_id != selection.end.buffer_id
 2667                {
 2668                    return false;
 2669                }
 2670                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2671                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2672            }) {
 2673                continue;
 2674            }
 2675            let start = buffer_snapshot.anchor_after(start_offset);
 2676            let end = buffer_snapshot.anchor_after(end_offset);
 2677            linked_edits
 2678                .entry(buffer.clone())
 2679                .or_default()
 2680                .push(start..end);
 2681        }
 2682        Some(linked_edits)
 2683    }
 2684
 2685    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2686        let text: Arc<str> = text.into();
 2687
 2688        if self.read_only(cx) {
 2689            return;
 2690        }
 2691
 2692        let selections = self.selections.all_adjusted(cx);
 2693        let mut bracket_inserted = false;
 2694        let mut edits = Vec::new();
 2695        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2696        let mut new_selections = Vec::with_capacity(selections.len());
 2697        let mut new_autoclose_regions = Vec::new();
 2698        let snapshot = self.buffer.read(cx).read(cx);
 2699
 2700        for (selection, autoclose_region) in
 2701            self.selections_with_autoclose_regions(selections, &snapshot)
 2702        {
 2703            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2704                // Determine if the inserted text matches the opening or closing
 2705                // bracket of any of this language's bracket pairs.
 2706                let mut bracket_pair = None;
 2707                let mut is_bracket_pair_start = false;
 2708                let mut is_bracket_pair_end = false;
 2709                if !text.is_empty() {
 2710                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2711                    //  and they are removing the character that triggered IME popup.
 2712                    for (pair, enabled) in scope.brackets() {
 2713                        if !pair.close && !pair.surround {
 2714                            continue;
 2715                        }
 2716
 2717                        if enabled && pair.start.ends_with(text.as_ref()) {
 2718                            let prefix_len = pair.start.len() - text.len();
 2719                            let preceding_text_matches_prefix = prefix_len == 0
 2720                                || (selection.start.column >= (prefix_len as u32)
 2721                                    && snapshot.contains_str_at(
 2722                                        Point::new(
 2723                                            selection.start.row,
 2724                                            selection.start.column - (prefix_len as u32),
 2725                                        ),
 2726                                        &pair.start[..prefix_len],
 2727                                    ));
 2728                            if preceding_text_matches_prefix {
 2729                                bracket_pair = Some(pair.clone());
 2730                                is_bracket_pair_start = true;
 2731                                break;
 2732                            }
 2733                        }
 2734                        if pair.end.as_str() == text.as_ref() {
 2735                            bracket_pair = Some(pair.clone());
 2736                            is_bracket_pair_end = true;
 2737                            break;
 2738                        }
 2739                    }
 2740                }
 2741
 2742                if let Some(bracket_pair) = bracket_pair {
 2743                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2744                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2745                    let auto_surround =
 2746                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2747                    if selection.is_empty() {
 2748                        if is_bracket_pair_start {
 2749                            // If the inserted text is a suffix of an opening bracket and the
 2750                            // selection is preceded by the rest of the opening bracket, then
 2751                            // insert the closing bracket.
 2752                            let following_text_allows_autoclose = snapshot
 2753                                .chars_at(selection.start)
 2754                                .next()
 2755                                .map_or(true, |c| scope.should_autoclose_before(c));
 2756
 2757                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2758                                && bracket_pair.start.len() == 1
 2759                            {
 2760                                let target = bracket_pair.start.chars().next().unwrap();
 2761                                let current_line_count = snapshot
 2762                                    .reversed_chars_at(selection.start)
 2763                                    .take_while(|&c| c != '\n')
 2764                                    .filter(|&c| c == target)
 2765                                    .count();
 2766                                current_line_count % 2 == 1
 2767                            } else {
 2768                                false
 2769                            };
 2770
 2771                            if autoclose
 2772                                && bracket_pair.close
 2773                                && following_text_allows_autoclose
 2774                                && !is_closing_quote
 2775                            {
 2776                                let anchor = snapshot.anchor_before(selection.end);
 2777                                new_selections.push((selection.map(|_| anchor), text.len()));
 2778                                new_autoclose_regions.push((
 2779                                    anchor,
 2780                                    text.len(),
 2781                                    selection.id,
 2782                                    bracket_pair.clone(),
 2783                                ));
 2784                                edits.push((
 2785                                    selection.range(),
 2786                                    format!("{}{}", text, bracket_pair.end).into(),
 2787                                ));
 2788                                bracket_inserted = true;
 2789                                continue;
 2790                            }
 2791                        }
 2792
 2793                        if let Some(region) = autoclose_region {
 2794                            // If the selection is followed by an auto-inserted closing bracket,
 2795                            // then don't insert that closing bracket again; just move the selection
 2796                            // past the closing bracket.
 2797                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2798                                && text.as_ref() == region.pair.end.as_str();
 2799                            if should_skip {
 2800                                let anchor = snapshot.anchor_after(selection.end);
 2801                                new_selections
 2802                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2803                                continue;
 2804                            }
 2805                        }
 2806
 2807                        let always_treat_brackets_as_autoclosed = snapshot
 2808                            .settings_at(selection.start, cx)
 2809                            .always_treat_brackets_as_autoclosed;
 2810                        if always_treat_brackets_as_autoclosed
 2811                            && is_bracket_pair_end
 2812                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2813                        {
 2814                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2815                            // and the inserted text is a closing bracket and the selection is followed
 2816                            // by the closing bracket then move the selection past the closing bracket.
 2817                            let anchor = snapshot.anchor_after(selection.end);
 2818                            new_selections.push((selection.map(|_| anchor), text.len()));
 2819                            continue;
 2820                        }
 2821                    }
 2822                    // If an opening bracket is 1 character long and is typed while
 2823                    // text is selected, then surround that text with the bracket pair.
 2824                    else if auto_surround
 2825                        && bracket_pair.surround
 2826                        && is_bracket_pair_start
 2827                        && bracket_pair.start.chars().count() == 1
 2828                    {
 2829                        edits.push((selection.start..selection.start, text.clone()));
 2830                        edits.push((
 2831                            selection.end..selection.end,
 2832                            bracket_pair.end.as_str().into(),
 2833                        ));
 2834                        bracket_inserted = true;
 2835                        new_selections.push((
 2836                            Selection {
 2837                                id: selection.id,
 2838                                start: snapshot.anchor_after(selection.start),
 2839                                end: snapshot.anchor_before(selection.end),
 2840                                reversed: selection.reversed,
 2841                                goal: selection.goal,
 2842                            },
 2843                            0,
 2844                        ));
 2845                        continue;
 2846                    }
 2847                }
 2848            }
 2849
 2850            if self.auto_replace_emoji_shortcode
 2851                && selection.is_empty()
 2852                && text.as_ref().ends_with(':')
 2853            {
 2854                if let Some(possible_emoji_short_code) =
 2855                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2856                {
 2857                    if !possible_emoji_short_code.is_empty() {
 2858                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2859                            let emoji_shortcode_start = Point::new(
 2860                                selection.start.row,
 2861                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2862                            );
 2863
 2864                            // Remove shortcode from buffer
 2865                            edits.push((
 2866                                emoji_shortcode_start..selection.start,
 2867                                "".to_string().into(),
 2868                            ));
 2869                            new_selections.push((
 2870                                Selection {
 2871                                    id: selection.id,
 2872                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2873                                    end: snapshot.anchor_before(selection.start),
 2874                                    reversed: selection.reversed,
 2875                                    goal: selection.goal,
 2876                                },
 2877                                0,
 2878                            ));
 2879
 2880                            // Insert emoji
 2881                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2882                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2883                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2884
 2885                            continue;
 2886                        }
 2887                    }
 2888                }
 2889            }
 2890
 2891            // If not handling any auto-close operation, then just replace the selected
 2892            // text with the given input and move the selection to the end of the
 2893            // newly inserted text.
 2894            let anchor = snapshot.anchor_after(selection.end);
 2895            if !self.linked_edit_ranges.is_empty() {
 2896                let start_anchor = snapshot.anchor_before(selection.start);
 2897
 2898                let is_word_char = text.chars().next().map_or(true, |char| {
 2899                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2900                    classifier.is_word(char)
 2901                });
 2902
 2903                if is_word_char {
 2904                    if let Some(ranges) = self
 2905                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2906                    {
 2907                        for (buffer, edits) in ranges {
 2908                            linked_edits
 2909                                .entry(buffer.clone())
 2910                                .or_default()
 2911                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2912                        }
 2913                    }
 2914                }
 2915            }
 2916
 2917            new_selections.push((selection.map(|_| anchor), 0));
 2918            edits.push((selection.start..selection.end, text.clone()));
 2919        }
 2920
 2921        drop(snapshot);
 2922
 2923        self.transact(window, cx, |this, window, cx| {
 2924            this.buffer.update(cx, |buffer, cx| {
 2925                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2926            });
 2927            for (buffer, edits) in linked_edits {
 2928                buffer.update(cx, |buffer, cx| {
 2929                    let snapshot = buffer.snapshot();
 2930                    let edits = edits
 2931                        .into_iter()
 2932                        .map(|(range, text)| {
 2933                            use text::ToPoint as TP;
 2934                            let end_point = TP::to_point(&range.end, &snapshot);
 2935                            let start_point = TP::to_point(&range.start, &snapshot);
 2936                            (start_point..end_point, text)
 2937                        })
 2938                        .sorted_by_key(|(range, _)| range.start)
 2939                        .collect::<Vec<_>>();
 2940                    buffer.edit(edits, None, cx);
 2941                })
 2942            }
 2943            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2944            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2945            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2946            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2947                .zip(new_selection_deltas)
 2948                .map(|(selection, delta)| Selection {
 2949                    id: selection.id,
 2950                    start: selection.start + delta,
 2951                    end: selection.end + delta,
 2952                    reversed: selection.reversed,
 2953                    goal: SelectionGoal::None,
 2954                })
 2955                .collect::<Vec<_>>();
 2956
 2957            let mut i = 0;
 2958            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2959                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2960                let start = map.buffer_snapshot.anchor_before(position);
 2961                let end = map.buffer_snapshot.anchor_after(position);
 2962                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2963                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2964                        Ordering::Less => i += 1,
 2965                        Ordering::Greater => break,
 2966                        Ordering::Equal => {
 2967                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2968                                Ordering::Less => i += 1,
 2969                                Ordering::Equal => break,
 2970                                Ordering::Greater => break,
 2971                            }
 2972                        }
 2973                    }
 2974                }
 2975                this.autoclose_regions.insert(
 2976                    i,
 2977                    AutocloseRegion {
 2978                        selection_id,
 2979                        range: start..end,
 2980                        pair,
 2981                    },
 2982                );
 2983            }
 2984
 2985            let had_active_inline_completion = this.has_active_inline_completion();
 2986            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2987                s.select(new_selections)
 2988            });
 2989
 2990            if !bracket_inserted {
 2991                if let Some(on_type_format_task) =
 2992                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2993                {
 2994                    on_type_format_task.detach_and_log_err(cx);
 2995                }
 2996            }
 2997
 2998            let editor_settings = EditorSettings::get_global(cx);
 2999            if bracket_inserted
 3000                && (editor_settings.auto_signature_help
 3001                    || editor_settings.show_signature_help_after_edits)
 3002            {
 3003                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3004            }
 3005
 3006            let trigger_in_words =
 3007                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3008            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3009            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3010            this.refresh_inline_completion(true, false, window, cx);
 3011        });
 3012    }
 3013
 3014    fn find_possible_emoji_shortcode_at_position(
 3015        snapshot: &MultiBufferSnapshot,
 3016        position: Point,
 3017    ) -> Option<String> {
 3018        let mut chars = Vec::new();
 3019        let mut found_colon = false;
 3020        for char in snapshot.reversed_chars_at(position).take(100) {
 3021            // Found a possible emoji shortcode in the middle of the buffer
 3022            if found_colon {
 3023                if char.is_whitespace() {
 3024                    chars.reverse();
 3025                    return Some(chars.iter().collect());
 3026                }
 3027                // If the previous character is not a whitespace, we are in the middle of a word
 3028                // and we only want to complete the shortcode if the word is made up of other emojis
 3029                let mut containing_word = String::new();
 3030                for ch in snapshot
 3031                    .reversed_chars_at(position)
 3032                    .skip(chars.len() + 1)
 3033                    .take(100)
 3034                {
 3035                    if ch.is_whitespace() {
 3036                        break;
 3037                    }
 3038                    containing_word.push(ch);
 3039                }
 3040                let containing_word = containing_word.chars().rev().collect::<String>();
 3041                if util::word_consists_of_emojis(containing_word.as_str()) {
 3042                    chars.reverse();
 3043                    return Some(chars.iter().collect());
 3044                }
 3045            }
 3046
 3047            if char.is_whitespace() || !char.is_ascii() {
 3048                return None;
 3049            }
 3050            if char == ':' {
 3051                found_colon = true;
 3052            } else {
 3053                chars.push(char);
 3054            }
 3055        }
 3056        // Found a possible emoji shortcode at the beginning of the buffer
 3057        chars.reverse();
 3058        Some(chars.iter().collect())
 3059    }
 3060
 3061    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3062        self.transact(window, cx, |this, window, cx| {
 3063            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3064                let selections = this.selections.all::<usize>(cx);
 3065                let multi_buffer = this.buffer.read(cx);
 3066                let buffer = multi_buffer.snapshot(cx);
 3067                selections
 3068                    .iter()
 3069                    .map(|selection| {
 3070                        let start_point = selection.start.to_point(&buffer);
 3071                        let mut indent =
 3072                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3073                        indent.len = cmp::min(indent.len, start_point.column);
 3074                        let start = selection.start;
 3075                        let end = selection.end;
 3076                        let selection_is_empty = start == end;
 3077                        let language_scope = buffer.language_scope_at(start);
 3078                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3079                            &language_scope
 3080                        {
 3081                            let leading_whitespace_len = buffer
 3082                                .reversed_chars_at(start)
 3083                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3084                                .map(|c| c.len_utf8())
 3085                                .sum::<usize>();
 3086
 3087                            let trailing_whitespace_len = buffer
 3088                                .chars_at(end)
 3089                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3090                                .map(|c| c.len_utf8())
 3091                                .sum::<usize>();
 3092
 3093                            let insert_extra_newline =
 3094                                language.brackets().any(|(pair, enabled)| {
 3095                                    let pair_start = pair.start.trim_end();
 3096                                    let pair_end = pair.end.trim_start();
 3097
 3098                                    enabled
 3099                                        && pair.newline
 3100                                        && buffer.contains_str_at(
 3101                                            end + trailing_whitespace_len,
 3102                                            pair_end,
 3103                                        )
 3104                                        && buffer.contains_str_at(
 3105                                            (start - leading_whitespace_len)
 3106                                                .saturating_sub(pair_start.len()),
 3107                                            pair_start,
 3108                                        )
 3109                                });
 3110
 3111                            // Comment extension on newline is allowed only for cursor selections
 3112                            let comment_delimiter = maybe!({
 3113                                if !selection_is_empty {
 3114                                    return None;
 3115                                }
 3116
 3117                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3118                                    return None;
 3119                                }
 3120
 3121                                let delimiters = language.line_comment_prefixes();
 3122                                let max_len_of_delimiter =
 3123                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3124                                let (snapshot, range) =
 3125                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3126
 3127                                let mut index_of_first_non_whitespace = 0;
 3128                                let comment_candidate = snapshot
 3129                                    .chars_for_range(range)
 3130                                    .skip_while(|c| {
 3131                                        let should_skip = c.is_whitespace();
 3132                                        if should_skip {
 3133                                            index_of_first_non_whitespace += 1;
 3134                                        }
 3135                                        should_skip
 3136                                    })
 3137                                    .take(max_len_of_delimiter)
 3138                                    .collect::<String>();
 3139                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3140                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3141                                })?;
 3142                                let cursor_is_placed_after_comment_marker =
 3143                                    index_of_first_non_whitespace + comment_prefix.len()
 3144                                        <= start_point.column as usize;
 3145                                if cursor_is_placed_after_comment_marker {
 3146                                    Some(comment_prefix.clone())
 3147                                } else {
 3148                                    None
 3149                                }
 3150                            });
 3151                            (comment_delimiter, insert_extra_newline)
 3152                        } else {
 3153                            (None, false)
 3154                        };
 3155
 3156                        let capacity_for_delimiter = comment_delimiter
 3157                            .as_deref()
 3158                            .map(str::len)
 3159                            .unwrap_or_default();
 3160                        let mut new_text =
 3161                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3162                        new_text.push('\n');
 3163                        new_text.extend(indent.chars());
 3164                        if let Some(delimiter) = &comment_delimiter {
 3165                            new_text.push_str(delimiter);
 3166                        }
 3167                        if insert_extra_newline {
 3168                            new_text = new_text.repeat(2);
 3169                        }
 3170
 3171                        let anchor = buffer.anchor_after(end);
 3172                        let new_selection = selection.map(|_| anchor);
 3173                        (
 3174                            (start..end, new_text),
 3175                            (insert_extra_newline, new_selection),
 3176                        )
 3177                    })
 3178                    .unzip()
 3179            };
 3180
 3181            this.edit_with_autoindent(edits, cx);
 3182            let buffer = this.buffer.read(cx).snapshot(cx);
 3183            let new_selections = selection_fixup_info
 3184                .into_iter()
 3185                .map(|(extra_newline_inserted, new_selection)| {
 3186                    let mut cursor = new_selection.end.to_point(&buffer);
 3187                    if extra_newline_inserted {
 3188                        cursor.row -= 1;
 3189                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3190                    }
 3191                    new_selection.map(|_| cursor)
 3192                })
 3193                .collect();
 3194
 3195            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3196                s.select(new_selections)
 3197            });
 3198            this.refresh_inline_completion(true, false, window, cx);
 3199        });
 3200    }
 3201
 3202    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3203        let buffer = self.buffer.read(cx);
 3204        let snapshot = buffer.snapshot(cx);
 3205
 3206        let mut edits = Vec::new();
 3207        let mut rows = Vec::new();
 3208
 3209        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3210            let cursor = selection.head();
 3211            let row = cursor.row;
 3212
 3213            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3214
 3215            let newline = "\n".to_string();
 3216            edits.push((start_of_line..start_of_line, newline));
 3217
 3218            rows.push(row + rows_inserted as u32);
 3219        }
 3220
 3221        self.transact(window, cx, |editor, window, cx| {
 3222            editor.edit(edits, cx);
 3223
 3224            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3225                let mut index = 0;
 3226                s.move_cursors_with(|map, _, _| {
 3227                    let row = rows[index];
 3228                    index += 1;
 3229
 3230                    let point = Point::new(row, 0);
 3231                    let boundary = map.next_line_boundary(point).1;
 3232                    let clipped = map.clip_point(boundary, Bias::Left);
 3233
 3234                    (clipped, SelectionGoal::None)
 3235                });
 3236            });
 3237
 3238            let mut indent_edits = Vec::new();
 3239            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3240            for row in rows {
 3241                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3242                for (row, indent) in indents {
 3243                    if indent.len == 0 {
 3244                        continue;
 3245                    }
 3246
 3247                    let text = match indent.kind {
 3248                        IndentKind::Space => " ".repeat(indent.len as usize),
 3249                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3250                    };
 3251                    let point = Point::new(row.0, 0);
 3252                    indent_edits.push((point..point, text));
 3253                }
 3254            }
 3255            editor.edit(indent_edits, cx);
 3256        });
 3257    }
 3258
 3259    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3260        let buffer = self.buffer.read(cx);
 3261        let snapshot = buffer.snapshot(cx);
 3262
 3263        let mut edits = Vec::new();
 3264        let mut rows = Vec::new();
 3265        let mut rows_inserted = 0;
 3266
 3267        for selection in self.selections.all_adjusted(cx) {
 3268            let cursor = selection.head();
 3269            let row = cursor.row;
 3270
 3271            let point = Point::new(row + 1, 0);
 3272            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3273
 3274            let newline = "\n".to_string();
 3275            edits.push((start_of_line..start_of_line, newline));
 3276
 3277            rows_inserted += 1;
 3278            rows.push(row + rows_inserted);
 3279        }
 3280
 3281        self.transact(window, cx, |editor, window, cx| {
 3282            editor.edit(edits, cx);
 3283
 3284            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3285                let mut index = 0;
 3286                s.move_cursors_with(|map, _, _| {
 3287                    let row = rows[index];
 3288                    index += 1;
 3289
 3290                    let point = Point::new(row, 0);
 3291                    let boundary = map.next_line_boundary(point).1;
 3292                    let clipped = map.clip_point(boundary, Bias::Left);
 3293
 3294                    (clipped, SelectionGoal::None)
 3295                });
 3296            });
 3297
 3298            let mut indent_edits = Vec::new();
 3299            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3300            for row in rows {
 3301                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3302                for (row, indent) in indents {
 3303                    if indent.len == 0 {
 3304                        continue;
 3305                    }
 3306
 3307                    let text = match indent.kind {
 3308                        IndentKind::Space => " ".repeat(indent.len as usize),
 3309                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3310                    };
 3311                    let point = Point::new(row.0, 0);
 3312                    indent_edits.push((point..point, text));
 3313                }
 3314            }
 3315            editor.edit(indent_edits, cx);
 3316        });
 3317    }
 3318
 3319    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3320        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3321            original_indent_columns: Vec::new(),
 3322        });
 3323        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3324    }
 3325
 3326    fn insert_with_autoindent_mode(
 3327        &mut self,
 3328        text: &str,
 3329        autoindent_mode: Option<AutoindentMode>,
 3330        window: &mut Window,
 3331        cx: &mut Context<Self>,
 3332    ) {
 3333        if self.read_only(cx) {
 3334            return;
 3335        }
 3336
 3337        let text: Arc<str> = text.into();
 3338        self.transact(window, cx, |this, window, cx| {
 3339            let old_selections = this.selections.all_adjusted(cx);
 3340            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3341                let anchors = {
 3342                    let snapshot = buffer.read(cx);
 3343                    old_selections
 3344                        .iter()
 3345                        .map(|s| {
 3346                            let anchor = snapshot.anchor_after(s.head());
 3347                            s.map(|_| anchor)
 3348                        })
 3349                        .collect::<Vec<_>>()
 3350                };
 3351                buffer.edit(
 3352                    old_selections
 3353                        .iter()
 3354                        .map(|s| (s.start..s.end, text.clone())),
 3355                    autoindent_mode,
 3356                    cx,
 3357                );
 3358                anchors
 3359            });
 3360
 3361            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                s.select_anchors(selection_anchors);
 3363            });
 3364
 3365            cx.notify();
 3366        });
 3367    }
 3368
 3369    fn trigger_completion_on_input(
 3370        &mut self,
 3371        text: &str,
 3372        trigger_in_words: bool,
 3373        window: &mut Window,
 3374        cx: &mut Context<Self>,
 3375    ) {
 3376        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3377            self.show_completions(
 3378                &ShowCompletions {
 3379                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3380                },
 3381                window,
 3382                cx,
 3383            );
 3384        } else {
 3385            self.hide_context_menu(window, cx);
 3386        }
 3387    }
 3388
 3389    fn is_completion_trigger(
 3390        &self,
 3391        text: &str,
 3392        trigger_in_words: bool,
 3393        cx: &mut Context<Self>,
 3394    ) -> bool {
 3395        let position = self.selections.newest_anchor().head();
 3396        let multibuffer = self.buffer.read(cx);
 3397        let Some(buffer) = position
 3398            .buffer_id
 3399            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3400        else {
 3401            return false;
 3402        };
 3403
 3404        if let Some(completion_provider) = &self.completion_provider {
 3405            completion_provider.is_completion_trigger(
 3406                &buffer,
 3407                position.text_anchor,
 3408                text,
 3409                trigger_in_words,
 3410                cx,
 3411            )
 3412        } else {
 3413            false
 3414        }
 3415    }
 3416
 3417    /// If any empty selections is touching the start of its innermost containing autoclose
 3418    /// region, expand it to select the brackets.
 3419    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3420        let selections = self.selections.all::<usize>(cx);
 3421        let buffer = self.buffer.read(cx).read(cx);
 3422        let new_selections = self
 3423            .selections_with_autoclose_regions(selections, &buffer)
 3424            .map(|(mut selection, region)| {
 3425                if !selection.is_empty() {
 3426                    return selection;
 3427                }
 3428
 3429                if let Some(region) = region {
 3430                    let mut range = region.range.to_offset(&buffer);
 3431                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3432                        range.start -= region.pair.start.len();
 3433                        if buffer.contains_str_at(range.start, &region.pair.start)
 3434                            && buffer.contains_str_at(range.end, &region.pair.end)
 3435                        {
 3436                            range.end += region.pair.end.len();
 3437                            selection.start = range.start;
 3438                            selection.end = range.end;
 3439
 3440                            return selection;
 3441                        }
 3442                    }
 3443                }
 3444
 3445                let always_treat_brackets_as_autoclosed = buffer
 3446                    .settings_at(selection.start, cx)
 3447                    .always_treat_brackets_as_autoclosed;
 3448
 3449                if !always_treat_brackets_as_autoclosed {
 3450                    return selection;
 3451                }
 3452
 3453                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3454                    for (pair, enabled) in scope.brackets() {
 3455                        if !enabled || !pair.close {
 3456                            continue;
 3457                        }
 3458
 3459                        if buffer.contains_str_at(selection.start, &pair.end) {
 3460                            let pair_start_len = pair.start.len();
 3461                            if buffer.contains_str_at(
 3462                                selection.start.saturating_sub(pair_start_len),
 3463                                &pair.start,
 3464                            ) {
 3465                                selection.start -= pair_start_len;
 3466                                selection.end += pair.end.len();
 3467
 3468                                return selection;
 3469                            }
 3470                        }
 3471                    }
 3472                }
 3473
 3474                selection
 3475            })
 3476            .collect();
 3477
 3478        drop(buffer);
 3479        self.change_selections(None, window, cx, |selections| {
 3480            selections.select(new_selections)
 3481        });
 3482    }
 3483
 3484    /// Iterate the given selections, and for each one, find the smallest surrounding
 3485    /// autoclose region. This uses the ordering of the selections and the autoclose
 3486    /// regions to avoid repeated comparisons.
 3487    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3488        &'a self,
 3489        selections: impl IntoIterator<Item = Selection<D>>,
 3490        buffer: &'a MultiBufferSnapshot,
 3491    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3492        let mut i = 0;
 3493        let mut regions = self.autoclose_regions.as_slice();
 3494        selections.into_iter().map(move |selection| {
 3495            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3496
 3497            let mut enclosing = None;
 3498            while let Some(pair_state) = regions.get(i) {
 3499                if pair_state.range.end.to_offset(buffer) < range.start {
 3500                    regions = &regions[i + 1..];
 3501                    i = 0;
 3502                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3503                    break;
 3504                } else {
 3505                    if pair_state.selection_id == selection.id {
 3506                        enclosing = Some(pair_state);
 3507                    }
 3508                    i += 1;
 3509                }
 3510            }
 3511
 3512            (selection, enclosing)
 3513        })
 3514    }
 3515
 3516    /// Remove any autoclose regions that no longer contain their selection.
 3517    fn invalidate_autoclose_regions(
 3518        &mut self,
 3519        mut selections: &[Selection<Anchor>],
 3520        buffer: &MultiBufferSnapshot,
 3521    ) {
 3522        self.autoclose_regions.retain(|state| {
 3523            let mut i = 0;
 3524            while let Some(selection) = selections.get(i) {
 3525                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3526                    selections = &selections[1..];
 3527                    continue;
 3528                }
 3529                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3530                    break;
 3531                }
 3532                if selection.id == state.selection_id {
 3533                    return true;
 3534                } else {
 3535                    i += 1;
 3536                }
 3537            }
 3538            false
 3539        });
 3540    }
 3541
 3542    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3543        let offset = position.to_offset(buffer);
 3544        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3545        if offset > word_range.start && kind == Some(CharKind::Word) {
 3546            Some(
 3547                buffer
 3548                    .text_for_range(word_range.start..offset)
 3549                    .collect::<String>(),
 3550            )
 3551        } else {
 3552            None
 3553        }
 3554    }
 3555
 3556    pub fn toggle_inlay_hints(
 3557        &mut self,
 3558        _: &ToggleInlayHints,
 3559        _: &mut Window,
 3560        cx: &mut Context<Self>,
 3561    ) {
 3562        self.refresh_inlay_hints(
 3563            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3564            cx,
 3565        );
 3566    }
 3567
 3568    pub fn inlay_hints_enabled(&self) -> bool {
 3569        self.inlay_hint_cache.enabled
 3570    }
 3571
 3572    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3573        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3574            return;
 3575        }
 3576
 3577        let reason_description = reason.description();
 3578        let ignore_debounce = matches!(
 3579            reason,
 3580            InlayHintRefreshReason::SettingsChange(_)
 3581                | InlayHintRefreshReason::Toggle(_)
 3582                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3583        );
 3584        let (invalidate_cache, required_languages) = match reason {
 3585            InlayHintRefreshReason::Toggle(enabled) => {
 3586                self.inlay_hint_cache.enabled = enabled;
 3587                if enabled {
 3588                    (InvalidationStrategy::RefreshRequested, None)
 3589                } else {
 3590                    self.inlay_hint_cache.clear();
 3591                    self.splice_inlays(
 3592                        &self
 3593                            .visible_inlay_hints(cx)
 3594                            .iter()
 3595                            .map(|inlay| inlay.id)
 3596                            .collect::<Vec<InlayId>>(),
 3597                        Vec::new(),
 3598                        cx,
 3599                    );
 3600                    return;
 3601                }
 3602            }
 3603            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3604                match self.inlay_hint_cache.update_settings(
 3605                    &self.buffer,
 3606                    new_settings,
 3607                    self.visible_inlay_hints(cx),
 3608                    cx,
 3609                ) {
 3610                    ControlFlow::Break(Some(InlaySplice {
 3611                        to_remove,
 3612                        to_insert,
 3613                    })) => {
 3614                        self.splice_inlays(&to_remove, to_insert, cx);
 3615                        return;
 3616                    }
 3617                    ControlFlow::Break(None) => return,
 3618                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3619                }
 3620            }
 3621            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3622                if let Some(InlaySplice {
 3623                    to_remove,
 3624                    to_insert,
 3625                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3626                {
 3627                    self.splice_inlays(&to_remove, to_insert, cx);
 3628                }
 3629                return;
 3630            }
 3631            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3632            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3633                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3634            }
 3635            InlayHintRefreshReason::RefreshRequested => {
 3636                (InvalidationStrategy::RefreshRequested, None)
 3637            }
 3638        };
 3639
 3640        if let Some(InlaySplice {
 3641            to_remove,
 3642            to_insert,
 3643        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3644            reason_description,
 3645            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3646            invalidate_cache,
 3647            ignore_debounce,
 3648            cx,
 3649        ) {
 3650            self.splice_inlays(&to_remove, to_insert, cx);
 3651        }
 3652    }
 3653
 3654    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3655        self.display_map
 3656            .read(cx)
 3657            .current_inlays()
 3658            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3659            .cloned()
 3660            .collect()
 3661    }
 3662
 3663    pub fn excerpts_for_inlay_hints_query(
 3664        &self,
 3665        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3666        cx: &mut Context<Editor>,
 3667    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3668        let Some(project) = self.project.as_ref() else {
 3669            return HashMap::default();
 3670        };
 3671        let project = project.read(cx);
 3672        let multi_buffer = self.buffer().read(cx);
 3673        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3674        let multi_buffer_visible_start = self
 3675            .scroll_manager
 3676            .anchor()
 3677            .anchor
 3678            .to_point(&multi_buffer_snapshot);
 3679        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3680            multi_buffer_visible_start
 3681                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3682            Bias::Left,
 3683        );
 3684        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3685        multi_buffer_snapshot
 3686            .range_to_buffer_ranges(multi_buffer_visible_range)
 3687            .into_iter()
 3688            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3689            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3690                let buffer_file = project::File::from_dyn(buffer.file())?;
 3691                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3692                let worktree_entry = buffer_worktree
 3693                    .read(cx)
 3694                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3695                if worktree_entry.is_ignored {
 3696                    return None;
 3697                }
 3698
 3699                let language = buffer.language()?;
 3700                if let Some(restrict_to_languages) = restrict_to_languages {
 3701                    if !restrict_to_languages.contains(language) {
 3702                        return None;
 3703                    }
 3704                }
 3705                Some((
 3706                    excerpt_id,
 3707                    (
 3708                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3709                        buffer.version().clone(),
 3710                        excerpt_visible_range,
 3711                    ),
 3712                ))
 3713            })
 3714            .collect()
 3715    }
 3716
 3717    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3718        TextLayoutDetails {
 3719            text_system: window.text_system().clone(),
 3720            editor_style: self.style.clone().unwrap(),
 3721            rem_size: window.rem_size(),
 3722            scroll_anchor: self.scroll_manager.anchor(),
 3723            visible_rows: self.visible_line_count(),
 3724            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3725        }
 3726    }
 3727
 3728    pub fn splice_inlays(
 3729        &self,
 3730        to_remove: &[InlayId],
 3731        to_insert: Vec<Inlay>,
 3732        cx: &mut Context<Self>,
 3733    ) {
 3734        self.display_map.update(cx, |display_map, cx| {
 3735            display_map.splice_inlays(to_remove, to_insert, cx)
 3736        });
 3737        cx.notify();
 3738    }
 3739
 3740    fn trigger_on_type_formatting(
 3741        &self,
 3742        input: String,
 3743        window: &mut Window,
 3744        cx: &mut Context<Self>,
 3745    ) -> Option<Task<Result<()>>> {
 3746        if input.len() != 1 {
 3747            return None;
 3748        }
 3749
 3750        let project = self.project.as_ref()?;
 3751        let position = self.selections.newest_anchor().head();
 3752        let (buffer, buffer_position) = self
 3753            .buffer
 3754            .read(cx)
 3755            .text_anchor_for_position(position, cx)?;
 3756
 3757        let settings = language_settings::language_settings(
 3758            buffer
 3759                .read(cx)
 3760                .language_at(buffer_position)
 3761                .map(|l| l.name()),
 3762            buffer.read(cx).file(),
 3763            cx,
 3764        );
 3765        if !settings.use_on_type_format {
 3766            return None;
 3767        }
 3768
 3769        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3770        // hence we do LSP request & edit on host side only — add formats to host's history.
 3771        let push_to_lsp_host_history = true;
 3772        // If this is not the host, append its history with new edits.
 3773        let push_to_client_history = project.read(cx).is_via_collab();
 3774
 3775        let on_type_formatting = project.update(cx, |project, cx| {
 3776            project.on_type_format(
 3777                buffer.clone(),
 3778                buffer_position,
 3779                input,
 3780                push_to_lsp_host_history,
 3781                cx,
 3782            )
 3783        });
 3784        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3785            if let Some(transaction) = on_type_formatting.await? {
 3786                if push_to_client_history {
 3787                    buffer
 3788                        .update(&mut cx, |buffer, _| {
 3789                            buffer.push_transaction(transaction, Instant::now());
 3790                        })
 3791                        .ok();
 3792                }
 3793                editor.update(&mut cx, |editor, cx| {
 3794                    editor.refresh_document_highlights(cx);
 3795                })?;
 3796            }
 3797            Ok(())
 3798        }))
 3799    }
 3800
 3801    pub fn show_completions(
 3802        &mut self,
 3803        options: &ShowCompletions,
 3804        window: &mut Window,
 3805        cx: &mut Context<Self>,
 3806    ) {
 3807        if self.pending_rename.is_some() {
 3808            return;
 3809        }
 3810
 3811        let Some(provider) = self.completion_provider.as_ref() else {
 3812            return;
 3813        };
 3814
 3815        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3816            return;
 3817        }
 3818
 3819        let position = self.selections.newest_anchor().head();
 3820        if position.diff_base_anchor.is_some() {
 3821            return;
 3822        }
 3823        let (buffer, buffer_position) =
 3824            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3825                output
 3826            } else {
 3827                return;
 3828            };
 3829        let show_completion_documentation = buffer
 3830            .read(cx)
 3831            .snapshot()
 3832            .settings_at(buffer_position, cx)
 3833            .show_completion_documentation;
 3834
 3835        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3836
 3837        let trigger_kind = match &options.trigger {
 3838            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3839                CompletionTriggerKind::TRIGGER_CHARACTER
 3840            }
 3841            _ => CompletionTriggerKind::INVOKED,
 3842        };
 3843        let completion_context = CompletionContext {
 3844            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3845                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3846                    Some(String::from(trigger))
 3847                } else {
 3848                    None
 3849                }
 3850            }),
 3851            trigger_kind,
 3852        };
 3853        let completions =
 3854            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3855        let sort_completions = provider.sort_completions();
 3856
 3857        let id = post_inc(&mut self.next_completion_id);
 3858        let task = cx.spawn_in(window, |editor, mut cx| {
 3859            async move {
 3860                editor.update(&mut cx, |this, _| {
 3861                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3862                })?;
 3863                let completions = completions.await.log_err();
 3864                let menu = if let Some(completions) = completions {
 3865                    let mut menu = CompletionsMenu::new(
 3866                        id,
 3867                        sort_completions,
 3868                        show_completion_documentation,
 3869                        position,
 3870                        buffer.clone(),
 3871                        completions.into(),
 3872                    );
 3873
 3874                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3875                        .await;
 3876
 3877                    menu.visible().then_some(menu)
 3878                } else {
 3879                    None
 3880                };
 3881
 3882                editor.update_in(&mut cx, |editor, window, cx| {
 3883                    match editor.context_menu.borrow().as_ref() {
 3884                        None => {}
 3885                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3886                            if prev_menu.id > id {
 3887                                return;
 3888                            }
 3889                        }
 3890                        _ => return,
 3891                    }
 3892
 3893                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3894                        let mut menu = menu.unwrap();
 3895                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3896
 3897                        *editor.context_menu.borrow_mut() =
 3898                            Some(CodeContextMenu::Completions(menu));
 3899
 3900                        if editor.show_inline_completions_in_menu(cx) {
 3901                            editor.update_visible_inline_completion(window, cx);
 3902                        } else {
 3903                            editor.discard_inline_completion(false, cx);
 3904                        }
 3905
 3906                        cx.notify();
 3907                    } else if editor.completion_tasks.len() <= 1 {
 3908                        // If there are no more completion tasks and the last menu was
 3909                        // empty, we should hide it.
 3910                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3911                        // If it was already hidden and we don't show inline
 3912                        // completions in the menu, we should also show the
 3913                        // inline-completion when available.
 3914                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3915                            editor.update_visible_inline_completion(window, cx);
 3916                        }
 3917                    }
 3918                })?;
 3919
 3920                Ok::<_, anyhow::Error>(())
 3921            }
 3922            .log_err()
 3923        });
 3924
 3925        self.completion_tasks.push((id, task));
 3926    }
 3927
 3928    pub fn confirm_completion(
 3929        &mut self,
 3930        action: &ConfirmCompletion,
 3931        window: &mut Window,
 3932        cx: &mut Context<Self>,
 3933    ) -> Option<Task<Result<()>>> {
 3934        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3935    }
 3936
 3937    pub fn compose_completion(
 3938        &mut self,
 3939        action: &ComposeCompletion,
 3940        window: &mut Window,
 3941        cx: &mut Context<Self>,
 3942    ) -> Option<Task<Result<()>>> {
 3943        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3944    }
 3945
 3946    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3947        window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
 3948    }
 3949
 3950    fn do_completion(
 3951        &mut self,
 3952        item_ix: Option<usize>,
 3953        intent: CompletionIntent,
 3954        window: &mut Window,
 3955        cx: &mut Context<Editor>,
 3956    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3957        use language::ToOffset as _;
 3958
 3959        let completions_menu =
 3960            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3961                menu
 3962            } else {
 3963                return None;
 3964            };
 3965
 3966        let entries = completions_menu.entries.borrow();
 3967        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3968        if self.show_inline_completions_in_menu(cx) {
 3969            self.discard_inline_completion(true, cx);
 3970        }
 3971        let candidate_id = mat.candidate_id;
 3972        drop(entries);
 3973
 3974        let buffer_handle = completions_menu.buffer;
 3975        let completion = completions_menu
 3976            .completions
 3977            .borrow()
 3978            .get(candidate_id)?
 3979            .clone();
 3980        cx.stop_propagation();
 3981
 3982        let snippet;
 3983        let text;
 3984
 3985        if completion.is_snippet() {
 3986            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3987            text = snippet.as_ref().unwrap().text.clone();
 3988        } else {
 3989            snippet = None;
 3990            text = completion.new_text.clone();
 3991        };
 3992        let selections = self.selections.all::<usize>(cx);
 3993        let buffer = buffer_handle.read(cx);
 3994        let old_range = completion.old_range.to_offset(buffer);
 3995        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3996
 3997        let newest_selection = self.selections.newest_anchor();
 3998        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3999            return None;
 4000        }
 4001
 4002        let lookbehind = newest_selection
 4003            .start
 4004            .text_anchor
 4005            .to_offset(buffer)
 4006            .saturating_sub(old_range.start);
 4007        let lookahead = old_range
 4008            .end
 4009            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4010        let mut common_prefix_len = old_text
 4011            .bytes()
 4012            .zip(text.bytes())
 4013            .take_while(|(a, b)| a == b)
 4014            .count();
 4015
 4016        let snapshot = self.buffer.read(cx).snapshot(cx);
 4017        let mut range_to_replace: Option<Range<isize>> = None;
 4018        let mut ranges = Vec::new();
 4019        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4020        for selection in &selections {
 4021            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4022                let start = selection.start.saturating_sub(lookbehind);
 4023                let end = selection.end + lookahead;
 4024                if selection.id == newest_selection.id {
 4025                    range_to_replace = Some(
 4026                        ((start + common_prefix_len) as isize - selection.start as isize)
 4027                            ..(end as isize - selection.start as isize),
 4028                    );
 4029                }
 4030                ranges.push(start + common_prefix_len..end);
 4031            } else {
 4032                common_prefix_len = 0;
 4033                ranges.clear();
 4034                ranges.extend(selections.iter().map(|s| {
 4035                    if s.id == newest_selection.id {
 4036                        range_to_replace = Some(
 4037                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4038                                - selection.start as isize
 4039                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4040                                    - selection.start as isize,
 4041                        );
 4042                        old_range.clone()
 4043                    } else {
 4044                        s.start..s.end
 4045                    }
 4046                }));
 4047                break;
 4048            }
 4049            if !self.linked_edit_ranges.is_empty() {
 4050                let start_anchor = snapshot.anchor_before(selection.head());
 4051                let end_anchor = snapshot.anchor_after(selection.tail());
 4052                if let Some(ranges) = self
 4053                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4054                {
 4055                    for (buffer, edits) in ranges {
 4056                        linked_edits.entry(buffer.clone()).or_default().extend(
 4057                            edits
 4058                                .into_iter()
 4059                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4060                        );
 4061                    }
 4062                }
 4063            }
 4064        }
 4065        let text = &text[common_prefix_len..];
 4066
 4067        cx.emit(EditorEvent::InputHandled {
 4068            utf16_range_to_replace: range_to_replace,
 4069            text: text.into(),
 4070        });
 4071
 4072        self.transact(window, cx, |this, window, cx| {
 4073            if let Some(mut snippet) = snippet {
 4074                snippet.text = text.to_string();
 4075                for tabstop in snippet
 4076                    .tabstops
 4077                    .iter_mut()
 4078                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4079                {
 4080                    tabstop.start -= common_prefix_len as isize;
 4081                    tabstop.end -= common_prefix_len as isize;
 4082                }
 4083
 4084                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4085            } else {
 4086                this.buffer.update(cx, |buffer, cx| {
 4087                    buffer.edit(
 4088                        ranges.iter().map(|range| (range.clone(), text)),
 4089                        this.autoindent_mode.clone(),
 4090                        cx,
 4091                    );
 4092                });
 4093            }
 4094            for (buffer, edits) in linked_edits {
 4095                buffer.update(cx, |buffer, cx| {
 4096                    let snapshot = buffer.snapshot();
 4097                    let edits = edits
 4098                        .into_iter()
 4099                        .map(|(range, text)| {
 4100                            use text::ToPoint as TP;
 4101                            let end_point = TP::to_point(&range.end, &snapshot);
 4102                            let start_point = TP::to_point(&range.start, &snapshot);
 4103                            (start_point..end_point, text)
 4104                        })
 4105                        .sorted_by_key(|(range, _)| range.start)
 4106                        .collect::<Vec<_>>();
 4107                    buffer.edit(edits, None, cx);
 4108                })
 4109            }
 4110
 4111            this.refresh_inline_completion(true, false, window, cx);
 4112        });
 4113
 4114        let show_new_completions_on_confirm = completion
 4115            .confirm
 4116            .as_ref()
 4117            .map_or(false, |confirm| confirm(intent, window, cx));
 4118        if show_new_completions_on_confirm {
 4119            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4120        }
 4121
 4122        let provider = self.completion_provider.as_ref()?;
 4123        drop(completion);
 4124        let apply_edits = provider.apply_additional_edits_for_completion(
 4125            buffer_handle,
 4126            completions_menu.completions.clone(),
 4127            candidate_id,
 4128            true,
 4129            cx,
 4130        );
 4131
 4132        let editor_settings = EditorSettings::get_global(cx);
 4133        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4134            // After the code completion is finished, users often want to know what signatures are needed.
 4135            // so we should automatically call signature_help
 4136            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4137        }
 4138
 4139        Some(cx.foreground_executor().spawn(async move {
 4140            apply_edits.await?;
 4141            Ok(())
 4142        }))
 4143    }
 4144
 4145    pub fn toggle_code_actions(
 4146        &mut self,
 4147        action: &ToggleCodeActions,
 4148        window: &mut Window,
 4149        cx: &mut Context<Self>,
 4150    ) {
 4151        let mut context_menu = self.context_menu.borrow_mut();
 4152        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4153            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4154                // Toggle if we're selecting the same one
 4155                *context_menu = None;
 4156                cx.notify();
 4157                return;
 4158            } else {
 4159                // Otherwise, clear it and start a new one
 4160                *context_menu = None;
 4161                cx.notify();
 4162            }
 4163        }
 4164        drop(context_menu);
 4165        let snapshot = self.snapshot(window, cx);
 4166        let deployed_from_indicator = action.deployed_from_indicator;
 4167        let mut task = self.code_actions_task.take();
 4168        let action = action.clone();
 4169        cx.spawn_in(window, |editor, mut cx| async move {
 4170            while let Some(prev_task) = task {
 4171                prev_task.await.log_err();
 4172                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4173            }
 4174
 4175            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4176                if editor.focus_handle.is_focused(window) {
 4177                    let multibuffer_point = action
 4178                        .deployed_from_indicator
 4179                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4180                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4181                    let (buffer, buffer_row) = snapshot
 4182                        .buffer_snapshot
 4183                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4184                        .and_then(|(buffer_snapshot, range)| {
 4185                            editor
 4186                                .buffer
 4187                                .read(cx)
 4188                                .buffer(buffer_snapshot.remote_id())
 4189                                .map(|buffer| (buffer, range.start.row))
 4190                        })?;
 4191                    let (_, code_actions) = editor
 4192                        .available_code_actions
 4193                        .clone()
 4194                        .and_then(|(location, code_actions)| {
 4195                            let snapshot = location.buffer.read(cx).snapshot();
 4196                            let point_range = location.range.to_point(&snapshot);
 4197                            let point_range = point_range.start.row..=point_range.end.row;
 4198                            if point_range.contains(&buffer_row) {
 4199                                Some((location, code_actions))
 4200                            } else {
 4201                                None
 4202                            }
 4203                        })
 4204                        .unzip();
 4205                    let buffer_id = buffer.read(cx).remote_id();
 4206                    let tasks = editor
 4207                        .tasks
 4208                        .get(&(buffer_id, buffer_row))
 4209                        .map(|t| Arc::new(t.to_owned()));
 4210                    if tasks.is_none() && code_actions.is_none() {
 4211                        return None;
 4212                    }
 4213
 4214                    editor.completion_tasks.clear();
 4215                    editor.discard_inline_completion(false, cx);
 4216                    let task_context =
 4217                        tasks
 4218                            .as_ref()
 4219                            .zip(editor.project.clone())
 4220                            .map(|(tasks, project)| {
 4221                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4222                            });
 4223
 4224                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4225                        let task_context = match task_context {
 4226                            Some(task_context) => task_context.await,
 4227                            None => None,
 4228                        };
 4229                        let resolved_tasks =
 4230                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4231                                Rc::new(ResolvedTasks {
 4232                                    templates: tasks.resolve(&task_context).collect(),
 4233                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4234                                        multibuffer_point.row,
 4235                                        tasks.column,
 4236                                    )),
 4237                                })
 4238                            });
 4239                        let spawn_straight_away = resolved_tasks
 4240                            .as_ref()
 4241                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4242                            && code_actions
 4243                                .as_ref()
 4244                                .map_or(true, |actions| actions.is_empty());
 4245                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4246                            *editor.context_menu.borrow_mut() =
 4247                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4248                                    buffer,
 4249                                    actions: CodeActionContents {
 4250                                        tasks: resolved_tasks,
 4251                                        actions: code_actions,
 4252                                    },
 4253                                    selected_item: Default::default(),
 4254                                    scroll_handle: UniformListScrollHandle::default(),
 4255                                    deployed_from_indicator,
 4256                                }));
 4257                            if spawn_straight_away {
 4258                                if let Some(task) = editor.confirm_code_action(
 4259                                    &ConfirmCodeAction { item_ix: Some(0) },
 4260                                    window,
 4261                                    cx,
 4262                                ) {
 4263                                    cx.notify();
 4264                                    return task;
 4265                                }
 4266                            }
 4267                            cx.notify();
 4268                            Task::ready(Ok(()))
 4269                        }) {
 4270                            task.await
 4271                        } else {
 4272                            Ok(())
 4273                        }
 4274                    }))
 4275                } else {
 4276                    Some(Task::ready(Ok(())))
 4277                }
 4278            })?;
 4279            if let Some(task) = spawned_test_task {
 4280                task.await?;
 4281            }
 4282
 4283            Ok::<_, anyhow::Error>(())
 4284        })
 4285        .detach_and_log_err(cx);
 4286    }
 4287
 4288    pub fn confirm_code_action(
 4289        &mut self,
 4290        action: &ConfirmCodeAction,
 4291        window: &mut Window,
 4292        cx: &mut Context<Self>,
 4293    ) -> Option<Task<Result<()>>> {
 4294        let actions_menu =
 4295            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4296                menu
 4297            } else {
 4298                return None;
 4299            };
 4300        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4301        let action = actions_menu.actions.get(action_ix)?;
 4302        let title = action.label();
 4303        let buffer = actions_menu.buffer;
 4304        let workspace = self.workspace()?;
 4305
 4306        match action {
 4307            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4308                workspace.update(cx, |workspace, cx| {
 4309                    workspace::tasks::schedule_resolved_task(
 4310                        workspace,
 4311                        task_source_kind,
 4312                        resolved_task,
 4313                        false,
 4314                        cx,
 4315                    );
 4316
 4317                    Some(Task::ready(Ok(())))
 4318                })
 4319            }
 4320            CodeActionsItem::CodeAction {
 4321                excerpt_id,
 4322                action,
 4323                provider,
 4324            } => {
 4325                let apply_code_action =
 4326                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4327                let workspace = workspace.downgrade();
 4328                Some(cx.spawn_in(window, |editor, cx| async move {
 4329                    let project_transaction = apply_code_action.await?;
 4330                    Self::open_project_transaction(
 4331                        &editor,
 4332                        workspace,
 4333                        project_transaction,
 4334                        title,
 4335                        cx,
 4336                    )
 4337                    .await
 4338                }))
 4339            }
 4340        }
 4341    }
 4342
 4343    pub async fn open_project_transaction(
 4344        this: &WeakEntity<Editor>,
 4345        workspace: WeakEntity<Workspace>,
 4346        transaction: ProjectTransaction,
 4347        title: String,
 4348        mut cx: AsyncWindowContext,
 4349    ) -> Result<()> {
 4350        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4351        cx.update(|_, cx| {
 4352            entries.sort_unstable_by_key(|(buffer, _)| {
 4353                buffer.read(cx).file().map(|f| f.path().clone())
 4354            });
 4355        })?;
 4356
 4357        // If the project transaction's edits are all contained within this editor, then
 4358        // avoid opening a new editor to display them.
 4359
 4360        if let Some((buffer, transaction)) = entries.first() {
 4361            if entries.len() == 1 {
 4362                let excerpt = this.update(&mut cx, |editor, cx| {
 4363                    editor
 4364                        .buffer()
 4365                        .read(cx)
 4366                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4367                })?;
 4368                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4369                    if excerpted_buffer == *buffer {
 4370                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4371                            let excerpt_range = excerpt_range.to_offset(buffer);
 4372                            buffer
 4373                                .edited_ranges_for_transaction::<usize>(transaction)
 4374                                .all(|range| {
 4375                                    excerpt_range.start <= range.start
 4376                                        && excerpt_range.end >= range.end
 4377                                })
 4378                        })?;
 4379
 4380                        if all_edits_within_excerpt {
 4381                            return Ok(());
 4382                        }
 4383                    }
 4384                }
 4385            }
 4386        } else {
 4387            return Ok(());
 4388        }
 4389
 4390        let mut ranges_to_highlight = Vec::new();
 4391        let excerpt_buffer = cx.new(|cx| {
 4392            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4393            for (buffer_handle, transaction) in &entries {
 4394                let buffer = buffer_handle.read(cx);
 4395                ranges_to_highlight.extend(
 4396                    multibuffer.push_excerpts_with_context_lines(
 4397                        buffer_handle.clone(),
 4398                        buffer
 4399                            .edited_ranges_for_transaction::<usize>(transaction)
 4400                            .collect(),
 4401                        DEFAULT_MULTIBUFFER_CONTEXT,
 4402                        cx,
 4403                    ),
 4404                );
 4405            }
 4406            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4407            multibuffer
 4408        })?;
 4409
 4410        workspace.update_in(&mut cx, |workspace, window, cx| {
 4411            let project = workspace.project().clone();
 4412            let editor = cx
 4413                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4414            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4415            editor.update(cx, |editor, cx| {
 4416                editor.highlight_background::<Self>(
 4417                    &ranges_to_highlight,
 4418                    |theme| theme.editor_highlighted_line_background,
 4419                    cx,
 4420                );
 4421            });
 4422        })?;
 4423
 4424        Ok(())
 4425    }
 4426
 4427    pub fn clear_code_action_providers(&mut self) {
 4428        self.code_action_providers.clear();
 4429        self.available_code_actions.take();
 4430    }
 4431
 4432    pub fn add_code_action_provider(
 4433        &mut self,
 4434        provider: Rc<dyn CodeActionProvider>,
 4435        window: &mut Window,
 4436        cx: &mut Context<Self>,
 4437    ) {
 4438        if self
 4439            .code_action_providers
 4440            .iter()
 4441            .any(|existing_provider| existing_provider.id() == provider.id())
 4442        {
 4443            return;
 4444        }
 4445
 4446        self.code_action_providers.push(provider);
 4447        self.refresh_code_actions(window, cx);
 4448    }
 4449
 4450    pub fn remove_code_action_provider(
 4451        &mut self,
 4452        id: Arc<str>,
 4453        window: &mut Window,
 4454        cx: &mut Context<Self>,
 4455    ) {
 4456        self.code_action_providers
 4457            .retain(|provider| provider.id() != id);
 4458        self.refresh_code_actions(window, cx);
 4459    }
 4460
 4461    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4462        let buffer = self.buffer.read(cx);
 4463        let newest_selection = self.selections.newest_anchor().clone();
 4464        if newest_selection.head().diff_base_anchor.is_some() {
 4465            return None;
 4466        }
 4467        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4468        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4469        if start_buffer != end_buffer {
 4470            return None;
 4471        }
 4472
 4473        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4474            cx.background_executor()
 4475                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4476                .await;
 4477
 4478            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4479                let providers = this.code_action_providers.clone();
 4480                let tasks = this
 4481                    .code_action_providers
 4482                    .iter()
 4483                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4484                    .collect::<Vec<_>>();
 4485                (providers, tasks)
 4486            })?;
 4487
 4488            let mut actions = Vec::new();
 4489            for (provider, provider_actions) in
 4490                providers.into_iter().zip(future::join_all(tasks).await)
 4491            {
 4492                if let Some(provider_actions) = provider_actions.log_err() {
 4493                    actions.extend(provider_actions.into_iter().map(|action| {
 4494                        AvailableCodeAction {
 4495                            excerpt_id: newest_selection.start.excerpt_id,
 4496                            action,
 4497                            provider: provider.clone(),
 4498                        }
 4499                    }));
 4500                }
 4501            }
 4502
 4503            this.update(&mut cx, |this, cx| {
 4504                this.available_code_actions = if actions.is_empty() {
 4505                    None
 4506                } else {
 4507                    Some((
 4508                        Location {
 4509                            buffer: start_buffer,
 4510                            range: start..end,
 4511                        },
 4512                        actions.into(),
 4513                    ))
 4514                };
 4515                cx.notify();
 4516            })
 4517        }));
 4518        None
 4519    }
 4520
 4521    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4522        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4523            self.show_git_blame_inline = false;
 4524
 4525            self.show_git_blame_inline_delay_task =
 4526                Some(cx.spawn_in(window, |this, mut cx| async move {
 4527                    cx.background_executor().timer(delay).await;
 4528
 4529                    this.update(&mut cx, |this, cx| {
 4530                        this.show_git_blame_inline = true;
 4531                        cx.notify();
 4532                    })
 4533                    .log_err();
 4534                }));
 4535        }
 4536    }
 4537
 4538    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4539        if self.pending_rename.is_some() {
 4540            return None;
 4541        }
 4542
 4543        let provider = self.semantics_provider.clone()?;
 4544        let buffer = self.buffer.read(cx);
 4545        let newest_selection = self.selections.newest_anchor().clone();
 4546        let cursor_position = newest_selection.head();
 4547        let (cursor_buffer, cursor_buffer_position) =
 4548            buffer.text_anchor_for_position(cursor_position, cx)?;
 4549        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4550        if cursor_buffer != tail_buffer {
 4551            return None;
 4552        }
 4553        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4554        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4555            cx.background_executor()
 4556                .timer(Duration::from_millis(debounce))
 4557                .await;
 4558
 4559            let highlights = if let Some(highlights) = cx
 4560                .update(|cx| {
 4561                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4562                })
 4563                .ok()
 4564                .flatten()
 4565            {
 4566                highlights.await.log_err()
 4567            } else {
 4568                None
 4569            };
 4570
 4571            if let Some(highlights) = highlights {
 4572                this.update(&mut cx, |this, cx| {
 4573                    if this.pending_rename.is_some() {
 4574                        return;
 4575                    }
 4576
 4577                    let buffer_id = cursor_position.buffer_id;
 4578                    let buffer = this.buffer.read(cx);
 4579                    if !buffer
 4580                        .text_anchor_for_position(cursor_position, cx)
 4581                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4582                    {
 4583                        return;
 4584                    }
 4585
 4586                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4587                    let mut write_ranges = Vec::new();
 4588                    let mut read_ranges = Vec::new();
 4589                    for highlight in highlights {
 4590                        for (excerpt_id, excerpt_range) in
 4591                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4592                        {
 4593                            let start = highlight
 4594                                .range
 4595                                .start
 4596                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4597                            let end = highlight
 4598                                .range
 4599                                .end
 4600                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4601                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4602                                continue;
 4603                            }
 4604
 4605                            let range = Anchor {
 4606                                buffer_id,
 4607                                excerpt_id,
 4608                                text_anchor: start,
 4609                                diff_base_anchor: None,
 4610                            }..Anchor {
 4611                                buffer_id,
 4612                                excerpt_id,
 4613                                text_anchor: end,
 4614                                diff_base_anchor: None,
 4615                            };
 4616                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4617                                write_ranges.push(range);
 4618                            } else {
 4619                                read_ranges.push(range);
 4620                            }
 4621                        }
 4622                    }
 4623
 4624                    this.highlight_background::<DocumentHighlightRead>(
 4625                        &read_ranges,
 4626                        |theme| theme.editor_document_highlight_read_background,
 4627                        cx,
 4628                    );
 4629                    this.highlight_background::<DocumentHighlightWrite>(
 4630                        &write_ranges,
 4631                        |theme| theme.editor_document_highlight_write_background,
 4632                        cx,
 4633                    );
 4634                    cx.notify();
 4635                })
 4636                .log_err();
 4637            }
 4638        }));
 4639        None
 4640    }
 4641
 4642    pub fn refresh_inline_completion(
 4643        &mut self,
 4644        debounce: bool,
 4645        user_requested: bool,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) -> Option<()> {
 4649        let provider = self.inline_completion_provider()?;
 4650        let cursor = self.selections.newest_anchor().head();
 4651        let (buffer, cursor_buffer_position) =
 4652            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4653
 4654        if !user_requested
 4655            && (!self.enable_inline_completions
 4656                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4657                || !self.is_focused(window)
 4658                || buffer.read(cx).is_empty())
 4659        {
 4660            self.discard_inline_completion(false, cx);
 4661            return None;
 4662        }
 4663
 4664        self.update_visible_inline_completion(window, cx);
 4665        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4666        Some(())
 4667    }
 4668
 4669    fn cycle_inline_completion(
 4670        &mut self,
 4671        direction: Direction,
 4672        window: &mut Window,
 4673        cx: &mut Context<Self>,
 4674    ) -> Option<()> {
 4675        let provider = self.inline_completion_provider()?;
 4676        let cursor = self.selections.newest_anchor().head();
 4677        let (buffer, cursor_buffer_position) =
 4678            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4679        if !self.enable_inline_completions
 4680            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4681        {
 4682            return None;
 4683        }
 4684
 4685        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4686        self.update_visible_inline_completion(window, cx);
 4687
 4688        Some(())
 4689    }
 4690
 4691    pub fn show_inline_completion(
 4692        &mut self,
 4693        _: &ShowInlineCompletion,
 4694        window: &mut Window,
 4695        cx: &mut Context<Self>,
 4696    ) {
 4697        if !self.has_active_inline_completion() {
 4698            self.refresh_inline_completion(false, true, window, cx);
 4699            return;
 4700        }
 4701
 4702        self.update_visible_inline_completion(window, cx);
 4703    }
 4704
 4705    pub fn display_cursor_names(
 4706        &mut self,
 4707        _: &DisplayCursorNames,
 4708        window: &mut Window,
 4709        cx: &mut Context<Self>,
 4710    ) {
 4711        self.show_cursor_names(window, cx);
 4712    }
 4713
 4714    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4715        self.show_cursor_names = true;
 4716        cx.notify();
 4717        cx.spawn_in(window, |this, mut cx| async move {
 4718            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4719            this.update(&mut cx, |this, cx| {
 4720                this.show_cursor_names = false;
 4721                cx.notify()
 4722            })
 4723            .ok()
 4724        })
 4725        .detach();
 4726    }
 4727
 4728    pub fn next_inline_completion(
 4729        &mut self,
 4730        _: &NextInlineCompletion,
 4731        window: &mut Window,
 4732        cx: &mut Context<Self>,
 4733    ) {
 4734        if self.has_active_inline_completion() {
 4735            self.cycle_inline_completion(Direction::Next, window, cx);
 4736        } else {
 4737            let is_copilot_disabled = self
 4738                .refresh_inline_completion(false, true, window, cx)
 4739                .is_none();
 4740            if is_copilot_disabled {
 4741                cx.propagate();
 4742            }
 4743        }
 4744    }
 4745
 4746    pub fn previous_inline_completion(
 4747        &mut self,
 4748        _: &PreviousInlineCompletion,
 4749        window: &mut Window,
 4750        cx: &mut Context<Self>,
 4751    ) {
 4752        if self.has_active_inline_completion() {
 4753            self.cycle_inline_completion(Direction::Prev, window, cx);
 4754        } else {
 4755            let is_copilot_disabled = self
 4756                .refresh_inline_completion(false, true, window, cx)
 4757                .is_none();
 4758            if is_copilot_disabled {
 4759                cx.propagate();
 4760            }
 4761        }
 4762    }
 4763
 4764    pub fn accept_inline_completion(
 4765        &mut self,
 4766        _: &AcceptInlineCompletion,
 4767        window: &mut Window,
 4768        cx: &mut Context<Self>,
 4769    ) {
 4770        let buffer = self.buffer.read(cx);
 4771        let snapshot = buffer.snapshot(cx);
 4772        let selection = self.selections.newest_adjusted(cx);
 4773        let cursor = selection.head();
 4774        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4775        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4776        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4777        {
 4778            if cursor.column < suggested_indent.len
 4779                && cursor.column <= current_indent.len
 4780                && current_indent.len <= suggested_indent.len
 4781            {
 4782                self.tab(&Default::default(), window, cx);
 4783                return;
 4784            }
 4785        }
 4786
 4787        if self.show_inline_completions_in_menu(cx) {
 4788            self.hide_context_menu(window, cx);
 4789        }
 4790
 4791        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4792            return;
 4793        };
 4794
 4795        self.report_inline_completion_event(true, cx);
 4796
 4797        match &active_inline_completion.completion {
 4798            InlineCompletion::Move { target, .. } => {
 4799                let target = *target;
 4800                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4801                    selections.select_anchor_ranges([target..target]);
 4802                });
 4803            }
 4804            InlineCompletion::Edit { edits, .. } => {
 4805                if let Some(provider) = self.inline_completion_provider() {
 4806                    provider.accept(cx);
 4807                }
 4808
 4809                let snapshot = self.buffer.read(cx).snapshot(cx);
 4810                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4811
 4812                self.buffer.update(cx, |buffer, cx| {
 4813                    buffer.edit(edits.iter().cloned(), None, cx)
 4814                });
 4815
 4816                self.change_selections(None, window, cx, |s| {
 4817                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4818                });
 4819
 4820                self.update_visible_inline_completion(window, cx);
 4821                if self.active_inline_completion.is_none() {
 4822                    self.refresh_inline_completion(true, true, window, cx);
 4823                }
 4824
 4825                cx.notify();
 4826            }
 4827        }
 4828    }
 4829
 4830    pub fn accept_partial_inline_completion(
 4831        &mut self,
 4832        _: &AcceptPartialInlineCompletion,
 4833        window: &mut Window,
 4834        cx: &mut Context<Self>,
 4835    ) {
 4836        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4837            return;
 4838        };
 4839        if self.selections.count() != 1 {
 4840            return;
 4841        }
 4842
 4843        self.report_inline_completion_event(true, cx);
 4844
 4845        match &active_inline_completion.completion {
 4846            InlineCompletion::Move { target, .. } => {
 4847                let target = *target;
 4848                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4849                    selections.select_anchor_ranges([target..target]);
 4850                });
 4851            }
 4852            InlineCompletion::Edit { edits, .. } => {
 4853                // Find an insertion that starts at the cursor position.
 4854                let snapshot = self.buffer.read(cx).snapshot(cx);
 4855                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4856                let insertion = edits.iter().find_map(|(range, text)| {
 4857                    let range = range.to_offset(&snapshot);
 4858                    if range.is_empty() && range.start == cursor_offset {
 4859                        Some(text)
 4860                    } else {
 4861                        None
 4862                    }
 4863                });
 4864
 4865                if let Some(text) = insertion {
 4866                    let mut partial_completion = text
 4867                        .chars()
 4868                        .by_ref()
 4869                        .take_while(|c| c.is_alphabetic())
 4870                        .collect::<String>();
 4871                    if partial_completion.is_empty() {
 4872                        partial_completion = text
 4873                            .chars()
 4874                            .by_ref()
 4875                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4876                            .collect::<String>();
 4877                    }
 4878
 4879                    cx.emit(EditorEvent::InputHandled {
 4880                        utf16_range_to_replace: None,
 4881                        text: partial_completion.clone().into(),
 4882                    });
 4883
 4884                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4885
 4886                    self.refresh_inline_completion(true, true, window, cx);
 4887                    cx.notify();
 4888                } else {
 4889                    self.accept_inline_completion(&Default::default(), window, cx);
 4890                }
 4891            }
 4892        }
 4893    }
 4894
 4895    fn discard_inline_completion(
 4896        &mut self,
 4897        should_report_inline_completion_event: bool,
 4898        cx: &mut Context<Self>,
 4899    ) -> bool {
 4900        if should_report_inline_completion_event {
 4901            self.report_inline_completion_event(false, cx);
 4902        }
 4903
 4904        if let Some(provider) = self.inline_completion_provider() {
 4905            provider.discard(cx);
 4906        }
 4907
 4908        self.take_active_inline_completion(cx)
 4909    }
 4910
 4911    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4912        let Some(provider) = self.inline_completion_provider() else {
 4913            return;
 4914        };
 4915
 4916        let Some((_, buffer, _)) = self
 4917            .buffer
 4918            .read(cx)
 4919            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4920        else {
 4921            return;
 4922        };
 4923
 4924        let extension = buffer
 4925            .read(cx)
 4926            .file()
 4927            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4928
 4929        let event_type = match accepted {
 4930            true => "Inline Completion Accepted",
 4931            false => "Inline Completion Discarded",
 4932        };
 4933        telemetry::event!(
 4934            event_type,
 4935            provider = provider.name(),
 4936            suggestion_accepted = accepted,
 4937            file_extension = extension,
 4938        );
 4939    }
 4940
 4941    pub fn has_active_inline_completion(&self) -> bool {
 4942        self.active_inline_completion.is_some()
 4943    }
 4944
 4945    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 4946        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 4947            return false;
 4948        };
 4949
 4950        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 4951        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4952        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 4953        true
 4954    }
 4955
 4956    pub fn is_previewing_inline_completion(&self) -> bool {
 4957        matches!(
 4958            self.context_menu.borrow().as_ref(),
 4959            Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
 4960        )
 4961    }
 4962
 4963    fn update_inline_completion_preview(
 4964        &mut self,
 4965        modifiers: &Modifiers,
 4966        window: &mut Window,
 4967        cx: &mut Context<Self>,
 4968    ) {
 4969        // Moves jump directly with a preview step
 4970
 4971        if self
 4972            .active_inline_completion
 4973            .as_ref()
 4974            .map_or(true, |c| c.is_move())
 4975        {
 4976            cx.notify();
 4977            return;
 4978        }
 4979
 4980        if !self.show_inline_completions_in_menu(cx) {
 4981            return;
 4982        }
 4983
 4984        let mut menu_borrow = self.context_menu.borrow_mut();
 4985
 4986        let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
 4987            return;
 4988        };
 4989
 4990        if completions_menu.is_empty()
 4991            || completions_menu.previewing_inline_completion == modifiers.alt
 4992        {
 4993            return;
 4994        }
 4995
 4996        completions_menu.set_previewing_inline_completion(modifiers.alt);
 4997        drop(menu_borrow);
 4998        self.update_visible_inline_completion(window, cx);
 4999    }
 5000
 5001    fn update_visible_inline_completion(
 5002        &mut self,
 5003        _window: &mut Window,
 5004        cx: &mut Context<Self>,
 5005    ) -> Option<()> {
 5006        let selection = self.selections.newest_anchor();
 5007        let cursor = selection.head();
 5008        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5009        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5010        let excerpt_id = cursor.excerpt_id;
 5011
 5012        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5013        let completions_menu_has_precedence = !show_in_menu
 5014            && (self.context_menu.borrow().is_some()
 5015                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5016        if completions_menu_has_precedence
 5017            || !offset_selection.is_empty()
 5018            || !self.enable_inline_completions
 5019            || self
 5020                .active_inline_completion
 5021                .as_ref()
 5022                .map_or(false, |completion| {
 5023                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5024                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5025                    !invalidation_range.contains(&offset_selection.head())
 5026                })
 5027        {
 5028            self.discard_inline_completion(false, cx);
 5029            return None;
 5030        }
 5031
 5032        self.take_active_inline_completion(cx);
 5033        let provider = self.inline_completion_provider()?;
 5034
 5035        let (buffer, cursor_buffer_position) =
 5036            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5037
 5038        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5039        let edits = inline_completion
 5040            .edits
 5041            .into_iter()
 5042            .flat_map(|(range, new_text)| {
 5043                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5044                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5045                Some((start..end, new_text))
 5046            })
 5047            .collect::<Vec<_>>();
 5048        if edits.is_empty() {
 5049            return None;
 5050        }
 5051
 5052        let first_edit_start = edits.first().unwrap().0.start;
 5053        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5054        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5055
 5056        let last_edit_end = edits.last().unwrap().0.end;
 5057        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5058        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5059
 5060        let cursor_row = cursor.to_point(&multibuffer).row;
 5061
 5062        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5063
 5064        let mut inlay_ids = Vec::new();
 5065        let invalidation_row_range;
 5066        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5067            Some(cursor_row..edit_end_row)
 5068        } else if cursor_row > edit_end_row {
 5069            Some(edit_start_row..cursor_row)
 5070        } else {
 5071            None
 5072        };
 5073        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5074            invalidation_row_range = move_invalidation_row_range;
 5075            let target = first_edit_start;
 5076            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5077            // TODO: Base this off of TreeSitter or word boundaries?
 5078            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5079                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5080                Bias::Left,
 5081            ));
 5082            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5083                Point::new(target_point.row, target_point.column + 20),
 5084                Bias::Right,
 5085            ));
 5086            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5087            InlineCompletion::Move {
 5088                target,
 5089                range_around_target,
 5090                snapshot,
 5091            }
 5092        } else {
 5093            if !show_in_menu || !self.has_active_completions_menu() {
 5094                if edits
 5095                    .iter()
 5096                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5097                {
 5098                    let mut inlays = Vec::new();
 5099                    for (range, new_text) in &edits {
 5100                        let inlay = Inlay::inline_completion(
 5101                            post_inc(&mut self.next_inlay_id),
 5102                            range.start,
 5103                            new_text.as_str(),
 5104                        );
 5105                        inlay_ids.push(inlay.id);
 5106                        inlays.push(inlay);
 5107                    }
 5108
 5109                    self.splice_inlays(&[], inlays, cx);
 5110                } else {
 5111                    let background_color = cx.theme().status().deleted_background;
 5112                    self.highlight_text::<InlineCompletionHighlight>(
 5113                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5114                        HighlightStyle {
 5115                            background_color: Some(background_color),
 5116                            ..Default::default()
 5117                        },
 5118                        cx,
 5119                    );
 5120                }
 5121            }
 5122
 5123            invalidation_row_range = edit_start_row..edit_end_row;
 5124
 5125            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5126                if provider.show_tab_accept_marker() {
 5127                    EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
 5128                } else {
 5129                    EditDisplayMode::Inline
 5130                }
 5131            } else {
 5132                EditDisplayMode::DiffPopover
 5133            };
 5134
 5135            InlineCompletion::Edit {
 5136                edits,
 5137                edit_preview: inline_completion.edit_preview,
 5138                display_mode,
 5139                snapshot,
 5140            }
 5141        };
 5142
 5143        let invalidation_range = multibuffer
 5144            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5145            ..multibuffer.anchor_after(Point::new(
 5146                invalidation_row_range.end,
 5147                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5148            ));
 5149
 5150        self.stale_inline_completion_in_menu = None;
 5151        self.active_inline_completion = Some(InlineCompletionState {
 5152            inlay_ids,
 5153            completion,
 5154            invalidation_range,
 5155        });
 5156
 5157        cx.notify();
 5158
 5159        Some(())
 5160    }
 5161
 5162    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5163        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5164    }
 5165
 5166    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5167        let by_provider = matches!(
 5168            self.menu_inline_completions_policy,
 5169            MenuInlineCompletionsPolicy::ByProvider
 5170        );
 5171
 5172        by_provider
 5173            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5174            && self
 5175                .inline_completion_provider()
 5176                .map_or(false, |provider| provider.show_completions_in_menu())
 5177    }
 5178
 5179    fn render_code_actions_indicator(
 5180        &self,
 5181        _style: &EditorStyle,
 5182        row: DisplayRow,
 5183        is_active: bool,
 5184        cx: &mut Context<Self>,
 5185    ) -> Option<IconButton> {
 5186        if self.available_code_actions.is_some() {
 5187            Some(
 5188                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5189                    .shape(ui::IconButtonShape::Square)
 5190                    .icon_size(IconSize::XSmall)
 5191                    .icon_color(Color::Muted)
 5192                    .toggle_state(is_active)
 5193                    .tooltip({
 5194                        let focus_handle = self.focus_handle.clone();
 5195                        move |window, cx| {
 5196                            Tooltip::for_action_in(
 5197                                "Toggle Code Actions",
 5198                                &ToggleCodeActions {
 5199                                    deployed_from_indicator: None,
 5200                                },
 5201                                &focus_handle,
 5202                                window,
 5203                                cx,
 5204                            )
 5205                        }
 5206                    })
 5207                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5208                        window.focus(&editor.focus_handle(cx));
 5209                        editor.toggle_code_actions(
 5210                            &ToggleCodeActions {
 5211                                deployed_from_indicator: Some(row),
 5212                            },
 5213                            window,
 5214                            cx,
 5215                        );
 5216                    })),
 5217            )
 5218        } else {
 5219            None
 5220        }
 5221    }
 5222
 5223    fn clear_tasks(&mut self) {
 5224        self.tasks.clear()
 5225    }
 5226
 5227    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5228        if self.tasks.insert(key, value).is_some() {
 5229            // This case should hopefully be rare, but just in case...
 5230            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5231        }
 5232    }
 5233
 5234    fn build_tasks_context(
 5235        project: &Entity<Project>,
 5236        buffer: &Entity<Buffer>,
 5237        buffer_row: u32,
 5238        tasks: &Arc<RunnableTasks>,
 5239        cx: &mut Context<Self>,
 5240    ) -> Task<Option<task::TaskContext>> {
 5241        let position = Point::new(buffer_row, tasks.column);
 5242        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5243        let location = Location {
 5244            buffer: buffer.clone(),
 5245            range: range_start..range_start,
 5246        };
 5247        // Fill in the environmental variables from the tree-sitter captures
 5248        let mut captured_task_variables = TaskVariables::default();
 5249        for (capture_name, value) in tasks.extra_variables.clone() {
 5250            captured_task_variables.insert(
 5251                task::VariableName::Custom(capture_name.into()),
 5252                value.clone(),
 5253            );
 5254        }
 5255        project.update(cx, |project, cx| {
 5256            project.task_store().update(cx, |task_store, cx| {
 5257                task_store.task_context_for_location(captured_task_variables, location, cx)
 5258            })
 5259        })
 5260    }
 5261
 5262    pub fn spawn_nearest_task(
 5263        &mut self,
 5264        action: &SpawnNearestTask,
 5265        window: &mut Window,
 5266        cx: &mut Context<Self>,
 5267    ) {
 5268        let Some((workspace, _)) = self.workspace.clone() else {
 5269            return;
 5270        };
 5271        let Some(project) = self.project.clone() else {
 5272            return;
 5273        };
 5274
 5275        // Try to find a closest, enclosing node using tree-sitter that has a
 5276        // task
 5277        let Some((buffer, buffer_row, tasks)) = self
 5278            .find_enclosing_node_task(cx)
 5279            // Or find the task that's closest in row-distance.
 5280            .or_else(|| self.find_closest_task(cx))
 5281        else {
 5282            return;
 5283        };
 5284
 5285        let reveal_strategy = action.reveal;
 5286        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5287        cx.spawn_in(window, |_, mut cx| async move {
 5288            let context = task_context.await?;
 5289            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5290
 5291            let resolved = resolved_task.resolved.as_mut()?;
 5292            resolved.reveal = reveal_strategy;
 5293
 5294            workspace
 5295                .update(&mut cx, |workspace, cx| {
 5296                    workspace::tasks::schedule_resolved_task(
 5297                        workspace,
 5298                        task_source_kind,
 5299                        resolved_task,
 5300                        false,
 5301                        cx,
 5302                    );
 5303                })
 5304                .ok()
 5305        })
 5306        .detach();
 5307    }
 5308
 5309    fn find_closest_task(
 5310        &mut self,
 5311        cx: &mut Context<Self>,
 5312    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5313        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5314
 5315        let ((buffer_id, row), tasks) = self
 5316            .tasks
 5317            .iter()
 5318            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5319
 5320        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5321        let tasks = Arc::new(tasks.to_owned());
 5322        Some((buffer, *row, tasks))
 5323    }
 5324
 5325    fn find_enclosing_node_task(
 5326        &mut self,
 5327        cx: &mut Context<Self>,
 5328    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5329        let snapshot = self.buffer.read(cx).snapshot(cx);
 5330        let offset = self.selections.newest::<usize>(cx).head();
 5331        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5332        let buffer_id = excerpt.buffer().remote_id();
 5333
 5334        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5335        let mut cursor = layer.node().walk();
 5336
 5337        while cursor.goto_first_child_for_byte(offset).is_some() {
 5338            if cursor.node().end_byte() == offset {
 5339                cursor.goto_next_sibling();
 5340            }
 5341        }
 5342
 5343        // Ascend to the smallest ancestor that contains the range and has a task.
 5344        loop {
 5345            let node = cursor.node();
 5346            let node_range = node.byte_range();
 5347            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5348
 5349            // Check if this node contains our offset
 5350            if node_range.start <= offset && node_range.end >= offset {
 5351                // If it contains offset, check for task
 5352                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5353                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5354                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5355                }
 5356            }
 5357
 5358            if !cursor.goto_parent() {
 5359                break;
 5360            }
 5361        }
 5362        None
 5363    }
 5364
 5365    fn render_run_indicator(
 5366        &self,
 5367        _style: &EditorStyle,
 5368        is_active: bool,
 5369        row: DisplayRow,
 5370        cx: &mut Context<Self>,
 5371    ) -> IconButton {
 5372        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5373            .shape(ui::IconButtonShape::Square)
 5374            .icon_size(IconSize::XSmall)
 5375            .icon_color(Color::Muted)
 5376            .toggle_state(is_active)
 5377            .on_click(cx.listener(move |editor, _e, window, cx| {
 5378                window.focus(&editor.focus_handle(cx));
 5379                editor.toggle_code_actions(
 5380                    &ToggleCodeActions {
 5381                        deployed_from_indicator: Some(row),
 5382                    },
 5383                    window,
 5384                    cx,
 5385                );
 5386            }))
 5387    }
 5388
 5389    pub fn context_menu_visible(&self) -> bool {
 5390        self.context_menu
 5391            .borrow()
 5392            .as_ref()
 5393            .map_or(false, |menu| menu.visible())
 5394    }
 5395
 5396    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5397        self.context_menu
 5398            .borrow()
 5399            .as_ref()
 5400            .map(|menu| menu.origin())
 5401    }
 5402
 5403    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5404        px(32.)
 5405    }
 5406
 5407    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5408        if self.read_only(cx) {
 5409            cx.theme().players().read_only()
 5410        } else {
 5411            self.style.as_ref().unwrap().local_player
 5412        }
 5413    }
 5414
 5415    #[allow(clippy::too_many_arguments)]
 5416    fn render_edit_prediction_cursor_popover(
 5417        &self,
 5418        max_width: Pixels,
 5419        cursor_point: Point,
 5420        line_layouts: &[LineWithInvisibles],
 5421        style: &EditorStyle,
 5422        accept_keystroke: &gpui::Keystroke,
 5423        window: &Window,
 5424        cx: &mut Context<Editor>,
 5425    ) -> Option<AnyElement> {
 5426        let provider = self.inline_completion_provider.as_ref()?;
 5427
 5428        if provider.provider.needs_terms_acceptance(cx) {
 5429            return Some(
 5430                h_flex()
 5431                    .h(self.edit_prediction_cursor_popover_height())
 5432                    .flex_1()
 5433                    .px_2()
 5434                    .gap_3()
 5435                    .elevation_2(cx)
 5436                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5437                    .id("accept-terms")
 5438                    .cursor_pointer()
 5439                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5440                    .on_click(cx.listener(|this, _event, window, cx| {
 5441                        cx.stop_propagation();
 5442                        this.toggle_zed_predict_onboarding(window, cx)
 5443                    }))
 5444                    .child(
 5445                        h_flex()
 5446                            .w_full()
 5447                            .gap_2()
 5448                            .child(Icon::new(IconName::ZedPredict))
 5449                            .child(Label::new("Accept Terms of Service"))
 5450                            .child(div().w_full())
 5451                            .child(Icon::new(IconName::ArrowUpRight))
 5452                            .into_any_element(),
 5453                    )
 5454                    .into_any(),
 5455            );
 5456        }
 5457
 5458        let is_refreshing = provider.provider.is_refreshing(cx);
 5459
 5460        fn pending_completion_container() -> Div {
 5461            h_flex().gap_3().child(Icon::new(IconName::ZedPredict))
 5462        }
 5463
 5464        let completion = match &self.active_inline_completion {
 5465            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5466                completion,
 5467                cursor_point,
 5468                line_layouts,
 5469                style,
 5470                cx,
 5471            )?,
 5472
 5473            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5474                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5475                    stale_completion,
 5476                    cursor_point,
 5477                    line_layouts,
 5478                    style,
 5479                    cx,
 5480                )?,
 5481
 5482                None => {
 5483                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5484                }
 5485            },
 5486
 5487            None => pending_completion_container().child(Label::new("No Prediction")),
 5488        };
 5489
 5490        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5491        let completion = completion.font(buffer_font.clone());
 5492
 5493        let completion = if is_refreshing {
 5494            completion
 5495                .with_animation(
 5496                    "loading-completion",
 5497                    Animation::new(Duration::from_secs(2))
 5498                        .repeat()
 5499                        .with_easing(pulsating_between(0.4, 0.8)),
 5500                    |label, delta| label.opacity(delta),
 5501                )
 5502                .into_any_element()
 5503        } else {
 5504            completion.into_any_element()
 5505        };
 5506
 5507        let has_completion = self.active_inline_completion.is_some();
 5508
 5509        Some(
 5510            h_flex()
 5511                .h(self.edit_prediction_cursor_popover_height())
 5512                .max_w(max_width)
 5513                .flex_1()
 5514                .px_2()
 5515                .gap_3()
 5516                .elevation_2(cx)
 5517                .child(completion)
 5518                .child(div().w_full())
 5519                .child(
 5520                    h_flex()
 5521                        .border_l_1()
 5522                        .border_color(cx.theme().colors().border_variant)
 5523                        .pl_2()
 5524                        .child(
 5525                            h_flex()
 5526                                .font(buffer_font.clone())
 5527                                .p_1()
 5528                                .rounded_sm()
 5529                                .children(ui::render_modifiers(
 5530                                    &accept_keystroke.modifiers,
 5531                                    PlatformStyle::platform(),
 5532                                    if window.modifiers() == accept_keystroke.modifiers {
 5533                                        Some(Color::Accent)
 5534                                    } else {
 5535                                        None
 5536                                    },
 5537                                )),
 5538                        )
 5539                        .opacity(if has_completion { 1.0 } else { 0.1 })
 5540                        .child(
 5541                            if self
 5542                                .active_inline_completion
 5543                                .as_ref()
 5544                                .map_or(false, |c| c.is_move())
 5545                            {
 5546                                div()
 5547                                    .child(ui::Key::new(&accept_keystroke.key, None))
 5548                                    .font(buffer_font.clone())
 5549                                    .into_any()
 5550                            } else {
 5551                                Label::new("Preview").color(Color::Muted).into_any_element()
 5552                            },
 5553                        ),
 5554                )
 5555                .into_any(),
 5556        )
 5557    }
 5558
 5559    fn render_edit_prediction_cursor_popover_preview(
 5560        &self,
 5561        completion: &InlineCompletionState,
 5562        cursor_point: Point,
 5563        line_layouts: &[LineWithInvisibles],
 5564        style: &EditorStyle,
 5565        cx: &mut Context<Editor>,
 5566    ) -> Option<Div> {
 5567        use text::ToPoint as _;
 5568
 5569        fn render_relative_row_jump(
 5570            prefix: impl Into<String>,
 5571            current_row: u32,
 5572            target_row: u32,
 5573        ) -> Div {
 5574            let (row_diff, arrow) = if target_row < current_row {
 5575                (current_row - target_row, IconName::ArrowUp)
 5576            } else {
 5577                (target_row - current_row, IconName::ArrowDown)
 5578            };
 5579
 5580            h_flex()
 5581                .child(
 5582                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5583                        .color(Color::Muted)
 5584                        .size(LabelSize::Small),
 5585                )
 5586                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5587        }
 5588
 5589        match &completion.completion {
 5590            InlineCompletion::Edit {
 5591                edits,
 5592                edit_preview,
 5593                snapshot,
 5594                display_mode: _,
 5595            } => {
 5596                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5597
 5598                let highlighted_edits = crate::inline_completion_edit_text(
 5599                    &snapshot,
 5600                    &edits,
 5601                    edit_preview.as_ref()?,
 5602                    true,
 5603                    cx,
 5604                );
 5605
 5606                let len_total = highlighted_edits.text.len();
 5607                let first_line = &highlighted_edits.text
 5608                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5609                let first_line_len = first_line.len();
 5610
 5611                let first_highlight_start = highlighted_edits
 5612                    .highlights
 5613                    .first()
 5614                    .map_or(0, |(range, _)| range.start);
 5615                let drop_prefix_len = first_line
 5616                    .char_indices()
 5617                    .find(|(_, c)| !c.is_whitespace())
 5618                    .map_or(first_highlight_start, |(ix, _)| {
 5619                        ix.min(first_highlight_start)
 5620                    });
 5621
 5622                let preview_text = &first_line[drop_prefix_len..];
 5623                let preview_len = preview_text.len();
 5624                let highlights = highlighted_edits
 5625                    .highlights
 5626                    .into_iter()
 5627                    .take_until(|(range, _)| range.start > first_line_len)
 5628                    .map(|(range, style)| {
 5629                        (
 5630                            range.start - drop_prefix_len
 5631                                ..(range.end - drop_prefix_len).min(preview_len),
 5632                            style,
 5633                        )
 5634                    });
 5635
 5636                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5637                    .with_highlights(&style.text, highlights);
 5638
 5639                let preview = h_flex()
 5640                    .gap_1()
 5641                    .child(styled_text)
 5642                    .when(len_total > first_line_len, |parent| parent.child(""));
 5643
 5644                let left = if first_edit_row != cursor_point.row {
 5645                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5646                        .into_any_element()
 5647                } else {
 5648                    Icon::new(IconName::ZedPredict).into_any_element()
 5649                };
 5650
 5651                Some(h_flex().gap_3().child(left).child(preview))
 5652            }
 5653
 5654            InlineCompletion::Move {
 5655                target,
 5656                range_around_target,
 5657                snapshot,
 5658            } => {
 5659                let highlighted_text = snapshot.highlighted_text_for_range(
 5660                    range_around_target.clone(),
 5661                    None,
 5662                    &style.syntax,
 5663                );
 5664                let cursor_color = self.current_user_player_color(cx).cursor;
 5665
 5666                let start_point = range_around_target.start.to_point(&snapshot);
 5667                let end_point = range_around_target.end.to_point(&snapshot);
 5668                let target_point = target.text_anchor.to_point(&snapshot);
 5669
 5670                let start_column_x =
 5671                    line_layouts[start_point.row as usize].x_for_index(start_point.column as usize);
 5672                let target_column_x = line_layouts[target_point.row as usize]
 5673                    .x_for_index(target_point.column as usize);
 5674                let cursor_relative_position = target_column_x - start_column_x;
 5675
 5676                let fade_before = start_point.column > 0;
 5677                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5678
 5679                let background = cx.theme().colors().elevated_surface_background;
 5680
 5681                Some(
 5682                    h_flex()
 5683                        .gap_3()
 5684                        .child(render_relative_row_jump(
 5685                            "Jump ",
 5686                            cursor_point.row,
 5687                            target.text_anchor.to_point(&snapshot).row,
 5688                        ))
 5689                        .when(!highlighted_text.text.is_empty(), |parent| {
 5690                            parent.child(
 5691                                h_flex()
 5692                                    .relative()
 5693                                    .child(highlighted_text.to_styled_text(&style.text))
 5694                                    .when(fade_before, |parent| {
 5695                                        parent.child(
 5696                                            div().absolute().top_0().left_0().w_4().h_full().bg(
 5697                                                linear_gradient(
 5698                                                    90.,
 5699                                                    linear_color_stop(background, 0.),
 5700                                                    linear_color_stop(background.opacity(0.), 1.),
 5701                                                ),
 5702                                            ),
 5703                                        )
 5704                                    })
 5705                                    .when(fade_after, |parent| {
 5706                                        parent.child(
 5707                                            div().absolute().top_0().right_0().w_4().h_full().bg(
 5708                                                linear_gradient(
 5709                                                    -90.,
 5710                                                    linear_color_stop(background, 0.),
 5711                                                    linear_color_stop(background.opacity(0.), 1.),
 5712                                                ),
 5713                                            ),
 5714                                        )
 5715                                    })
 5716                                    .child(
 5717                                        div()
 5718                                            .w(px(2.))
 5719                                            .h_full()
 5720                                            .bg(cursor_color)
 5721                                            .absolute()
 5722                                            .top_0()
 5723                                            .left(cursor_relative_position),
 5724                                    ),
 5725                            )
 5726                        }),
 5727                )
 5728            }
 5729        }
 5730    }
 5731
 5732    fn render_context_menu(
 5733        &self,
 5734        style: &EditorStyle,
 5735        max_height_in_lines: u32,
 5736        y_flipped: bool,
 5737        window: &mut Window,
 5738        cx: &mut Context<Editor>,
 5739    ) -> Option<AnyElement> {
 5740        let menu = self.context_menu.borrow();
 5741        let menu = menu.as_ref()?;
 5742        if !menu.visible() {
 5743            return None;
 5744        };
 5745        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5746    }
 5747
 5748    fn render_context_menu_aside(
 5749        &self,
 5750        style: &EditorStyle,
 5751        max_size: Size<Pixels>,
 5752        cx: &mut Context<Editor>,
 5753    ) -> Option<AnyElement> {
 5754        self.context_menu.borrow().as_ref().and_then(|menu| {
 5755            if menu.visible() {
 5756                menu.render_aside(
 5757                    style,
 5758                    max_size,
 5759                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5760                    cx,
 5761                )
 5762            } else {
 5763                None
 5764            }
 5765        })
 5766    }
 5767
 5768    fn hide_context_menu(
 5769        &mut self,
 5770        window: &mut Window,
 5771        cx: &mut Context<Self>,
 5772    ) -> Option<CodeContextMenu> {
 5773        cx.notify();
 5774        self.completion_tasks.clear();
 5775        let context_menu = self.context_menu.borrow_mut().take();
 5776        self.stale_inline_completion_in_menu.take();
 5777        if context_menu.is_some() {
 5778            self.update_visible_inline_completion(window, cx);
 5779        }
 5780        context_menu
 5781    }
 5782
 5783    fn show_snippet_choices(
 5784        &mut self,
 5785        choices: &Vec<String>,
 5786        selection: Range<Anchor>,
 5787        cx: &mut Context<Self>,
 5788    ) {
 5789        if selection.start.buffer_id.is_none() {
 5790            return;
 5791        }
 5792        let buffer_id = selection.start.buffer_id.unwrap();
 5793        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5794        let id = post_inc(&mut self.next_completion_id);
 5795
 5796        if let Some(buffer) = buffer {
 5797            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5798                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5799            ));
 5800        }
 5801    }
 5802
 5803    pub fn insert_snippet(
 5804        &mut self,
 5805        insertion_ranges: &[Range<usize>],
 5806        snippet: Snippet,
 5807        window: &mut Window,
 5808        cx: &mut Context<Self>,
 5809    ) -> Result<()> {
 5810        struct Tabstop<T> {
 5811            is_end_tabstop: bool,
 5812            ranges: Vec<Range<T>>,
 5813            choices: Option<Vec<String>>,
 5814        }
 5815
 5816        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5817            let snippet_text: Arc<str> = snippet.text.clone().into();
 5818            buffer.edit(
 5819                insertion_ranges
 5820                    .iter()
 5821                    .cloned()
 5822                    .map(|range| (range, snippet_text.clone())),
 5823                Some(AutoindentMode::EachLine),
 5824                cx,
 5825            );
 5826
 5827            let snapshot = &*buffer.read(cx);
 5828            let snippet = &snippet;
 5829            snippet
 5830                .tabstops
 5831                .iter()
 5832                .map(|tabstop| {
 5833                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5834                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5835                    });
 5836                    let mut tabstop_ranges = tabstop
 5837                        .ranges
 5838                        .iter()
 5839                        .flat_map(|tabstop_range| {
 5840                            let mut delta = 0_isize;
 5841                            insertion_ranges.iter().map(move |insertion_range| {
 5842                                let insertion_start = insertion_range.start as isize + delta;
 5843                                delta +=
 5844                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5845
 5846                                let start = ((insertion_start + tabstop_range.start) as usize)
 5847                                    .min(snapshot.len());
 5848                                let end = ((insertion_start + tabstop_range.end) as usize)
 5849                                    .min(snapshot.len());
 5850                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5851                            })
 5852                        })
 5853                        .collect::<Vec<_>>();
 5854                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5855
 5856                    Tabstop {
 5857                        is_end_tabstop,
 5858                        ranges: tabstop_ranges,
 5859                        choices: tabstop.choices.clone(),
 5860                    }
 5861                })
 5862                .collect::<Vec<_>>()
 5863        });
 5864        if let Some(tabstop) = tabstops.first() {
 5865            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5866                s.select_ranges(tabstop.ranges.iter().cloned());
 5867            });
 5868
 5869            if let Some(choices) = &tabstop.choices {
 5870                if let Some(selection) = tabstop.ranges.first() {
 5871                    self.show_snippet_choices(choices, selection.clone(), cx)
 5872                }
 5873            }
 5874
 5875            // If we're already at the last tabstop and it's at the end of the snippet,
 5876            // we're done, we don't need to keep the state around.
 5877            if !tabstop.is_end_tabstop {
 5878                let choices = tabstops
 5879                    .iter()
 5880                    .map(|tabstop| tabstop.choices.clone())
 5881                    .collect();
 5882
 5883                let ranges = tabstops
 5884                    .into_iter()
 5885                    .map(|tabstop| tabstop.ranges)
 5886                    .collect::<Vec<_>>();
 5887
 5888                self.snippet_stack.push(SnippetState {
 5889                    active_index: 0,
 5890                    ranges,
 5891                    choices,
 5892                });
 5893            }
 5894
 5895            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5896            if self.autoclose_regions.is_empty() {
 5897                let snapshot = self.buffer.read(cx).snapshot(cx);
 5898                for selection in &mut self.selections.all::<Point>(cx) {
 5899                    let selection_head = selection.head();
 5900                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5901                        continue;
 5902                    };
 5903
 5904                    let mut bracket_pair = None;
 5905                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5906                    let prev_chars = snapshot
 5907                        .reversed_chars_at(selection_head)
 5908                        .collect::<String>();
 5909                    for (pair, enabled) in scope.brackets() {
 5910                        if enabled
 5911                            && pair.close
 5912                            && prev_chars.starts_with(pair.start.as_str())
 5913                            && next_chars.starts_with(pair.end.as_str())
 5914                        {
 5915                            bracket_pair = Some(pair.clone());
 5916                            break;
 5917                        }
 5918                    }
 5919                    if let Some(pair) = bracket_pair {
 5920                        let start = snapshot.anchor_after(selection_head);
 5921                        let end = snapshot.anchor_after(selection_head);
 5922                        self.autoclose_regions.push(AutocloseRegion {
 5923                            selection_id: selection.id,
 5924                            range: start..end,
 5925                            pair,
 5926                        });
 5927                    }
 5928                }
 5929            }
 5930        }
 5931        Ok(())
 5932    }
 5933
 5934    pub fn move_to_next_snippet_tabstop(
 5935        &mut self,
 5936        window: &mut Window,
 5937        cx: &mut Context<Self>,
 5938    ) -> bool {
 5939        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5940    }
 5941
 5942    pub fn move_to_prev_snippet_tabstop(
 5943        &mut self,
 5944        window: &mut Window,
 5945        cx: &mut Context<Self>,
 5946    ) -> bool {
 5947        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5948    }
 5949
 5950    pub fn move_to_snippet_tabstop(
 5951        &mut self,
 5952        bias: Bias,
 5953        window: &mut Window,
 5954        cx: &mut Context<Self>,
 5955    ) -> bool {
 5956        if let Some(mut snippet) = self.snippet_stack.pop() {
 5957            match bias {
 5958                Bias::Left => {
 5959                    if snippet.active_index > 0 {
 5960                        snippet.active_index -= 1;
 5961                    } else {
 5962                        self.snippet_stack.push(snippet);
 5963                        return false;
 5964                    }
 5965                }
 5966                Bias::Right => {
 5967                    if snippet.active_index + 1 < snippet.ranges.len() {
 5968                        snippet.active_index += 1;
 5969                    } else {
 5970                        self.snippet_stack.push(snippet);
 5971                        return false;
 5972                    }
 5973                }
 5974            }
 5975            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5976                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5977                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5978                });
 5979
 5980                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5981                    if let Some(selection) = current_ranges.first() {
 5982                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5983                    }
 5984                }
 5985
 5986                // If snippet state is not at the last tabstop, push it back on the stack
 5987                if snippet.active_index + 1 < snippet.ranges.len() {
 5988                    self.snippet_stack.push(snippet);
 5989                }
 5990                return true;
 5991            }
 5992        }
 5993
 5994        false
 5995    }
 5996
 5997    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5998        self.transact(window, cx, |this, window, cx| {
 5999            this.select_all(&SelectAll, window, cx);
 6000            this.insert("", window, cx);
 6001        });
 6002    }
 6003
 6004    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6005        self.transact(window, cx, |this, window, cx| {
 6006            this.select_autoclose_pair(window, cx);
 6007            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6008            if !this.linked_edit_ranges.is_empty() {
 6009                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6010                let snapshot = this.buffer.read(cx).snapshot(cx);
 6011
 6012                for selection in selections.iter() {
 6013                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6014                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6015                    if selection_start.buffer_id != selection_end.buffer_id {
 6016                        continue;
 6017                    }
 6018                    if let Some(ranges) =
 6019                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6020                    {
 6021                        for (buffer, entries) in ranges {
 6022                            linked_ranges.entry(buffer).or_default().extend(entries);
 6023                        }
 6024                    }
 6025                }
 6026            }
 6027
 6028            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6029            if !this.selections.line_mode {
 6030                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6031                for selection in &mut selections {
 6032                    if selection.is_empty() {
 6033                        let old_head = selection.head();
 6034                        let mut new_head =
 6035                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6036                                .to_point(&display_map);
 6037                        if let Some((buffer, line_buffer_range)) = display_map
 6038                            .buffer_snapshot
 6039                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6040                        {
 6041                            let indent_size =
 6042                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6043                            let indent_len = match indent_size.kind {
 6044                                IndentKind::Space => {
 6045                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6046                                }
 6047                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6048                            };
 6049                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6050                                let indent_len = indent_len.get();
 6051                                new_head = cmp::min(
 6052                                    new_head,
 6053                                    MultiBufferPoint::new(
 6054                                        old_head.row,
 6055                                        ((old_head.column - 1) / indent_len) * indent_len,
 6056                                    ),
 6057                                );
 6058                            }
 6059                        }
 6060
 6061                        selection.set_head(new_head, SelectionGoal::None);
 6062                    }
 6063                }
 6064            }
 6065
 6066            this.signature_help_state.set_backspace_pressed(true);
 6067            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6068                s.select(selections)
 6069            });
 6070            this.insert("", window, cx);
 6071            let empty_str: Arc<str> = Arc::from("");
 6072            for (buffer, edits) in linked_ranges {
 6073                let snapshot = buffer.read(cx).snapshot();
 6074                use text::ToPoint as TP;
 6075
 6076                let edits = edits
 6077                    .into_iter()
 6078                    .map(|range| {
 6079                        let end_point = TP::to_point(&range.end, &snapshot);
 6080                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6081
 6082                        if end_point == start_point {
 6083                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6084                                .saturating_sub(1);
 6085                            start_point =
 6086                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6087                        };
 6088
 6089                        (start_point..end_point, empty_str.clone())
 6090                    })
 6091                    .sorted_by_key(|(range, _)| range.start)
 6092                    .collect::<Vec<_>>();
 6093                buffer.update(cx, |this, cx| {
 6094                    this.edit(edits, None, cx);
 6095                })
 6096            }
 6097            this.refresh_inline_completion(true, false, window, cx);
 6098            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6099        });
 6100    }
 6101
 6102    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6103        self.transact(window, cx, |this, window, cx| {
 6104            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6105                let line_mode = s.line_mode;
 6106                s.move_with(|map, selection| {
 6107                    if selection.is_empty() && !line_mode {
 6108                        let cursor = movement::right(map, selection.head());
 6109                        selection.end = cursor;
 6110                        selection.reversed = true;
 6111                        selection.goal = SelectionGoal::None;
 6112                    }
 6113                })
 6114            });
 6115            this.insert("", window, cx);
 6116            this.refresh_inline_completion(true, false, window, cx);
 6117        });
 6118    }
 6119
 6120    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6121        if self.move_to_prev_snippet_tabstop(window, cx) {
 6122            return;
 6123        }
 6124
 6125        self.outdent(&Outdent, window, cx);
 6126    }
 6127
 6128    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6129        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6130            return;
 6131        }
 6132
 6133        let mut selections = self.selections.all_adjusted(cx);
 6134        let buffer = self.buffer.read(cx);
 6135        let snapshot = buffer.snapshot(cx);
 6136        let rows_iter = selections.iter().map(|s| s.head().row);
 6137        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6138
 6139        let mut edits = Vec::new();
 6140        let mut prev_edited_row = 0;
 6141        let mut row_delta = 0;
 6142        for selection in &mut selections {
 6143            if selection.start.row != prev_edited_row {
 6144                row_delta = 0;
 6145            }
 6146            prev_edited_row = selection.end.row;
 6147
 6148            // If the selection is non-empty, then increase the indentation of the selected lines.
 6149            if !selection.is_empty() {
 6150                row_delta =
 6151                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6152                continue;
 6153            }
 6154
 6155            // If the selection is empty and the cursor is in the leading whitespace before the
 6156            // suggested indentation, then auto-indent the line.
 6157            let cursor = selection.head();
 6158            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6159            if let Some(suggested_indent) =
 6160                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6161            {
 6162                if cursor.column < suggested_indent.len
 6163                    && cursor.column <= current_indent.len
 6164                    && current_indent.len <= suggested_indent.len
 6165                {
 6166                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6167                    selection.end = selection.start;
 6168                    if row_delta == 0 {
 6169                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6170                            cursor.row,
 6171                            current_indent,
 6172                            suggested_indent,
 6173                        ));
 6174                        row_delta = suggested_indent.len - current_indent.len;
 6175                    }
 6176                    continue;
 6177                }
 6178            }
 6179
 6180            // Otherwise, insert a hard or soft tab.
 6181            let settings = buffer.settings_at(cursor, cx);
 6182            let tab_size = if settings.hard_tabs {
 6183                IndentSize::tab()
 6184            } else {
 6185                let tab_size = settings.tab_size.get();
 6186                let char_column = snapshot
 6187                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6188                    .flat_map(str::chars)
 6189                    .count()
 6190                    + row_delta as usize;
 6191                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6192                IndentSize::spaces(chars_to_next_tab_stop)
 6193            };
 6194            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6195            selection.end = selection.start;
 6196            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6197            row_delta += tab_size.len;
 6198        }
 6199
 6200        self.transact(window, cx, |this, window, cx| {
 6201            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6202            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6203                s.select(selections)
 6204            });
 6205            this.refresh_inline_completion(true, false, window, cx);
 6206        });
 6207    }
 6208
 6209    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6210        if self.read_only(cx) {
 6211            return;
 6212        }
 6213        let mut selections = self.selections.all::<Point>(cx);
 6214        let mut prev_edited_row = 0;
 6215        let mut row_delta = 0;
 6216        let mut edits = Vec::new();
 6217        let buffer = self.buffer.read(cx);
 6218        let snapshot = buffer.snapshot(cx);
 6219        for selection in &mut selections {
 6220            if selection.start.row != prev_edited_row {
 6221                row_delta = 0;
 6222            }
 6223            prev_edited_row = selection.end.row;
 6224
 6225            row_delta =
 6226                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6227        }
 6228
 6229        self.transact(window, cx, |this, window, cx| {
 6230            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6231            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6232                s.select(selections)
 6233            });
 6234        });
 6235    }
 6236
 6237    fn indent_selection(
 6238        buffer: &MultiBuffer,
 6239        snapshot: &MultiBufferSnapshot,
 6240        selection: &mut Selection<Point>,
 6241        edits: &mut Vec<(Range<Point>, String)>,
 6242        delta_for_start_row: u32,
 6243        cx: &App,
 6244    ) -> u32 {
 6245        let settings = buffer.settings_at(selection.start, cx);
 6246        let tab_size = settings.tab_size.get();
 6247        let indent_kind = if settings.hard_tabs {
 6248            IndentKind::Tab
 6249        } else {
 6250            IndentKind::Space
 6251        };
 6252        let mut start_row = selection.start.row;
 6253        let mut end_row = selection.end.row + 1;
 6254
 6255        // If a selection ends at the beginning of a line, don't indent
 6256        // that last line.
 6257        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6258            end_row -= 1;
 6259        }
 6260
 6261        // Avoid re-indenting a row that has already been indented by a
 6262        // previous selection, but still update this selection's column
 6263        // to reflect that indentation.
 6264        if delta_for_start_row > 0 {
 6265            start_row += 1;
 6266            selection.start.column += delta_for_start_row;
 6267            if selection.end.row == selection.start.row {
 6268                selection.end.column += delta_for_start_row;
 6269            }
 6270        }
 6271
 6272        let mut delta_for_end_row = 0;
 6273        let has_multiple_rows = start_row + 1 != end_row;
 6274        for row in start_row..end_row {
 6275            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6276            let indent_delta = match (current_indent.kind, indent_kind) {
 6277                (IndentKind::Space, IndentKind::Space) => {
 6278                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6279                    IndentSize::spaces(columns_to_next_tab_stop)
 6280                }
 6281                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6282                (_, IndentKind::Tab) => IndentSize::tab(),
 6283            };
 6284
 6285            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6286                0
 6287            } else {
 6288                selection.start.column
 6289            };
 6290            let row_start = Point::new(row, start);
 6291            edits.push((
 6292                row_start..row_start,
 6293                indent_delta.chars().collect::<String>(),
 6294            ));
 6295
 6296            // Update this selection's endpoints to reflect the indentation.
 6297            if row == selection.start.row {
 6298                selection.start.column += indent_delta.len;
 6299            }
 6300            if row == selection.end.row {
 6301                selection.end.column += indent_delta.len;
 6302                delta_for_end_row = indent_delta.len;
 6303            }
 6304        }
 6305
 6306        if selection.start.row == selection.end.row {
 6307            delta_for_start_row + delta_for_end_row
 6308        } else {
 6309            delta_for_end_row
 6310        }
 6311    }
 6312
 6313    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6314        if self.read_only(cx) {
 6315            return;
 6316        }
 6317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6318        let selections = self.selections.all::<Point>(cx);
 6319        let mut deletion_ranges = Vec::new();
 6320        let mut last_outdent = None;
 6321        {
 6322            let buffer = self.buffer.read(cx);
 6323            let snapshot = buffer.snapshot(cx);
 6324            for selection in &selections {
 6325                let settings = buffer.settings_at(selection.start, cx);
 6326                let tab_size = settings.tab_size.get();
 6327                let mut rows = selection.spanned_rows(false, &display_map);
 6328
 6329                // Avoid re-outdenting a row that has already been outdented by a
 6330                // previous selection.
 6331                if let Some(last_row) = last_outdent {
 6332                    if last_row == rows.start {
 6333                        rows.start = rows.start.next_row();
 6334                    }
 6335                }
 6336                let has_multiple_rows = rows.len() > 1;
 6337                for row in rows.iter_rows() {
 6338                    let indent_size = snapshot.indent_size_for_line(row);
 6339                    if indent_size.len > 0 {
 6340                        let deletion_len = match indent_size.kind {
 6341                            IndentKind::Space => {
 6342                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6343                                if columns_to_prev_tab_stop == 0 {
 6344                                    tab_size
 6345                                } else {
 6346                                    columns_to_prev_tab_stop
 6347                                }
 6348                            }
 6349                            IndentKind::Tab => 1,
 6350                        };
 6351                        let start = if has_multiple_rows
 6352                            || deletion_len > selection.start.column
 6353                            || indent_size.len < selection.start.column
 6354                        {
 6355                            0
 6356                        } else {
 6357                            selection.start.column - deletion_len
 6358                        };
 6359                        deletion_ranges.push(
 6360                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6361                        );
 6362                        last_outdent = Some(row);
 6363                    }
 6364                }
 6365            }
 6366        }
 6367
 6368        self.transact(window, cx, |this, window, cx| {
 6369            this.buffer.update(cx, |buffer, cx| {
 6370                let empty_str: Arc<str> = Arc::default();
 6371                buffer.edit(
 6372                    deletion_ranges
 6373                        .into_iter()
 6374                        .map(|range| (range, empty_str.clone())),
 6375                    None,
 6376                    cx,
 6377                );
 6378            });
 6379            let selections = this.selections.all::<usize>(cx);
 6380            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6381                s.select(selections)
 6382            });
 6383        });
 6384    }
 6385
 6386    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6387        if self.read_only(cx) {
 6388            return;
 6389        }
 6390        let selections = self
 6391            .selections
 6392            .all::<usize>(cx)
 6393            .into_iter()
 6394            .map(|s| s.range());
 6395
 6396        self.transact(window, cx, |this, window, cx| {
 6397            this.buffer.update(cx, |buffer, cx| {
 6398                buffer.autoindent_ranges(selections, cx);
 6399            });
 6400            let selections = this.selections.all::<usize>(cx);
 6401            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6402                s.select(selections)
 6403            });
 6404        });
 6405    }
 6406
 6407    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6409        let selections = self.selections.all::<Point>(cx);
 6410
 6411        let mut new_cursors = Vec::new();
 6412        let mut edit_ranges = Vec::new();
 6413        let mut selections = selections.iter().peekable();
 6414        while let Some(selection) = selections.next() {
 6415            let mut rows = selection.spanned_rows(false, &display_map);
 6416            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6417
 6418            // Accumulate contiguous regions of rows that we want to delete.
 6419            while let Some(next_selection) = selections.peek() {
 6420                let next_rows = next_selection.spanned_rows(false, &display_map);
 6421                if next_rows.start <= rows.end {
 6422                    rows.end = next_rows.end;
 6423                    selections.next().unwrap();
 6424                } else {
 6425                    break;
 6426                }
 6427            }
 6428
 6429            let buffer = &display_map.buffer_snapshot;
 6430            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6431            let edit_end;
 6432            let cursor_buffer_row;
 6433            if buffer.max_point().row >= rows.end.0 {
 6434                // If there's a line after the range, delete the \n from the end of the row range
 6435                // and position the cursor on the next line.
 6436                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6437                cursor_buffer_row = rows.end;
 6438            } else {
 6439                // If there isn't a line after the range, delete the \n from the line before the
 6440                // start of the row range and position the cursor there.
 6441                edit_start = edit_start.saturating_sub(1);
 6442                edit_end = buffer.len();
 6443                cursor_buffer_row = rows.start.previous_row();
 6444            }
 6445
 6446            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6447            *cursor.column_mut() =
 6448                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6449
 6450            new_cursors.push((
 6451                selection.id,
 6452                buffer.anchor_after(cursor.to_point(&display_map)),
 6453            ));
 6454            edit_ranges.push(edit_start..edit_end);
 6455        }
 6456
 6457        self.transact(window, cx, |this, window, cx| {
 6458            let buffer = this.buffer.update(cx, |buffer, cx| {
 6459                let empty_str: Arc<str> = Arc::default();
 6460                buffer.edit(
 6461                    edit_ranges
 6462                        .into_iter()
 6463                        .map(|range| (range, empty_str.clone())),
 6464                    None,
 6465                    cx,
 6466                );
 6467                buffer.snapshot(cx)
 6468            });
 6469            let new_selections = new_cursors
 6470                .into_iter()
 6471                .map(|(id, cursor)| {
 6472                    let cursor = cursor.to_point(&buffer);
 6473                    Selection {
 6474                        id,
 6475                        start: cursor,
 6476                        end: cursor,
 6477                        reversed: false,
 6478                        goal: SelectionGoal::None,
 6479                    }
 6480                })
 6481                .collect();
 6482
 6483            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6484                s.select(new_selections);
 6485            });
 6486        });
 6487    }
 6488
 6489    pub fn join_lines_impl(
 6490        &mut self,
 6491        insert_whitespace: bool,
 6492        window: &mut Window,
 6493        cx: &mut Context<Self>,
 6494    ) {
 6495        if self.read_only(cx) {
 6496            return;
 6497        }
 6498        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6499        for selection in self.selections.all::<Point>(cx) {
 6500            let start = MultiBufferRow(selection.start.row);
 6501            // Treat single line selections as if they include the next line. Otherwise this action
 6502            // would do nothing for single line selections individual cursors.
 6503            let end = if selection.start.row == selection.end.row {
 6504                MultiBufferRow(selection.start.row + 1)
 6505            } else {
 6506                MultiBufferRow(selection.end.row)
 6507            };
 6508
 6509            if let Some(last_row_range) = row_ranges.last_mut() {
 6510                if start <= last_row_range.end {
 6511                    last_row_range.end = end;
 6512                    continue;
 6513                }
 6514            }
 6515            row_ranges.push(start..end);
 6516        }
 6517
 6518        let snapshot = self.buffer.read(cx).snapshot(cx);
 6519        let mut cursor_positions = Vec::new();
 6520        for row_range in &row_ranges {
 6521            let anchor = snapshot.anchor_before(Point::new(
 6522                row_range.end.previous_row().0,
 6523                snapshot.line_len(row_range.end.previous_row()),
 6524            ));
 6525            cursor_positions.push(anchor..anchor);
 6526        }
 6527
 6528        self.transact(window, cx, |this, window, cx| {
 6529            for row_range in row_ranges.into_iter().rev() {
 6530                for row in row_range.iter_rows().rev() {
 6531                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6532                    let next_line_row = row.next_row();
 6533                    let indent = snapshot.indent_size_for_line(next_line_row);
 6534                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6535
 6536                    let replace =
 6537                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6538                            " "
 6539                        } else {
 6540                            ""
 6541                        };
 6542
 6543                    this.buffer.update(cx, |buffer, cx| {
 6544                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6545                    });
 6546                }
 6547            }
 6548
 6549            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6550                s.select_anchor_ranges(cursor_positions)
 6551            });
 6552        });
 6553    }
 6554
 6555    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6556        self.join_lines_impl(true, window, cx);
 6557    }
 6558
 6559    pub fn sort_lines_case_sensitive(
 6560        &mut self,
 6561        _: &SortLinesCaseSensitive,
 6562        window: &mut Window,
 6563        cx: &mut Context<Self>,
 6564    ) {
 6565        self.manipulate_lines(window, cx, |lines| lines.sort())
 6566    }
 6567
 6568    pub fn sort_lines_case_insensitive(
 6569        &mut self,
 6570        _: &SortLinesCaseInsensitive,
 6571        window: &mut Window,
 6572        cx: &mut Context<Self>,
 6573    ) {
 6574        self.manipulate_lines(window, cx, |lines| {
 6575            lines.sort_by_key(|line| line.to_lowercase())
 6576        })
 6577    }
 6578
 6579    pub fn unique_lines_case_insensitive(
 6580        &mut self,
 6581        _: &UniqueLinesCaseInsensitive,
 6582        window: &mut Window,
 6583        cx: &mut Context<Self>,
 6584    ) {
 6585        self.manipulate_lines(window, cx, |lines| {
 6586            let mut seen = HashSet::default();
 6587            lines.retain(|line| seen.insert(line.to_lowercase()));
 6588        })
 6589    }
 6590
 6591    pub fn unique_lines_case_sensitive(
 6592        &mut self,
 6593        _: &UniqueLinesCaseSensitive,
 6594        window: &mut Window,
 6595        cx: &mut Context<Self>,
 6596    ) {
 6597        self.manipulate_lines(window, cx, |lines| {
 6598            let mut seen = HashSet::default();
 6599            lines.retain(|line| seen.insert(*line));
 6600        })
 6601    }
 6602
 6603    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6604        let mut revert_changes = HashMap::default();
 6605        let snapshot = self.snapshot(window, cx);
 6606        for hunk in snapshot
 6607            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6608        {
 6609            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6610        }
 6611        if !revert_changes.is_empty() {
 6612            self.transact(window, cx, |editor, window, cx| {
 6613                editor.revert(revert_changes, window, cx);
 6614            });
 6615        }
 6616    }
 6617
 6618    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6619        let Some(project) = self.project.clone() else {
 6620            return;
 6621        };
 6622        self.reload(project, window, cx)
 6623            .detach_and_notify_err(window, cx);
 6624    }
 6625
 6626    pub fn revert_selected_hunks(
 6627        &mut self,
 6628        _: &RevertSelectedHunks,
 6629        window: &mut Window,
 6630        cx: &mut Context<Self>,
 6631    ) {
 6632        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6633        self.revert_hunks_in_ranges(selections, window, cx);
 6634    }
 6635
 6636    fn revert_hunks_in_ranges(
 6637        &mut self,
 6638        ranges: impl Iterator<Item = Range<Point>>,
 6639        window: &mut Window,
 6640        cx: &mut Context<Editor>,
 6641    ) {
 6642        let mut revert_changes = HashMap::default();
 6643        let snapshot = self.snapshot(window, cx);
 6644        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6645            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6646        }
 6647        if !revert_changes.is_empty() {
 6648            self.transact(window, cx, |editor, window, cx| {
 6649                editor.revert(revert_changes, window, cx);
 6650            });
 6651        }
 6652    }
 6653
 6654    pub fn open_active_item_in_terminal(
 6655        &mut self,
 6656        _: &OpenInTerminal,
 6657        window: &mut Window,
 6658        cx: &mut Context<Self>,
 6659    ) {
 6660        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6661            let project_path = buffer.read(cx).project_path(cx)?;
 6662            let project = self.project.as_ref()?.read(cx);
 6663            let entry = project.entry_for_path(&project_path, cx)?;
 6664            let parent = match &entry.canonical_path {
 6665                Some(canonical_path) => canonical_path.to_path_buf(),
 6666                None => project.absolute_path(&project_path, cx)?,
 6667            }
 6668            .parent()?
 6669            .to_path_buf();
 6670            Some(parent)
 6671        }) {
 6672            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6673        }
 6674    }
 6675
 6676    pub fn prepare_revert_change(
 6677        &self,
 6678        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6679        hunk: &MultiBufferDiffHunk,
 6680        cx: &mut App,
 6681    ) -> Option<()> {
 6682        let buffer = self.buffer.read(cx);
 6683        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6684        let buffer = buffer.buffer(hunk.buffer_id)?;
 6685        let buffer = buffer.read(cx);
 6686        let original_text = change_set
 6687            .read(cx)
 6688            .base_text
 6689            .as_ref()?
 6690            .as_rope()
 6691            .slice(hunk.diff_base_byte_range.clone());
 6692        let buffer_snapshot = buffer.snapshot();
 6693        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6694        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6695            probe
 6696                .0
 6697                .start
 6698                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6699                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6700        }) {
 6701            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6702            Some(())
 6703        } else {
 6704            None
 6705        }
 6706    }
 6707
 6708    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6709        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6710    }
 6711
 6712    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6713        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6714    }
 6715
 6716    fn manipulate_lines<Fn>(
 6717        &mut self,
 6718        window: &mut Window,
 6719        cx: &mut Context<Self>,
 6720        mut callback: Fn,
 6721    ) where
 6722        Fn: FnMut(&mut Vec<&str>),
 6723    {
 6724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6725        let buffer = self.buffer.read(cx).snapshot(cx);
 6726
 6727        let mut edits = Vec::new();
 6728
 6729        let selections = self.selections.all::<Point>(cx);
 6730        let mut selections = selections.iter().peekable();
 6731        let mut contiguous_row_selections = Vec::new();
 6732        let mut new_selections = Vec::new();
 6733        let mut added_lines = 0;
 6734        let mut removed_lines = 0;
 6735
 6736        while let Some(selection) = selections.next() {
 6737            let (start_row, end_row) = consume_contiguous_rows(
 6738                &mut contiguous_row_selections,
 6739                selection,
 6740                &display_map,
 6741                &mut selections,
 6742            );
 6743
 6744            let start_point = Point::new(start_row.0, 0);
 6745            let end_point = Point::new(
 6746                end_row.previous_row().0,
 6747                buffer.line_len(end_row.previous_row()),
 6748            );
 6749            let text = buffer
 6750                .text_for_range(start_point..end_point)
 6751                .collect::<String>();
 6752
 6753            let mut lines = text.split('\n').collect_vec();
 6754
 6755            let lines_before = lines.len();
 6756            callback(&mut lines);
 6757            let lines_after = lines.len();
 6758
 6759            edits.push((start_point..end_point, lines.join("\n")));
 6760
 6761            // Selections must change based on added and removed line count
 6762            let start_row =
 6763                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6764            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6765            new_selections.push(Selection {
 6766                id: selection.id,
 6767                start: start_row,
 6768                end: end_row,
 6769                goal: SelectionGoal::None,
 6770                reversed: selection.reversed,
 6771            });
 6772
 6773            if lines_after > lines_before {
 6774                added_lines += lines_after - lines_before;
 6775            } else if lines_before > lines_after {
 6776                removed_lines += lines_before - lines_after;
 6777            }
 6778        }
 6779
 6780        self.transact(window, cx, |this, window, cx| {
 6781            let buffer = this.buffer.update(cx, |buffer, cx| {
 6782                buffer.edit(edits, None, cx);
 6783                buffer.snapshot(cx)
 6784            });
 6785
 6786            // Recalculate offsets on newly edited buffer
 6787            let new_selections = new_selections
 6788                .iter()
 6789                .map(|s| {
 6790                    let start_point = Point::new(s.start.0, 0);
 6791                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6792                    Selection {
 6793                        id: s.id,
 6794                        start: buffer.point_to_offset(start_point),
 6795                        end: buffer.point_to_offset(end_point),
 6796                        goal: s.goal,
 6797                        reversed: s.reversed,
 6798                    }
 6799                })
 6800                .collect();
 6801
 6802            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6803                s.select(new_selections);
 6804            });
 6805
 6806            this.request_autoscroll(Autoscroll::fit(), cx);
 6807        });
 6808    }
 6809
 6810    pub fn convert_to_upper_case(
 6811        &mut self,
 6812        _: &ConvertToUpperCase,
 6813        window: &mut Window,
 6814        cx: &mut Context<Self>,
 6815    ) {
 6816        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6817    }
 6818
 6819    pub fn convert_to_lower_case(
 6820        &mut self,
 6821        _: &ConvertToLowerCase,
 6822        window: &mut Window,
 6823        cx: &mut Context<Self>,
 6824    ) {
 6825        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6826    }
 6827
 6828    pub fn convert_to_title_case(
 6829        &mut self,
 6830        _: &ConvertToTitleCase,
 6831        window: &mut Window,
 6832        cx: &mut Context<Self>,
 6833    ) {
 6834        self.manipulate_text(window, cx, |text| {
 6835            text.split('\n')
 6836                .map(|line| line.to_case(Case::Title))
 6837                .join("\n")
 6838        })
 6839    }
 6840
 6841    pub fn convert_to_snake_case(
 6842        &mut self,
 6843        _: &ConvertToSnakeCase,
 6844        window: &mut Window,
 6845        cx: &mut Context<Self>,
 6846    ) {
 6847        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6848    }
 6849
 6850    pub fn convert_to_kebab_case(
 6851        &mut self,
 6852        _: &ConvertToKebabCase,
 6853        window: &mut Window,
 6854        cx: &mut Context<Self>,
 6855    ) {
 6856        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6857    }
 6858
 6859    pub fn convert_to_upper_camel_case(
 6860        &mut self,
 6861        _: &ConvertToUpperCamelCase,
 6862        window: &mut Window,
 6863        cx: &mut Context<Self>,
 6864    ) {
 6865        self.manipulate_text(window, cx, |text| {
 6866            text.split('\n')
 6867                .map(|line| line.to_case(Case::UpperCamel))
 6868                .join("\n")
 6869        })
 6870    }
 6871
 6872    pub fn convert_to_lower_camel_case(
 6873        &mut self,
 6874        _: &ConvertToLowerCamelCase,
 6875        window: &mut Window,
 6876        cx: &mut Context<Self>,
 6877    ) {
 6878        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6879    }
 6880
 6881    pub fn convert_to_opposite_case(
 6882        &mut self,
 6883        _: &ConvertToOppositeCase,
 6884        window: &mut Window,
 6885        cx: &mut Context<Self>,
 6886    ) {
 6887        self.manipulate_text(window, cx, |text| {
 6888            text.chars()
 6889                .fold(String::with_capacity(text.len()), |mut t, c| {
 6890                    if c.is_uppercase() {
 6891                        t.extend(c.to_lowercase());
 6892                    } else {
 6893                        t.extend(c.to_uppercase());
 6894                    }
 6895                    t
 6896                })
 6897        })
 6898    }
 6899
 6900    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6901    where
 6902        Fn: FnMut(&str) -> String,
 6903    {
 6904        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6905        let buffer = self.buffer.read(cx).snapshot(cx);
 6906
 6907        let mut new_selections = Vec::new();
 6908        let mut edits = Vec::new();
 6909        let mut selection_adjustment = 0i32;
 6910
 6911        for selection in self.selections.all::<usize>(cx) {
 6912            let selection_is_empty = selection.is_empty();
 6913
 6914            let (start, end) = if selection_is_empty {
 6915                let word_range = movement::surrounding_word(
 6916                    &display_map,
 6917                    selection.start.to_display_point(&display_map),
 6918                );
 6919                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6920                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6921                (start, end)
 6922            } else {
 6923                (selection.start, selection.end)
 6924            };
 6925
 6926            let text = buffer.text_for_range(start..end).collect::<String>();
 6927            let old_length = text.len() as i32;
 6928            let text = callback(&text);
 6929
 6930            new_selections.push(Selection {
 6931                start: (start as i32 - selection_adjustment) as usize,
 6932                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6933                goal: SelectionGoal::None,
 6934                ..selection
 6935            });
 6936
 6937            selection_adjustment += old_length - text.len() as i32;
 6938
 6939            edits.push((start..end, text));
 6940        }
 6941
 6942        self.transact(window, cx, |this, window, cx| {
 6943            this.buffer.update(cx, |buffer, cx| {
 6944                buffer.edit(edits, None, cx);
 6945            });
 6946
 6947            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6948                s.select(new_selections);
 6949            });
 6950
 6951            this.request_autoscroll(Autoscroll::fit(), cx);
 6952        });
 6953    }
 6954
 6955    pub fn duplicate(
 6956        &mut self,
 6957        upwards: bool,
 6958        whole_lines: bool,
 6959        window: &mut Window,
 6960        cx: &mut Context<Self>,
 6961    ) {
 6962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6963        let buffer = &display_map.buffer_snapshot;
 6964        let selections = self.selections.all::<Point>(cx);
 6965
 6966        let mut edits = Vec::new();
 6967        let mut selections_iter = selections.iter().peekable();
 6968        while let Some(selection) = selections_iter.next() {
 6969            let mut rows = selection.spanned_rows(false, &display_map);
 6970            // duplicate line-wise
 6971            if whole_lines || selection.start == selection.end {
 6972                // Avoid duplicating the same lines twice.
 6973                while let Some(next_selection) = selections_iter.peek() {
 6974                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6975                    if next_rows.start < rows.end {
 6976                        rows.end = next_rows.end;
 6977                        selections_iter.next().unwrap();
 6978                    } else {
 6979                        break;
 6980                    }
 6981                }
 6982
 6983                // Copy the text from the selected row region and splice it either at the start
 6984                // or end of the region.
 6985                let start = Point::new(rows.start.0, 0);
 6986                let end = Point::new(
 6987                    rows.end.previous_row().0,
 6988                    buffer.line_len(rows.end.previous_row()),
 6989                );
 6990                let text = buffer
 6991                    .text_for_range(start..end)
 6992                    .chain(Some("\n"))
 6993                    .collect::<String>();
 6994                let insert_location = if upwards {
 6995                    Point::new(rows.end.0, 0)
 6996                } else {
 6997                    start
 6998                };
 6999                edits.push((insert_location..insert_location, text));
 7000            } else {
 7001                // duplicate character-wise
 7002                let start = selection.start;
 7003                let end = selection.end;
 7004                let text = buffer.text_for_range(start..end).collect::<String>();
 7005                edits.push((selection.end..selection.end, text));
 7006            }
 7007        }
 7008
 7009        self.transact(window, cx, |this, _, cx| {
 7010            this.buffer.update(cx, |buffer, cx| {
 7011                buffer.edit(edits, None, cx);
 7012            });
 7013
 7014            this.request_autoscroll(Autoscroll::fit(), cx);
 7015        });
 7016    }
 7017
 7018    pub fn duplicate_line_up(
 7019        &mut self,
 7020        _: &DuplicateLineUp,
 7021        window: &mut Window,
 7022        cx: &mut Context<Self>,
 7023    ) {
 7024        self.duplicate(true, true, window, cx);
 7025    }
 7026
 7027    pub fn duplicate_line_down(
 7028        &mut self,
 7029        _: &DuplicateLineDown,
 7030        window: &mut Window,
 7031        cx: &mut Context<Self>,
 7032    ) {
 7033        self.duplicate(false, true, window, cx);
 7034    }
 7035
 7036    pub fn duplicate_selection(
 7037        &mut self,
 7038        _: &DuplicateSelection,
 7039        window: &mut Window,
 7040        cx: &mut Context<Self>,
 7041    ) {
 7042        self.duplicate(false, false, window, cx);
 7043    }
 7044
 7045    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7046        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7047        let buffer = self.buffer.read(cx).snapshot(cx);
 7048
 7049        let mut edits = Vec::new();
 7050        let mut unfold_ranges = Vec::new();
 7051        let mut refold_creases = Vec::new();
 7052
 7053        let selections = self.selections.all::<Point>(cx);
 7054        let mut selections = selections.iter().peekable();
 7055        let mut contiguous_row_selections = Vec::new();
 7056        let mut new_selections = Vec::new();
 7057
 7058        while let Some(selection) = selections.next() {
 7059            // Find all the selections that span a contiguous row range
 7060            let (start_row, end_row) = consume_contiguous_rows(
 7061                &mut contiguous_row_selections,
 7062                selection,
 7063                &display_map,
 7064                &mut selections,
 7065            );
 7066
 7067            // Move the text spanned by the row range to be before the line preceding the row range
 7068            if start_row.0 > 0 {
 7069                let range_to_move = Point::new(
 7070                    start_row.previous_row().0,
 7071                    buffer.line_len(start_row.previous_row()),
 7072                )
 7073                    ..Point::new(
 7074                        end_row.previous_row().0,
 7075                        buffer.line_len(end_row.previous_row()),
 7076                    );
 7077                let insertion_point = display_map
 7078                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7079                    .0;
 7080
 7081                // Don't move lines across excerpts
 7082                if buffer
 7083                    .excerpt_containing(insertion_point..range_to_move.end)
 7084                    .is_some()
 7085                {
 7086                    let text = buffer
 7087                        .text_for_range(range_to_move.clone())
 7088                        .flat_map(|s| s.chars())
 7089                        .skip(1)
 7090                        .chain(['\n'])
 7091                        .collect::<String>();
 7092
 7093                    edits.push((
 7094                        buffer.anchor_after(range_to_move.start)
 7095                            ..buffer.anchor_before(range_to_move.end),
 7096                        String::new(),
 7097                    ));
 7098                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7099                    edits.push((insertion_anchor..insertion_anchor, text));
 7100
 7101                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7102
 7103                    // Move selections up
 7104                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7105                        |mut selection| {
 7106                            selection.start.row -= row_delta;
 7107                            selection.end.row -= row_delta;
 7108                            selection
 7109                        },
 7110                    ));
 7111
 7112                    // Move folds up
 7113                    unfold_ranges.push(range_to_move.clone());
 7114                    for fold in display_map.folds_in_range(
 7115                        buffer.anchor_before(range_to_move.start)
 7116                            ..buffer.anchor_after(range_to_move.end),
 7117                    ) {
 7118                        let mut start = fold.range.start.to_point(&buffer);
 7119                        let mut end = fold.range.end.to_point(&buffer);
 7120                        start.row -= row_delta;
 7121                        end.row -= row_delta;
 7122                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7123                    }
 7124                }
 7125            }
 7126
 7127            // If we didn't move line(s), preserve the existing selections
 7128            new_selections.append(&mut contiguous_row_selections);
 7129        }
 7130
 7131        self.transact(window, cx, |this, window, cx| {
 7132            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7133            this.buffer.update(cx, |buffer, cx| {
 7134                for (range, text) in edits {
 7135                    buffer.edit([(range, text)], None, cx);
 7136                }
 7137            });
 7138            this.fold_creases(refold_creases, true, window, cx);
 7139            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7140                s.select(new_selections);
 7141            })
 7142        });
 7143    }
 7144
 7145    pub fn move_line_down(
 7146        &mut self,
 7147        _: &MoveLineDown,
 7148        window: &mut Window,
 7149        cx: &mut Context<Self>,
 7150    ) {
 7151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7152        let buffer = self.buffer.read(cx).snapshot(cx);
 7153
 7154        let mut edits = Vec::new();
 7155        let mut unfold_ranges = Vec::new();
 7156        let mut refold_creases = Vec::new();
 7157
 7158        let selections = self.selections.all::<Point>(cx);
 7159        let mut selections = selections.iter().peekable();
 7160        let mut contiguous_row_selections = Vec::new();
 7161        let mut new_selections = Vec::new();
 7162
 7163        while let Some(selection) = selections.next() {
 7164            // Find all the selections that span a contiguous row range
 7165            let (start_row, end_row) = consume_contiguous_rows(
 7166                &mut contiguous_row_selections,
 7167                selection,
 7168                &display_map,
 7169                &mut selections,
 7170            );
 7171
 7172            // Move the text spanned by the row range to be after the last line of the row range
 7173            if end_row.0 <= buffer.max_point().row {
 7174                let range_to_move =
 7175                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7176                let insertion_point = display_map
 7177                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7178                    .0;
 7179
 7180                // Don't move lines across excerpt boundaries
 7181                if buffer
 7182                    .excerpt_containing(range_to_move.start..insertion_point)
 7183                    .is_some()
 7184                {
 7185                    let mut text = String::from("\n");
 7186                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7187                    text.pop(); // Drop trailing newline
 7188                    edits.push((
 7189                        buffer.anchor_after(range_to_move.start)
 7190                            ..buffer.anchor_before(range_to_move.end),
 7191                        String::new(),
 7192                    ));
 7193                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7194                    edits.push((insertion_anchor..insertion_anchor, text));
 7195
 7196                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7197
 7198                    // Move selections down
 7199                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7200                        |mut selection| {
 7201                            selection.start.row += row_delta;
 7202                            selection.end.row += row_delta;
 7203                            selection
 7204                        },
 7205                    ));
 7206
 7207                    // Move folds down
 7208                    unfold_ranges.push(range_to_move.clone());
 7209                    for fold in display_map.folds_in_range(
 7210                        buffer.anchor_before(range_to_move.start)
 7211                            ..buffer.anchor_after(range_to_move.end),
 7212                    ) {
 7213                        let mut start = fold.range.start.to_point(&buffer);
 7214                        let mut end = fold.range.end.to_point(&buffer);
 7215                        start.row += row_delta;
 7216                        end.row += row_delta;
 7217                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7218                    }
 7219                }
 7220            }
 7221
 7222            // If we didn't move line(s), preserve the existing selections
 7223            new_selections.append(&mut contiguous_row_selections);
 7224        }
 7225
 7226        self.transact(window, cx, |this, window, cx| {
 7227            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7228            this.buffer.update(cx, |buffer, cx| {
 7229                for (range, text) in edits {
 7230                    buffer.edit([(range, text)], None, cx);
 7231                }
 7232            });
 7233            this.fold_creases(refold_creases, true, window, cx);
 7234            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7235                s.select(new_selections)
 7236            });
 7237        });
 7238    }
 7239
 7240    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7241        let text_layout_details = &self.text_layout_details(window);
 7242        self.transact(window, cx, |this, window, cx| {
 7243            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7244                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7245                let line_mode = s.line_mode;
 7246                s.move_with(|display_map, selection| {
 7247                    if !selection.is_empty() || line_mode {
 7248                        return;
 7249                    }
 7250
 7251                    let mut head = selection.head();
 7252                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7253                    if head.column() == display_map.line_len(head.row()) {
 7254                        transpose_offset = display_map
 7255                            .buffer_snapshot
 7256                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7257                    }
 7258
 7259                    if transpose_offset == 0 {
 7260                        return;
 7261                    }
 7262
 7263                    *head.column_mut() += 1;
 7264                    head = display_map.clip_point(head, Bias::Right);
 7265                    let goal = SelectionGoal::HorizontalPosition(
 7266                        display_map
 7267                            .x_for_display_point(head, text_layout_details)
 7268                            .into(),
 7269                    );
 7270                    selection.collapse_to(head, goal);
 7271
 7272                    let transpose_start = display_map
 7273                        .buffer_snapshot
 7274                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7275                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7276                        let transpose_end = display_map
 7277                            .buffer_snapshot
 7278                            .clip_offset(transpose_offset + 1, Bias::Right);
 7279                        if let Some(ch) =
 7280                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7281                        {
 7282                            edits.push((transpose_start..transpose_offset, String::new()));
 7283                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7284                        }
 7285                    }
 7286                });
 7287                edits
 7288            });
 7289            this.buffer
 7290                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7291            let selections = this.selections.all::<usize>(cx);
 7292            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7293                s.select(selections);
 7294            });
 7295        });
 7296    }
 7297
 7298    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7299        self.rewrap_impl(IsVimMode::No, cx)
 7300    }
 7301
 7302    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7303        let buffer = self.buffer.read(cx).snapshot(cx);
 7304        let selections = self.selections.all::<Point>(cx);
 7305        let mut selections = selections.iter().peekable();
 7306
 7307        let mut edits = Vec::new();
 7308        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7309
 7310        while let Some(selection) = selections.next() {
 7311            let mut start_row = selection.start.row;
 7312            let mut end_row = selection.end.row;
 7313
 7314            // Skip selections that overlap with a range that has already been rewrapped.
 7315            let selection_range = start_row..end_row;
 7316            if rewrapped_row_ranges
 7317                .iter()
 7318                .any(|range| range.overlaps(&selection_range))
 7319            {
 7320                continue;
 7321            }
 7322
 7323            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7324
 7325            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7326                match language_scope.language_name().as_ref() {
 7327                    "Markdown" | "Plain Text" => {
 7328                        should_rewrap = true;
 7329                    }
 7330                    _ => {}
 7331                }
 7332            }
 7333
 7334            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7335
 7336            // Since not all lines in the selection may be at the same indent
 7337            // level, choose the indent size that is the most common between all
 7338            // of the lines.
 7339            //
 7340            // If there is a tie, we use the deepest indent.
 7341            let (indent_size, indent_end) = {
 7342                let mut indent_size_occurrences = HashMap::default();
 7343                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7344
 7345                for row in start_row..=end_row {
 7346                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7347                    rows_by_indent_size.entry(indent).or_default().push(row);
 7348                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7349                }
 7350
 7351                let indent_size = indent_size_occurrences
 7352                    .into_iter()
 7353                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7354                    .map(|(indent, _)| indent)
 7355                    .unwrap_or_default();
 7356                let row = rows_by_indent_size[&indent_size][0];
 7357                let indent_end = Point::new(row, indent_size.len);
 7358
 7359                (indent_size, indent_end)
 7360            };
 7361
 7362            let mut line_prefix = indent_size.chars().collect::<String>();
 7363
 7364            if let Some(comment_prefix) =
 7365                buffer
 7366                    .language_scope_at(selection.head())
 7367                    .and_then(|language| {
 7368                        language
 7369                            .line_comment_prefixes()
 7370                            .iter()
 7371                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7372                            .cloned()
 7373                    })
 7374            {
 7375                line_prefix.push_str(&comment_prefix);
 7376                should_rewrap = true;
 7377            }
 7378
 7379            if !should_rewrap {
 7380                continue;
 7381            }
 7382
 7383            if selection.is_empty() {
 7384                'expand_upwards: while start_row > 0 {
 7385                    let prev_row = start_row - 1;
 7386                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7387                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7388                    {
 7389                        start_row = prev_row;
 7390                    } else {
 7391                        break 'expand_upwards;
 7392                    }
 7393                }
 7394
 7395                'expand_downwards: while end_row < buffer.max_point().row {
 7396                    let next_row = end_row + 1;
 7397                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7398                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7399                    {
 7400                        end_row = next_row;
 7401                    } else {
 7402                        break 'expand_downwards;
 7403                    }
 7404                }
 7405            }
 7406
 7407            let start = Point::new(start_row, 0);
 7408            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7409            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7410            let Some(lines_without_prefixes) = selection_text
 7411                .lines()
 7412                .map(|line| {
 7413                    line.strip_prefix(&line_prefix)
 7414                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7415                        .ok_or_else(|| {
 7416                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7417                        })
 7418                })
 7419                .collect::<Result<Vec<_>, _>>()
 7420                .log_err()
 7421            else {
 7422                continue;
 7423            };
 7424
 7425            let wrap_column = buffer
 7426                .settings_at(Point::new(start_row, 0), cx)
 7427                .preferred_line_length as usize;
 7428            let wrapped_text = wrap_with_prefix(
 7429                line_prefix,
 7430                lines_without_prefixes.join(" "),
 7431                wrap_column,
 7432                tab_size,
 7433            );
 7434
 7435            // TODO: should always use char-based diff while still supporting cursor behavior that
 7436            // matches vim.
 7437            let diff = match is_vim_mode {
 7438                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7439                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7440            };
 7441            let mut offset = start.to_offset(&buffer);
 7442            let mut moved_since_edit = true;
 7443
 7444            for change in diff.iter_all_changes() {
 7445                let value = change.value();
 7446                match change.tag() {
 7447                    ChangeTag::Equal => {
 7448                        offset += value.len();
 7449                        moved_since_edit = true;
 7450                    }
 7451                    ChangeTag::Delete => {
 7452                        let start = buffer.anchor_after(offset);
 7453                        let end = buffer.anchor_before(offset + value.len());
 7454
 7455                        if moved_since_edit {
 7456                            edits.push((start..end, String::new()));
 7457                        } else {
 7458                            edits.last_mut().unwrap().0.end = end;
 7459                        }
 7460
 7461                        offset += value.len();
 7462                        moved_since_edit = false;
 7463                    }
 7464                    ChangeTag::Insert => {
 7465                        if moved_since_edit {
 7466                            let anchor = buffer.anchor_after(offset);
 7467                            edits.push((anchor..anchor, value.to_string()));
 7468                        } else {
 7469                            edits.last_mut().unwrap().1.push_str(value);
 7470                        }
 7471
 7472                        moved_since_edit = false;
 7473                    }
 7474                }
 7475            }
 7476
 7477            rewrapped_row_ranges.push(start_row..=end_row);
 7478        }
 7479
 7480        self.buffer
 7481            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7482    }
 7483
 7484    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7485        let mut text = String::new();
 7486        let buffer = self.buffer.read(cx).snapshot(cx);
 7487        let mut selections = self.selections.all::<Point>(cx);
 7488        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7489        {
 7490            let max_point = buffer.max_point();
 7491            let mut is_first = true;
 7492            for selection in &mut selections {
 7493                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7494                if is_entire_line {
 7495                    selection.start = Point::new(selection.start.row, 0);
 7496                    if !selection.is_empty() && selection.end.column == 0 {
 7497                        selection.end = cmp::min(max_point, selection.end);
 7498                    } else {
 7499                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7500                    }
 7501                    selection.goal = SelectionGoal::None;
 7502                }
 7503                if is_first {
 7504                    is_first = false;
 7505                } else {
 7506                    text += "\n";
 7507                }
 7508                let mut len = 0;
 7509                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7510                    text.push_str(chunk);
 7511                    len += chunk.len();
 7512                }
 7513                clipboard_selections.push(ClipboardSelection {
 7514                    len,
 7515                    is_entire_line,
 7516                    first_line_indent: buffer
 7517                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7518                        .len,
 7519                });
 7520            }
 7521        }
 7522
 7523        self.transact(window, cx, |this, window, cx| {
 7524            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7525                s.select(selections);
 7526            });
 7527            this.insert("", window, cx);
 7528        });
 7529        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7530    }
 7531
 7532    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7533        let item = self.cut_common(window, cx);
 7534        cx.write_to_clipboard(item);
 7535    }
 7536
 7537    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7538        self.change_selections(None, window, cx, |s| {
 7539            s.move_with(|snapshot, sel| {
 7540                if sel.is_empty() {
 7541                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7542                }
 7543            });
 7544        });
 7545        let item = self.cut_common(window, cx);
 7546        cx.set_global(KillRing(item))
 7547    }
 7548
 7549    pub fn kill_ring_yank(
 7550        &mut self,
 7551        _: &KillRingYank,
 7552        window: &mut Window,
 7553        cx: &mut Context<Self>,
 7554    ) {
 7555        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7556            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7557                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7558            } else {
 7559                return;
 7560            }
 7561        } else {
 7562            return;
 7563        };
 7564        self.do_paste(&text, metadata, false, window, cx);
 7565    }
 7566
 7567    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7568        let selections = self.selections.all::<Point>(cx);
 7569        let buffer = self.buffer.read(cx).read(cx);
 7570        let mut text = String::new();
 7571
 7572        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7573        {
 7574            let max_point = buffer.max_point();
 7575            let mut is_first = true;
 7576            for selection in selections.iter() {
 7577                let mut start = selection.start;
 7578                let mut end = selection.end;
 7579                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7580                if is_entire_line {
 7581                    start = Point::new(start.row, 0);
 7582                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7583                }
 7584                if is_first {
 7585                    is_first = false;
 7586                } else {
 7587                    text += "\n";
 7588                }
 7589                let mut len = 0;
 7590                for chunk in buffer.text_for_range(start..end) {
 7591                    text.push_str(chunk);
 7592                    len += chunk.len();
 7593                }
 7594                clipboard_selections.push(ClipboardSelection {
 7595                    len,
 7596                    is_entire_line,
 7597                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7598                });
 7599            }
 7600        }
 7601
 7602        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7603            text,
 7604            clipboard_selections,
 7605        ));
 7606    }
 7607
 7608    pub fn do_paste(
 7609        &mut self,
 7610        text: &String,
 7611        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7612        handle_entire_lines: bool,
 7613        window: &mut Window,
 7614        cx: &mut Context<Self>,
 7615    ) {
 7616        if self.read_only(cx) {
 7617            return;
 7618        }
 7619
 7620        let clipboard_text = Cow::Borrowed(text);
 7621
 7622        self.transact(window, cx, |this, window, cx| {
 7623            if let Some(mut clipboard_selections) = clipboard_selections {
 7624                let old_selections = this.selections.all::<usize>(cx);
 7625                let all_selections_were_entire_line =
 7626                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7627                let first_selection_indent_column =
 7628                    clipboard_selections.first().map(|s| s.first_line_indent);
 7629                if clipboard_selections.len() != old_selections.len() {
 7630                    clipboard_selections.drain(..);
 7631                }
 7632                let cursor_offset = this.selections.last::<usize>(cx).head();
 7633                let mut auto_indent_on_paste = true;
 7634
 7635                this.buffer.update(cx, |buffer, cx| {
 7636                    let snapshot = buffer.read(cx);
 7637                    auto_indent_on_paste =
 7638                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7639
 7640                    let mut start_offset = 0;
 7641                    let mut edits = Vec::new();
 7642                    let mut original_indent_columns = Vec::new();
 7643                    for (ix, selection) in old_selections.iter().enumerate() {
 7644                        let to_insert;
 7645                        let entire_line;
 7646                        let original_indent_column;
 7647                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7648                            let end_offset = start_offset + clipboard_selection.len;
 7649                            to_insert = &clipboard_text[start_offset..end_offset];
 7650                            entire_line = clipboard_selection.is_entire_line;
 7651                            start_offset = end_offset + 1;
 7652                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7653                        } else {
 7654                            to_insert = clipboard_text.as_str();
 7655                            entire_line = all_selections_were_entire_line;
 7656                            original_indent_column = first_selection_indent_column
 7657                        }
 7658
 7659                        // If the corresponding selection was empty when this slice of the
 7660                        // clipboard text was written, then the entire line containing the
 7661                        // selection was copied. If this selection is also currently empty,
 7662                        // then paste the line before the current line of the buffer.
 7663                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7664                            let column = selection.start.to_point(&snapshot).column as usize;
 7665                            let line_start = selection.start - column;
 7666                            line_start..line_start
 7667                        } else {
 7668                            selection.range()
 7669                        };
 7670
 7671                        edits.push((range, to_insert));
 7672                        original_indent_columns.extend(original_indent_column);
 7673                    }
 7674                    drop(snapshot);
 7675
 7676                    buffer.edit(
 7677                        edits,
 7678                        if auto_indent_on_paste {
 7679                            Some(AutoindentMode::Block {
 7680                                original_indent_columns,
 7681                            })
 7682                        } else {
 7683                            None
 7684                        },
 7685                        cx,
 7686                    );
 7687                });
 7688
 7689                let selections = this.selections.all::<usize>(cx);
 7690                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7691                    s.select(selections)
 7692                });
 7693            } else {
 7694                this.insert(&clipboard_text, window, cx);
 7695            }
 7696        });
 7697    }
 7698
 7699    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7700        if let Some(item) = cx.read_from_clipboard() {
 7701            let entries = item.entries();
 7702
 7703            match entries.first() {
 7704                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7705                // of all the pasted entries.
 7706                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7707                    .do_paste(
 7708                        clipboard_string.text(),
 7709                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7710                        true,
 7711                        window,
 7712                        cx,
 7713                    ),
 7714                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7715            }
 7716        }
 7717    }
 7718
 7719    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7720        if self.read_only(cx) {
 7721            return;
 7722        }
 7723
 7724        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7725            if let Some((selections, _)) =
 7726                self.selection_history.transaction(transaction_id).cloned()
 7727            {
 7728                self.change_selections(None, window, cx, |s| {
 7729                    s.select_anchors(selections.to_vec());
 7730                });
 7731            }
 7732            self.request_autoscroll(Autoscroll::fit(), cx);
 7733            self.unmark_text(window, cx);
 7734            self.refresh_inline_completion(true, false, window, cx);
 7735            cx.emit(EditorEvent::Edited { transaction_id });
 7736            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7737        }
 7738    }
 7739
 7740    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7741        if self.read_only(cx) {
 7742            return;
 7743        }
 7744
 7745        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7746            if let Some((_, Some(selections))) =
 7747                self.selection_history.transaction(transaction_id).cloned()
 7748            {
 7749                self.change_selections(None, window, cx, |s| {
 7750                    s.select_anchors(selections.to_vec());
 7751                });
 7752            }
 7753            self.request_autoscroll(Autoscroll::fit(), cx);
 7754            self.unmark_text(window, cx);
 7755            self.refresh_inline_completion(true, false, window, cx);
 7756            cx.emit(EditorEvent::Edited { transaction_id });
 7757        }
 7758    }
 7759
 7760    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7761        self.buffer
 7762            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7763    }
 7764
 7765    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7766        self.buffer
 7767            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7768    }
 7769
 7770    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7771        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7772            let line_mode = s.line_mode;
 7773            s.move_with(|map, selection| {
 7774                let cursor = if selection.is_empty() && !line_mode {
 7775                    movement::left(map, selection.start)
 7776                } else {
 7777                    selection.start
 7778                };
 7779                selection.collapse_to(cursor, SelectionGoal::None);
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7785        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7786            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7787        })
 7788    }
 7789
 7790    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7791        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7792            let line_mode = s.line_mode;
 7793            s.move_with(|map, selection| {
 7794                let cursor = if selection.is_empty() && !line_mode {
 7795                    movement::right(map, selection.end)
 7796                } else {
 7797                    selection.end
 7798                };
 7799                selection.collapse_to(cursor, SelectionGoal::None)
 7800            });
 7801        })
 7802    }
 7803
 7804    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7806            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7807        })
 7808    }
 7809
 7810    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7811        if self.take_rename(true, window, cx).is_some() {
 7812            return;
 7813        }
 7814
 7815        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7816            cx.propagate();
 7817            return;
 7818        }
 7819
 7820        let text_layout_details = &self.text_layout_details(window);
 7821        let selection_count = self.selections.count();
 7822        let first_selection = self.selections.first_anchor();
 7823
 7824        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7825            let line_mode = s.line_mode;
 7826            s.move_with(|map, selection| {
 7827                if !selection.is_empty() && !line_mode {
 7828                    selection.goal = SelectionGoal::None;
 7829                }
 7830                let (cursor, goal) = movement::up(
 7831                    map,
 7832                    selection.start,
 7833                    selection.goal,
 7834                    false,
 7835                    text_layout_details,
 7836                );
 7837                selection.collapse_to(cursor, goal);
 7838            });
 7839        });
 7840
 7841        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7842        {
 7843            cx.propagate();
 7844        }
 7845    }
 7846
 7847    pub fn move_up_by_lines(
 7848        &mut self,
 7849        action: &MoveUpByLines,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        if self.take_rename(true, window, cx).is_some() {
 7854            return;
 7855        }
 7856
 7857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7858            cx.propagate();
 7859            return;
 7860        }
 7861
 7862        let text_layout_details = &self.text_layout_details(window);
 7863
 7864        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7865            let line_mode = s.line_mode;
 7866            s.move_with(|map, selection| {
 7867                if !selection.is_empty() && !line_mode {
 7868                    selection.goal = SelectionGoal::None;
 7869                }
 7870                let (cursor, goal) = movement::up_by_rows(
 7871                    map,
 7872                    selection.start,
 7873                    action.lines,
 7874                    selection.goal,
 7875                    false,
 7876                    text_layout_details,
 7877                );
 7878                selection.collapse_to(cursor, goal);
 7879            });
 7880        })
 7881    }
 7882
 7883    pub fn move_down_by_lines(
 7884        &mut self,
 7885        action: &MoveDownByLines,
 7886        window: &mut Window,
 7887        cx: &mut Context<Self>,
 7888    ) {
 7889        if self.take_rename(true, window, cx).is_some() {
 7890            return;
 7891        }
 7892
 7893        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7894            cx.propagate();
 7895            return;
 7896        }
 7897
 7898        let text_layout_details = &self.text_layout_details(window);
 7899
 7900        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7901            let line_mode = s.line_mode;
 7902            s.move_with(|map, selection| {
 7903                if !selection.is_empty() && !line_mode {
 7904                    selection.goal = SelectionGoal::None;
 7905                }
 7906                let (cursor, goal) = movement::down_by_rows(
 7907                    map,
 7908                    selection.start,
 7909                    action.lines,
 7910                    selection.goal,
 7911                    false,
 7912                    text_layout_details,
 7913                );
 7914                selection.collapse_to(cursor, goal);
 7915            });
 7916        })
 7917    }
 7918
 7919    pub fn select_down_by_lines(
 7920        &mut self,
 7921        action: &SelectDownByLines,
 7922        window: &mut Window,
 7923        cx: &mut Context<Self>,
 7924    ) {
 7925        let text_layout_details = &self.text_layout_details(window);
 7926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7927            s.move_heads_with(|map, head, goal| {
 7928                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7929            })
 7930        })
 7931    }
 7932
 7933    pub fn select_up_by_lines(
 7934        &mut self,
 7935        action: &SelectUpByLines,
 7936        window: &mut Window,
 7937        cx: &mut Context<Self>,
 7938    ) {
 7939        let text_layout_details = &self.text_layout_details(window);
 7940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7941            s.move_heads_with(|map, head, goal| {
 7942                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7943            })
 7944        })
 7945    }
 7946
 7947    pub fn select_page_up(
 7948        &mut self,
 7949        _: &SelectPageUp,
 7950        window: &mut Window,
 7951        cx: &mut Context<Self>,
 7952    ) {
 7953        let Some(row_count) = self.visible_row_count() else {
 7954            return;
 7955        };
 7956
 7957        let text_layout_details = &self.text_layout_details(window);
 7958
 7959        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7960            s.move_heads_with(|map, head, goal| {
 7961                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7962            })
 7963        })
 7964    }
 7965
 7966    pub fn move_page_up(
 7967        &mut self,
 7968        action: &MovePageUp,
 7969        window: &mut Window,
 7970        cx: &mut Context<Self>,
 7971    ) {
 7972        if self.take_rename(true, window, cx).is_some() {
 7973            return;
 7974        }
 7975
 7976        if self
 7977            .context_menu
 7978            .borrow_mut()
 7979            .as_mut()
 7980            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7981            .unwrap_or(false)
 7982        {
 7983            return;
 7984        }
 7985
 7986        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7987            cx.propagate();
 7988            return;
 7989        }
 7990
 7991        let Some(row_count) = self.visible_row_count() else {
 7992            return;
 7993        };
 7994
 7995        let autoscroll = if action.center_cursor {
 7996            Autoscroll::center()
 7997        } else {
 7998            Autoscroll::fit()
 7999        };
 8000
 8001        let text_layout_details = &self.text_layout_details(window);
 8002
 8003        self.change_selections(Some(autoscroll), window, cx, |s| {
 8004            let line_mode = s.line_mode;
 8005            s.move_with(|map, selection| {
 8006                if !selection.is_empty() && !line_mode {
 8007                    selection.goal = SelectionGoal::None;
 8008                }
 8009                let (cursor, goal) = movement::up_by_rows(
 8010                    map,
 8011                    selection.end,
 8012                    row_count,
 8013                    selection.goal,
 8014                    false,
 8015                    text_layout_details,
 8016                );
 8017                selection.collapse_to(cursor, goal);
 8018            });
 8019        });
 8020    }
 8021
 8022    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8023        let text_layout_details = &self.text_layout_details(window);
 8024        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8025            s.move_heads_with(|map, head, goal| {
 8026                movement::up(map, head, goal, false, text_layout_details)
 8027            })
 8028        })
 8029    }
 8030
 8031    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8032        self.take_rename(true, window, cx);
 8033
 8034        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8035            cx.propagate();
 8036            return;
 8037        }
 8038
 8039        let text_layout_details = &self.text_layout_details(window);
 8040        let selection_count = self.selections.count();
 8041        let first_selection = self.selections.first_anchor();
 8042
 8043        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8044            let line_mode = s.line_mode;
 8045            s.move_with(|map, selection| {
 8046                if !selection.is_empty() && !line_mode {
 8047                    selection.goal = SelectionGoal::None;
 8048                }
 8049                let (cursor, goal) = movement::down(
 8050                    map,
 8051                    selection.end,
 8052                    selection.goal,
 8053                    false,
 8054                    text_layout_details,
 8055                );
 8056                selection.collapse_to(cursor, goal);
 8057            });
 8058        });
 8059
 8060        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8061        {
 8062            cx.propagate();
 8063        }
 8064    }
 8065
 8066    pub fn select_page_down(
 8067        &mut self,
 8068        _: &SelectPageDown,
 8069        window: &mut Window,
 8070        cx: &mut Context<Self>,
 8071    ) {
 8072        let Some(row_count) = self.visible_row_count() else {
 8073            return;
 8074        };
 8075
 8076        let text_layout_details = &self.text_layout_details(window);
 8077
 8078        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8079            s.move_heads_with(|map, head, goal| {
 8080                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8081            })
 8082        })
 8083    }
 8084
 8085    pub fn move_page_down(
 8086        &mut self,
 8087        action: &MovePageDown,
 8088        window: &mut Window,
 8089        cx: &mut Context<Self>,
 8090    ) {
 8091        if self.take_rename(true, window, cx).is_some() {
 8092            return;
 8093        }
 8094
 8095        if self
 8096            .context_menu
 8097            .borrow_mut()
 8098            .as_mut()
 8099            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8100            .unwrap_or(false)
 8101        {
 8102            return;
 8103        }
 8104
 8105        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8106            cx.propagate();
 8107            return;
 8108        }
 8109
 8110        let Some(row_count) = self.visible_row_count() else {
 8111            return;
 8112        };
 8113
 8114        let autoscroll = if action.center_cursor {
 8115            Autoscroll::center()
 8116        } else {
 8117            Autoscroll::fit()
 8118        };
 8119
 8120        let text_layout_details = &self.text_layout_details(window);
 8121        self.change_selections(Some(autoscroll), window, cx, |s| {
 8122            let line_mode = s.line_mode;
 8123            s.move_with(|map, selection| {
 8124                if !selection.is_empty() && !line_mode {
 8125                    selection.goal = SelectionGoal::None;
 8126                }
 8127                let (cursor, goal) = movement::down_by_rows(
 8128                    map,
 8129                    selection.end,
 8130                    row_count,
 8131                    selection.goal,
 8132                    false,
 8133                    text_layout_details,
 8134                );
 8135                selection.collapse_to(cursor, goal);
 8136            });
 8137        });
 8138    }
 8139
 8140    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8141        let text_layout_details = &self.text_layout_details(window);
 8142        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8143            s.move_heads_with(|map, head, goal| {
 8144                movement::down(map, head, goal, false, text_layout_details)
 8145            })
 8146        });
 8147    }
 8148
 8149    pub fn context_menu_first(
 8150        &mut self,
 8151        _: &ContextMenuFirst,
 8152        _window: &mut Window,
 8153        cx: &mut Context<Self>,
 8154    ) {
 8155        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8156            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8157        }
 8158    }
 8159
 8160    pub fn context_menu_prev(
 8161        &mut self,
 8162        _: &ContextMenuPrev,
 8163        _window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) {
 8166        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8167            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8168        }
 8169    }
 8170
 8171    pub fn context_menu_next(
 8172        &mut self,
 8173        _: &ContextMenuNext,
 8174        _window: &mut Window,
 8175        cx: &mut Context<Self>,
 8176    ) {
 8177        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8178            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8179        }
 8180    }
 8181
 8182    pub fn context_menu_last(
 8183        &mut self,
 8184        _: &ContextMenuLast,
 8185        _window: &mut Window,
 8186        cx: &mut Context<Self>,
 8187    ) {
 8188        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8189            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8190        }
 8191    }
 8192
 8193    pub fn move_to_previous_word_start(
 8194        &mut self,
 8195        _: &MoveToPreviousWordStart,
 8196        window: &mut Window,
 8197        cx: &mut Context<Self>,
 8198    ) {
 8199        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8200            s.move_cursors_with(|map, head, _| {
 8201                (
 8202                    movement::previous_word_start(map, head),
 8203                    SelectionGoal::None,
 8204                )
 8205            });
 8206        })
 8207    }
 8208
 8209    pub fn move_to_previous_subword_start(
 8210        &mut self,
 8211        _: &MoveToPreviousSubwordStart,
 8212        window: &mut Window,
 8213        cx: &mut Context<Self>,
 8214    ) {
 8215        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8216            s.move_cursors_with(|map, head, _| {
 8217                (
 8218                    movement::previous_subword_start(map, head),
 8219                    SelectionGoal::None,
 8220                )
 8221            });
 8222        })
 8223    }
 8224
 8225    pub fn select_to_previous_word_start(
 8226        &mut self,
 8227        _: &SelectToPreviousWordStart,
 8228        window: &mut Window,
 8229        cx: &mut Context<Self>,
 8230    ) {
 8231        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8232            s.move_heads_with(|map, head, _| {
 8233                (
 8234                    movement::previous_word_start(map, head),
 8235                    SelectionGoal::None,
 8236                )
 8237            });
 8238        })
 8239    }
 8240
 8241    pub fn select_to_previous_subword_start(
 8242        &mut self,
 8243        _: &SelectToPreviousSubwordStart,
 8244        window: &mut Window,
 8245        cx: &mut Context<Self>,
 8246    ) {
 8247        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8248            s.move_heads_with(|map, head, _| {
 8249                (
 8250                    movement::previous_subword_start(map, head),
 8251                    SelectionGoal::None,
 8252                )
 8253            });
 8254        })
 8255    }
 8256
 8257    pub fn delete_to_previous_word_start(
 8258        &mut self,
 8259        action: &DeleteToPreviousWordStart,
 8260        window: &mut Window,
 8261        cx: &mut Context<Self>,
 8262    ) {
 8263        self.transact(window, cx, |this, window, cx| {
 8264            this.select_autoclose_pair(window, cx);
 8265            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8266                let line_mode = s.line_mode;
 8267                s.move_with(|map, selection| {
 8268                    if selection.is_empty() && !line_mode {
 8269                        let cursor = if action.ignore_newlines {
 8270                            movement::previous_word_start(map, selection.head())
 8271                        } else {
 8272                            movement::previous_word_start_or_newline(map, selection.head())
 8273                        };
 8274                        selection.set_head(cursor, SelectionGoal::None);
 8275                    }
 8276                });
 8277            });
 8278            this.insert("", window, cx);
 8279        });
 8280    }
 8281
 8282    pub fn delete_to_previous_subword_start(
 8283        &mut self,
 8284        _: &DeleteToPreviousSubwordStart,
 8285        window: &mut Window,
 8286        cx: &mut Context<Self>,
 8287    ) {
 8288        self.transact(window, cx, |this, window, cx| {
 8289            this.select_autoclose_pair(window, cx);
 8290            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8291                let line_mode = s.line_mode;
 8292                s.move_with(|map, selection| {
 8293                    if selection.is_empty() && !line_mode {
 8294                        let cursor = movement::previous_subword_start(map, selection.head());
 8295                        selection.set_head(cursor, SelectionGoal::None);
 8296                    }
 8297                });
 8298            });
 8299            this.insert("", window, cx);
 8300        });
 8301    }
 8302
 8303    pub fn move_to_next_word_end(
 8304        &mut self,
 8305        _: &MoveToNextWordEnd,
 8306        window: &mut Window,
 8307        cx: &mut Context<Self>,
 8308    ) {
 8309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8310            s.move_cursors_with(|map, head, _| {
 8311                (movement::next_word_end(map, head), SelectionGoal::None)
 8312            });
 8313        })
 8314    }
 8315
 8316    pub fn move_to_next_subword_end(
 8317        &mut self,
 8318        _: &MoveToNextSubwordEnd,
 8319        window: &mut Window,
 8320        cx: &mut Context<Self>,
 8321    ) {
 8322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323            s.move_cursors_with(|map, head, _| {
 8324                (movement::next_subword_end(map, head), SelectionGoal::None)
 8325            });
 8326        })
 8327    }
 8328
 8329    pub fn select_to_next_word_end(
 8330        &mut self,
 8331        _: &SelectToNextWordEnd,
 8332        window: &mut Window,
 8333        cx: &mut Context<Self>,
 8334    ) {
 8335        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8336            s.move_heads_with(|map, head, _| {
 8337                (movement::next_word_end(map, head), SelectionGoal::None)
 8338            });
 8339        })
 8340    }
 8341
 8342    pub fn select_to_next_subword_end(
 8343        &mut self,
 8344        _: &SelectToNextSubwordEnd,
 8345        window: &mut Window,
 8346        cx: &mut Context<Self>,
 8347    ) {
 8348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8349            s.move_heads_with(|map, head, _| {
 8350                (movement::next_subword_end(map, head), SelectionGoal::None)
 8351            });
 8352        })
 8353    }
 8354
 8355    pub fn delete_to_next_word_end(
 8356        &mut self,
 8357        action: &DeleteToNextWordEnd,
 8358        window: &mut Window,
 8359        cx: &mut Context<Self>,
 8360    ) {
 8361        self.transact(window, cx, |this, window, cx| {
 8362            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8363                let line_mode = s.line_mode;
 8364                s.move_with(|map, selection| {
 8365                    if selection.is_empty() && !line_mode {
 8366                        let cursor = if action.ignore_newlines {
 8367                            movement::next_word_end(map, selection.head())
 8368                        } else {
 8369                            movement::next_word_end_or_newline(map, selection.head())
 8370                        };
 8371                        selection.set_head(cursor, SelectionGoal::None);
 8372                    }
 8373                });
 8374            });
 8375            this.insert("", window, cx);
 8376        });
 8377    }
 8378
 8379    pub fn delete_to_next_subword_end(
 8380        &mut self,
 8381        _: &DeleteToNextSubwordEnd,
 8382        window: &mut Window,
 8383        cx: &mut Context<Self>,
 8384    ) {
 8385        self.transact(window, cx, |this, window, cx| {
 8386            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8387                s.move_with(|map, selection| {
 8388                    if selection.is_empty() {
 8389                        let cursor = movement::next_subword_end(map, selection.head());
 8390                        selection.set_head(cursor, SelectionGoal::None);
 8391                    }
 8392                });
 8393            });
 8394            this.insert("", window, cx);
 8395        });
 8396    }
 8397
 8398    pub fn move_to_beginning_of_line(
 8399        &mut self,
 8400        action: &MoveToBeginningOfLine,
 8401        window: &mut Window,
 8402        cx: &mut Context<Self>,
 8403    ) {
 8404        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8405            s.move_cursors_with(|map, head, _| {
 8406                (
 8407                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8408                    SelectionGoal::None,
 8409                )
 8410            });
 8411        })
 8412    }
 8413
 8414    pub fn select_to_beginning_of_line(
 8415        &mut self,
 8416        action: &SelectToBeginningOfLine,
 8417        window: &mut Window,
 8418        cx: &mut Context<Self>,
 8419    ) {
 8420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421            s.move_heads_with(|map, head, _| {
 8422                (
 8423                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8424                    SelectionGoal::None,
 8425                )
 8426            });
 8427        });
 8428    }
 8429
 8430    pub fn delete_to_beginning_of_line(
 8431        &mut self,
 8432        _: &DeleteToBeginningOfLine,
 8433        window: &mut Window,
 8434        cx: &mut Context<Self>,
 8435    ) {
 8436        self.transact(window, cx, |this, window, cx| {
 8437            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8438                s.move_with(|_, selection| {
 8439                    selection.reversed = true;
 8440                });
 8441            });
 8442
 8443            this.select_to_beginning_of_line(
 8444                &SelectToBeginningOfLine {
 8445                    stop_at_soft_wraps: false,
 8446                },
 8447                window,
 8448                cx,
 8449            );
 8450            this.backspace(&Backspace, window, cx);
 8451        });
 8452    }
 8453
 8454    pub fn move_to_end_of_line(
 8455        &mut self,
 8456        action: &MoveToEndOfLine,
 8457        window: &mut Window,
 8458        cx: &mut Context<Self>,
 8459    ) {
 8460        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8461            s.move_cursors_with(|map, head, _| {
 8462                (
 8463                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8464                    SelectionGoal::None,
 8465                )
 8466            });
 8467        })
 8468    }
 8469
 8470    pub fn select_to_end_of_line(
 8471        &mut self,
 8472        action: &SelectToEndOfLine,
 8473        window: &mut Window,
 8474        cx: &mut Context<Self>,
 8475    ) {
 8476        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8477            s.move_heads_with(|map, head, _| {
 8478                (
 8479                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8480                    SelectionGoal::None,
 8481                )
 8482            });
 8483        })
 8484    }
 8485
 8486    pub fn delete_to_end_of_line(
 8487        &mut self,
 8488        _: &DeleteToEndOfLine,
 8489        window: &mut Window,
 8490        cx: &mut Context<Self>,
 8491    ) {
 8492        self.transact(window, cx, |this, window, cx| {
 8493            this.select_to_end_of_line(
 8494                &SelectToEndOfLine {
 8495                    stop_at_soft_wraps: false,
 8496                },
 8497                window,
 8498                cx,
 8499            );
 8500            this.delete(&Delete, window, cx);
 8501        });
 8502    }
 8503
 8504    pub fn cut_to_end_of_line(
 8505        &mut self,
 8506        _: &CutToEndOfLine,
 8507        window: &mut Window,
 8508        cx: &mut Context<Self>,
 8509    ) {
 8510        self.transact(window, cx, |this, window, cx| {
 8511            this.select_to_end_of_line(
 8512                &SelectToEndOfLine {
 8513                    stop_at_soft_wraps: false,
 8514                },
 8515                window,
 8516                cx,
 8517            );
 8518            this.cut(&Cut, window, cx);
 8519        });
 8520    }
 8521
 8522    pub fn move_to_start_of_paragraph(
 8523        &mut self,
 8524        _: &MoveToStartOfParagraph,
 8525        window: &mut Window,
 8526        cx: &mut Context<Self>,
 8527    ) {
 8528        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8529            cx.propagate();
 8530            return;
 8531        }
 8532
 8533        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8534            s.move_with(|map, selection| {
 8535                selection.collapse_to(
 8536                    movement::start_of_paragraph(map, selection.head(), 1),
 8537                    SelectionGoal::None,
 8538                )
 8539            });
 8540        })
 8541    }
 8542
 8543    pub fn move_to_end_of_paragraph(
 8544        &mut self,
 8545        _: &MoveToEndOfParagraph,
 8546        window: &mut Window,
 8547        cx: &mut Context<Self>,
 8548    ) {
 8549        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8550            cx.propagate();
 8551            return;
 8552        }
 8553
 8554        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8555            s.move_with(|map, selection| {
 8556                selection.collapse_to(
 8557                    movement::end_of_paragraph(map, selection.head(), 1),
 8558                    SelectionGoal::None,
 8559                )
 8560            });
 8561        })
 8562    }
 8563
 8564    pub fn select_to_start_of_paragraph(
 8565        &mut self,
 8566        _: &SelectToStartOfParagraph,
 8567        window: &mut Window,
 8568        cx: &mut Context<Self>,
 8569    ) {
 8570        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8571            cx.propagate();
 8572            return;
 8573        }
 8574
 8575        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8576            s.move_heads_with(|map, head, _| {
 8577                (
 8578                    movement::start_of_paragraph(map, head, 1),
 8579                    SelectionGoal::None,
 8580                )
 8581            });
 8582        })
 8583    }
 8584
 8585    pub fn select_to_end_of_paragraph(
 8586        &mut self,
 8587        _: &SelectToEndOfParagraph,
 8588        window: &mut Window,
 8589        cx: &mut Context<Self>,
 8590    ) {
 8591        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8592            cx.propagate();
 8593            return;
 8594        }
 8595
 8596        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8597            s.move_heads_with(|map, head, _| {
 8598                (
 8599                    movement::end_of_paragraph(map, head, 1),
 8600                    SelectionGoal::None,
 8601                )
 8602            });
 8603        })
 8604    }
 8605
 8606    pub fn move_to_beginning(
 8607        &mut self,
 8608        _: &MoveToBeginning,
 8609        window: &mut Window,
 8610        cx: &mut Context<Self>,
 8611    ) {
 8612        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8613            cx.propagate();
 8614            return;
 8615        }
 8616
 8617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8618            s.select_ranges(vec![0..0]);
 8619        });
 8620    }
 8621
 8622    pub fn select_to_beginning(
 8623        &mut self,
 8624        _: &SelectToBeginning,
 8625        window: &mut Window,
 8626        cx: &mut Context<Self>,
 8627    ) {
 8628        let mut selection = self.selections.last::<Point>(cx);
 8629        selection.set_head(Point::zero(), SelectionGoal::None);
 8630
 8631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8632            s.select(vec![selection]);
 8633        });
 8634    }
 8635
 8636    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8637        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8638            cx.propagate();
 8639            return;
 8640        }
 8641
 8642        let cursor = self.buffer.read(cx).read(cx).len();
 8643        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8644            s.select_ranges(vec![cursor..cursor])
 8645        });
 8646    }
 8647
 8648    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8649        self.nav_history = nav_history;
 8650    }
 8651
 8652    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8653        self.nav_history.as_ref()
 8654    }
 8655
 8656    fn push_to_nav_history(
 8657        &mut self,
 8658        cursor_anchor: Anchor,
 8659        new_position: Option<Point>,
 8660        cx: &mut Context<Self>,
 8661    ) {
 8662        if let Some(nav_history) = self.nav_history.as_mut() {
 8663            let buffer = self.buffer.read(cx).read(cx);
 8664            let cursor_position = cursor_anchor.to_point(&buffer);
 8665            let scroll_state = self.scroll_manager.anchor();
 8666            let scroll_top_row = scroll_state.top_row(&buffer);
 8667            drop(buffer);
 8668
 8669            if let Some(new_position) = new_position {
 8670                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8671                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8672                    return;
 8673                }
 8674            }
 8675
 8676            nav_history.push(
 8677                Some(NavigationData {
 8678                    cursor_anchor,
 8679                    cursor_position,
 8680                    scroll_anchor: scroll_state,
 8681                    scroll_top_row,
 8682                }),
 8683                cx,
 8684            );
 8685        }
 8686    }
 8687
 8688    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8689        let buffer = self.buffer.read(cx).snapshot(cx);
 8690        let mut selection = self.selections.first::<usize>(cx);
 8691        selection.set_head(buffer.len(), SelectionGoal::None);
 8692        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8693            s.select(vec![selection]);
 8694        });
 8695    }
 8696
 8697    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8698        let end = self.buffer.read(cx).read(cx).len();
 8699        self.change_selections(None, window, cx, |s| {
 8700            s.select_ranges(vec![0..end]);
 8701        });
 8702    }
 8703
 8704    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8705        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8706        let mut selections = self.selections.all::<Point>(cx);
 8707        let max_point = display_map.buffer_snapshot.max_point();
 8708        for selection in &mut selections {
 8709            let rows = selection.spanned_rows(true, &display_map);
 8710            selection.start = Point::new(rows.start.0, 0);
 8711            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8712            selection.reversed = false;
 8713        }
 8714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8715            s.select(selections);
 8716        });
 8717    }
 8718
 8719    pub fn split_selection_into_lines(
 8720        &mut self,
 8721        _: &SplitSelectionIntoLines,
 8722        window: &mut Window,
 8723        cx: &mut Context<Self>,
 8724    ) {
 8725        let mut to_unfold = Vec::new();
 8726        let mut new_selection_ranges = Vec::new();
 8727        {
 8728            let selections = self.selections.all::<Point>(cx);
 8729            let buffer = self.buffer.read(cx).read(cx);
 8730            for selection in selections {
 8731                for row in selection.start.row..selection.end.row {
 8732                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8733                    new_selection_ranges.push(cursor..cursor);
 8734                }
 8735                new_selection_ranges.push(selection.end..selection.end);
 8736                to_unfold.push(selection.start..selection.end);
 8737            }
 8738        }
 8739        self.unfold_ranges(&to_unfold, true, true, cx);
 8740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741            s.select_ranges(new_selection_ranges);
 8742        });
 8743    }
 8744
 8745    pub fn add_selection_above(
 8746        &mut self,
 8747        _: &AddSelectionAbove,
 8748        window: &mut Window,
 8749        cx: &mut Context<Self>,
 8750    ) {
 8751        self.add_selection(true, window, cx);
 8752    }
 8753
 8754    pub fn add_selection_below(
 8755        &mut self,
 8756        _: &AddSelectionBelow,
 8757        window: &mut Window,
 8758        cx: &mut Context<Self>,
 8759    ) {
 8760        self.add_selection(false, window, cx);
 8761    }
 8762
 8763    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8764        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8765        let mut selections = self.selections.all::<Point>(cx);
 8766        let text_layout_details = self.text_layout_details(window);
 8767        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8768            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8769            let range = oldest_selection.display_range(&display_map).sorted();
 8770
 8771            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8772            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8773            let positions = start_x.min(end_x)..start_x.max(end_x);
 8774
 8775            selections.clear();
 8776            let mut stack = Vec::new();
 8777            for row in range.start.row().0..=range.end.row().0 {
 8778                if let Some(selection) = self.selections.build_columnar_selection(
 8779                    &display_map,
 8780                    DisplayRow(row),
 8781                    &positions,
 8782                    oldest_selection.reversed,
 8783                    &text_layout_details,
 8784                ) {
 8785                    stack.push(selection.id);
 8786                    selections.push(selection);
 8787                }
 8788            }
 8789
 8790            if above {
 8791                stack.reverse();
 8792            }
 8793
 8794            AddSelectionsState { above, stack }
 8795        });
 8796
 8797        let last_added_selection = *state.stack.last().unwrap();
 8798        let mut new_selections = Vec::new();
 8799        if above == state.above {
 8800            let end_row = if above {
 8801                DisplayRow(0)
 8802            } else {
 8803                display_map.max_point().row()
 8804            };
 8805
 8806            'outer: for selection in selections {
 8807                if selection.id == last_added_selection {
 8808                    let range = selection.display_range(&display_map).sorted();
 8809                    debug_assert_eq!(range.start.row(), range.end.row());
 8810                    let mut row = range.start.row();
 8811                    let positions =
 8812                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8813                            px(start)..px(end)
 8814                        } else {
 8815                            let start_x =
 8816                                display_map.x_for_display_point(range.start, &text_layout_details);
 8817                            let end_x =
 8818                                display_map.x_for_display_point(range.end, &text_layout_details);
 8819                            start_x.min(end_x)..start_x.max(end_x)
 8820                        };
 8821
 8822                    while row != end_row {
 8823                        if above {
 8824                            row.0 -= 1;
 8825                        } else {
 8826                            row.0 += 1;
 8827                        }
 8828
 8829                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8830                            &display_map,
 8831                            row,
 8832                            &positions,
 8833                            selection.reversed,
 8834                            &text_layout_details,
 8835                        ) {
 8836                            state.stack.push(new_selection.id);
 8837                            if above {
 8838                                new_selections.push(new_selection);
 8839                                new_selections.push(selection);
 8840                            } else {
 8841                                new_selections.push(selection);
 8842                                new_selections.push(new_selection);
 8843                            }
 8844
 8845                            continue 'outer;
 8846                        }
 8847                    }
 8848                }
 8849
 8850                new_selections.push(selection);
 8851            }
 8852        } else {
 8853            new_selections = selections;
 8854            new_selections.retain(|s| s.id != last_added_selection);
 8855            state.stack.pop();
 8856        }
 8857
 8858        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8859            s.select(new_selections);
 8860        });
 8861        if state.stack.len() > 1 {
 8862            self.add_selections_state = Some(state);
 8863        }
 8864    }
 8865
 8866    pub fn select_next_match_internal(
 8867        &mut self,
 8868        display_map: &DisplaySnapshot,
 8869        replace_newest: bool,
 8870        autoscroll: Option<Autoscroll>,
 8871        window: &mut Window,
 8872        cx: &mut Context<Self>,
 8873    ) -> Result<()> {
 8874        fn select_next_match_ranges(
 8875            this: &mut Editor,
 8876            range: Range<usize>,
 8877            replace_newest: bool,
 8878            auto_scroll: Option<Autoscroll>,
 8879            window: &mut Window,
 8880            cx: &mut Context<Editor>,
 8881        ) {
 8882            this.unfold_ranges(&[range.clone()], false, true, cx);
 8883            this.change_selections(auto_scroll, window, cx, |s| {
 8884                if replace_newest {
 8885                    s.delete(s.newest_anchor().id);
 8886                }
 8887                s.insert_range(range.clone());
 8888            });
 8889        }
 8890
 8891        let buffer = &display_map.buffer_snapshot;
 8892        let mut selections = self.selections.all::<usize>(cx);
 8893        if let Some(mut select_next_state) = self.select_next_state.take() {
 8894            let query = &select_next_state.query;
 8895            if !select_next_state.done {
 8896                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8897                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8898                let mut next_selected_range = None;
 8899
 8900                let bytes_after_last_selection =
 8901                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8902                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8903                let query_matches = query
 8904                    .stream_find_iter(bytes_after_last_selection)
 8905                    .map(|result| (last_selection.end, result))
 8906                    .chain(
 8907                        query
 8908                            .stream_find_iter(bytes_before_first_selection)
 8909                            .map(|result| (0, result)),
 8910                    );
 8911
 8912                for (start_offset, query_match) in query_matches {
 8913                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8914                    let offset_range =
 8915                        start_offset + query_match.start()..start_offset + query_match.end();
 8916                    let display_range = offset_range.start.to_display_point(display_map)
 8917                        ..offset_range.end.to_display_point(display_map);
 8918
 8919                    if !select_next_state.wordwise
 8920                        || (!movement::is_inside_word(display_map, display_range.start)
 8921                            && !movement::is_inside_word(display_map, display_range.end))
 8922                    {
 8923                        // TODO: This is n^2, because we might check all the selections
 8924                        if !selections
 8925                            .iter()
 8926                            .any(|selection| selection.range().overlaps(&offset_range))
 8927                        {
 8928                            next_selected_range = Some(offset_range);
 8929                            break;
 8930                        }
 8931                    }
 8932                }
 8933
 8934                if let Some(next_selected_range) = next_selected_range {
 8935                    select_next_match_ranges(
 8936                        self,
 8937                        next_selected_range,
 8938                        replace_newest,
 8939                        autoscroll,
 8940                        window,
 8941                        cx,
 8942                    );
 8943                } else {
 8944                    select_next_state.done = true;
 8945                }
 8946            }
 8947
 8948            self.select_next_state = Some(select_next_state);
 8949        } else {
 8950            let mut only_carets = true;
 8951            let mut same_text_selected = true;
 8952            let mut selected_text = None;
 8953
 8954            let mut selections_iter = selections.iter().peekable();
 8955            while let Some(selection) = selections_iter.next() {
 8956                if selection.start != selection.end {
 8957                    only_carets = false;
 8958                }
 8959
 8960                if same_text_selected {
 8961                    if selected_text.is_none() {
 8962                        selected_text =
 8963                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8964                    }
 8965
 8966                    if let Some(next_selection) = selections_iter.peek() {
 8967                        if next_selection.range().len() == selection.range().len() {
 8968                            let next_selected_text = buffer
 8969                                .text_for_range(next_selection.range())
 8970                                .collect::<String>();
 8971                            if Some(next_selected_text) != selected_text {
 8972                                same_text_selected = false;
 8973                                selected_text = None;
 8974                            }
 8975                        } else {
 8976                            same_text_selected = false;
 8977                            selected_text = None;
 8978                        }
 8979                    }
 8980                }
 8981            }
 8982
 8983            if only_carets {
 8984                for selection in &mut selections {
 8985                    let word_range = movement::surrounding_word(
 8986                        display_map,
 8987                        selection.start.to_display_point(display_map),
 8988                    );
 8989                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8990                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8991                    selection.goal = SelectionGoal::None;
 8992                    selection.reversed = false;
 8993                    select_next_match_ranges(
 8994                        self,
 8995                        selection.start..selection.end,
 8996                        replace_newest,
 8997                        autoscroll,
 8998                        window,
 8999                        cx,
 9000                    );
 9001                }
 9002
 9003                if selections.len() == 1 {
 9004                    let selection = selections
 9005                        .last()
 9006                        .expect("ensured that there's only one selection");
 9007                    let query = buffer
 9008                        .text_for_range(selection.start..selection.end)
 9009                        .collect::<String>();
 9010                    let is_empty = query.is_empty();
 9011                    let select_state = SelectNextState {
 9012                        query: AhoCorasick::new(&[query])?,
 9013                        wordwise: true,
 9014                        done: is_empty,
 9015                    };
 9016                    self.select_next_state = Some(select_state);
 9017                } else {
 9018                    self.select_next_state = None;
 9019                }
 9020            } else if let Some(selected_text) = selected_text {
 9021                self.select_next_state = Some(SelectNextState {
 9022                    query: AhoCorasick::new(&[selected_text])?,
 9023                    wordwise: false,
 9024                    done: false,
 9025                });
 9026                self.select_next_match_internal(
 9027                    display_map,
 9028                    replace_newest,
 9029                    autoscroll,
 9030                    window,
 9031                    cx,
 9032                )?;
 9033            }
 9034        }
 9035        Ok(())
 9036    }
 9037
 9038    pub fn select_all_matches(
 9039        &mut self,
 9040        _action: &SelectAllMatches,
 9041        window: &mut Window,
 9042        cx: &mut Context<Self>,
 9043    ) -> Result<()> {
 9044        self.push_to_selection_history();
 9045        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9046
 9047        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9048        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9049            return Ok(());
 9050        };
 9051        if select_next_state.done {
 9052            return Ok(());
 9053        }
 9054
 9055        let mut new_selections = self.selections.all::<usize>(cx);
 9056
 9057        let buffer = &display_map.buffer_snapshot;
 9058        let query_matches = select_next_state
 9059            .query
 9060            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9061
 9062        for query_match in query_matches {
 9063            let query_match = query_match.unwrap(); // can only fail due to I/O
 9064            let offset_range = query_match.start()..query_match.end();
 9065            let display_range = offset_range.start.to_display_point(&display_map)
 9066                ..offset_range.end.to_display_point(&display_map);
 9067
 9068            if !select_next_state.wordwise
 9069                || (!movement::is_inside_word(&display_map, display_range.start)
 9070                    && !movement::is_inside_word(&display_map, display_range.end))
 9071            {
 9072                self.selections.change_with(cx, |selections| {
 9073                    new_selections.push(Selection {
 9074                        id: selections.new_selection_id(),
 9075                        start: offset_range.start,
 9076                        end: offset_range.end,
 9077                        reversed: false,
 9078                        goal: SelectionGoal::None,
 9079                    });
 9080                });
 9081            }
 9082        }
 9083
 9084        new_selections.sort_by_key(|selection| selection.start);
 9085        let mut ix = 0;
 9086        while ix + 1 < new_selections.len() {
 9087            let current_selection = &new_selections[ix];
 9088            let next_selection = &new_selections[ix + 1];
 9089            if current_selection.range().overlaps(&next_selection.range()) {
 9090                if current_selection.id < next_selection.id {
 9091                    new_selections.remove(ix + 1);
 9092                } else {
 9093                    new_selections.remove(ix);
 9094                }
 9095            } else {
 9096                ix += 1;
 9097            }
 9098        }
 9099
 9100        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9101
 9102        for selection in new_selections.iter_mut() {
 9103            selection.reversed = reversed;
 9104        }
 9105
 9106        select_next_state.done = true;
 9107        self.unfold_ranges(
 9108            &new_selections
 9109                .iter()
 9110                .map(|selection| selection.range())
 9111                .collect::<Vec<_>>(),
 9112            false,
 9113            false,
 9114            cx,
 9115        );
 9116        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9117            selections.select(new_selections)
 9118        });
 9119
 9120        Ok(())
 9121    }
 9122
 9123    pub fn select_next(
 9124        &mut self,
 9125        action: &SelectNext,
 9126        window: &mut Window,
 9127        cx: &mut Context<Self>,
 9128    ) -> Result<()> {
 9129        self.push_to_selection_history();
 9130        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9131        self.select_next_match_internal(
 9132            &display_map,
 9133            action.replace_newest,
 9134            Some(Autoscroll::newest()),
 9135            window,
 9136            cx,
 9137        )?;
 9138        Ok(())
 9139    }
 9140
 9141    pub fn select_previous(
 9142        &mut self,
 9143        action: &SelectPrevious,
 9144        window: &mut Window,
 9145        cx: &mut Context<Self>,
 9146    ) -> Result<()> {
 9147        self.push_to_selection_history();
 9148        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9149        let buffer = &display_map.buffer_snapshot;
 9150        let mut selections = self.selections.all::<usize>(cx);
 9151        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9152            let query = &select_prev_state.query;
 9153            if !select_prev_state.done {
 9154                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9155                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9156                let mut next_selected_range = None;
 9157                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9158                let bytes_before_last_selection =
 9159                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9160                let bytes_after_first_selection =
 9161                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9162                let query_matches = query
 9163                    .stream_find_iter(bytes_before_last_selection)
 9164                    .map(|result| (last_selection.start, result))
 9165                    .chain(
 9166                        query
 9167                            .stream_find_iter(bytes_after_first_selection)
 9168                            .map(|result| (buffer.len(), result)),
 9169                    );
 9170                for (end_offset, query_match) in query_matches {
 9171                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9172                    let offset_range =
 9173                        end_offset - query_match.end()..end_offset - query_match.start();
 9174                    let display_range = offset_range.start.to_display_point(&display_map)
 9175                        ..offset_range.end.to_display_point(&display_map);
 9176
 9177                    if !select_prev_state.wordwise
 9178                        || (!movement::is_inside_word(&display_map, display_range.start)
 9179                            && !movement::is_inside_word(&display_map, display_range.end))
 9180                    {
 9181                        next_selected_range = Some(offset_range);
 9182                        break;
 9183                    }
 9184                }
 9185
 9186                if let Some(next_selected_range) = next_selected_range {
 9187                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9188                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9189                        if action.replace_newest {
 9190                            s.delete(s.newest_anchor().id);
 9191                        }
 9192                        s.insert_range(next_selected_range);
 9193                    });
 9194                } else {
 9195                    select_prev_state.done = true;
 9196                }
 9197            }
 9198
 9199            self.select_prev_state = Some(select_prev_state);
 9200        } else {
 9201            let mut only_carets = true;
 9202            let mut same_text_selected = true;
 9203            let mut selected_text = None;
 9204
 9205            let mut selections_iter = selections.iter().peekable();
 9206            while let Some(selection) = selections_iter.next() {
 9207                if selection.start != selection.end {
 9208                    only_carets = false;
 9209                }
 9210
 9211                if same_text_selected {
 9212                    if selected_text.is_none() {
 9213                        selected_text =
 9214                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9215                    }
 9216
 9217                    if let Some(next_selection) = selections_iter.peek() {
 9218                        if next_selection.range().len() == selection.range().len() {
 9219                            let next_selected_text = buffer
 9220                                .text_for_range(next_selection.range())
 9221                                .collect::<String>();
 9222                            if Some(next_selected_text) != selected_text {
 9223                                same_text_selected = false;
 9224                                selected_text = None;
 9225                            }
 9226                        } else {
 9227                            same_text_selected = false;
 9228                            selected_text = None;
 9229                        }
 9230                    }
 9231                }
 9232            }
 9233
 9234            if only_carets {
 9235                for selection in &mut selections {
 9236                    let word_range = movement::surrounding_word(
 9237                        &display_map,
 9238                        selection.start.to_display_point(&display_map),
 9239                    );
 9240                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9241                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9242                    selection.goal = SelectionGoal::None;
 9243                    selection.reversed = false;
 9244                }
 9245                if selections.len() == 1 {
 9246                    let selection = selections
 9247                        .last()
 9248                        .expect("ensured that there's only one selection");
 9249                    let query = buffer
 9250                        .text_for_range(selection.start..selection.end)
 9251                        .collect::<String>();
 9252                    let is_empty = query.is_empty();
 9253                    let select_state = SelectNextState {
 9254                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9255                        wordwise: true,
 9256                        done: is_empty,
 9257                    };
 9258                    self.select_prev_state = Some(select_state);
 9259                } else {
 9260                    self.select_prev_state = None;
 9261                }
 9262
 9263                self.unfold_ranges(
 9264                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9265                    false,
 9266                    true,
 9267                    cx,
 9268                );
 9269                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9270                    s.select(selections);
 9271                });
 9272            } else if let Some(selected_text) = selected_text {
 9273                self.select_prev_state = Some(SelectNextState {
 9274                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9275                    wordwise: false,
 9276                    done: false,
 9277                });
 9278                self.select_previous(action, window, cx)?;
 9279            }
 9280        }
 9281        Ok(())
 9282    }
 9283
 9284    pub fn toggle_comments(
 9285        &mut self,
 9286        action: &ToggleComments,
 9287        window: &mut Window,
 9288        cx: &mut Context<Self>,
 9289    ) {
 9290        if self.read_only(cx) {
 9291            return;
 9292        }
 9293        let text_layout_details = &self.text_layout_details(window);
 9294        self.transact(window, cx, |this, window, cx| {
 9295            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9296            let mut edits = Vec::new();
 9297            let mut selection_edit_ranges = Vec::new();
 9298            let mut last_toggled_row = None;
 9299            let snapshot = this.buffer.read(cx).read(cx);
 9300            let empty_str: Arc<str> = Arc::default();
 9301            let mut suffixes_inserted = Vec::new();
 9302            let ignore_indent = action.ignore_indent;
 9303
 9304            fn comment_prefix_range(
 9305                snapshot: &MultiBufferSnapshot,
 9306                row: MultiBufferRow,
 9307                comment_prefix: &str,
 9308                comment_prefix_whitespace: &str,
 9309                ignore_indent: bool,
 9310            ) -> Range<Point> {
 9311                let indent_size = if ignore_indent {
 9312                    0
 9313                } else {
 9314                    snapshot.indent_size_for_line(row).len
 9315                };
 9316
 9317                let start = Point::new(row.0, indent_size);
 9318
 9319                let mut line_bytes = snapshot
 9320                    .bytes_in_range(start..snapshot.max_point())
 9321                    .flatten()
 9322                    .copied();
 9323
 9324                // If this line currently begins with the line comment prefix, then record
 9325                // the range containing the prefix.
 9326                if line_bytes
 9327                    .by_ref()
 9328                    .take(comment_prefix.len())
 9329                    .eq(comment_prefix.bytes())
 9330                {
 9331                    // Include any whitespace that matches the comment prefix.
 9332                    let matching_whitespace_len = line_bytes
 9333                        .zip(comment_prefix_whitespace.bytes())
 9334                        .take_while(|(a, b)| a == b)
 9335                        .count() as u32;
 9336                    let end = Point::new(
 9337                        start.row,
 9338                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9339                    );
 9340                    start..end
 9341                } else {
 9342                    start..start
 9343                }
 9344            }
 9345
 9346            fn comment_suffix_range(
 9347                snapshot: &MultiBufferSnapshot,
 9348                row: MultiBufferRow,
 9349                comment_suffix: &str,
 9350                comment_suffix_has_leading_space: bool,
 9351            ) -> Range<Point> {
 9352                let end = Point::new(row.0, snapshot.line_len(row));
 9353                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9354
 9355                let mut line_end_bytes = snapshot
 9356                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9357                    .flatten()
 9358                    .copied();
 9359
 9360                let leading_space_len = if suffix_start_column > 0
 9361                    && line_end_bytes.next() == Some(b' ')
 9362                    && comment_suffix_has_leading_space
 9363                {
 9364                    1
 9365                } else {
 9366                    0
 9367                };
 9368
 9369                // If this line currently begins with the line comment prefix, then record
 9370                // the range containing the prefix.
 9371                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9372                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9373                    start..end
 9374                } else {
 9375                    end..end
 9376                }
 9377            }
 9378
 9379            // TODO: Handle selections that cross excerpts
 9380            for selection in &mut selections {
 9381                let start_column = snapshot
 9382                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9383                    .len;
 9384                let language = if let Some(language) =
 9385                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9386                {
 9387                    language
 9388                } else {
 9389                    continue;
 9390                };
 9391
 9392                selection_edit_ranges.clear();
 9393
 9394                // If multiple selections contain a given row, avoid processing that
 9395                // row more than once.
 9396                let mut start_row = MultiBufferRow(selection.start.row);
 9397                if last_toggled_row == Some(start_row) {
 9398                    start_row = start_row.next_row();
 9399                }
 9400                let end_row =
 9401                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9402                        MultiBufferRow(selection.end.row - 1)
 9403                    } else {
 9404                        MultiBufferRow(selection.end.row)
 9405                    };
 9406                last_toggled_row = Some(end_row);
 9407
 9408                if start_row > end_row {
 9409                    continue;
 9410                }
 9411
 9412                // If the language has line comments, toggle those.
 9413                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9414
 9415                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9416                if ignore_indent {
 9417                    full_comment_prefixes = full_comment_prefixes
 9418                        .into_iter()
 9419                        .map(|s| Arc::from(s.trim_end()))
 9420                        .collect();
 9421                }
 9422
 9423                if !full_comment_prefixes.is_empty() {
 9424                    let first_prefix = full_comment_prefixes
 9425                        .first()
 9426                        .expect("prefixes is non-empty");
 9427                    let prefix_trimmed_lengths = full_comment_prefixes
 9428                        .iter()
 9429                        .map(|p| p.trim_end_matches(' ').len())
 9430                        .collect::<SmallVec<[usize; 4]>>();
 9431
 9432                    let mut all_selection_lines_are_comments = true;
 9433
 9434                    for row in start_row.0..=end_row.0 {
 9435                        let row = MultiBufferRow(row);
 9436                        if start_row < end_row && snapshot.is_line_blank(row) {
 9437                            continue;
 9438                        }
 9439
 9440                        let prefix_range = full_comment_prefixes
 9441                            .iter()
 9442                            .zip(prefix_trimmed_lengths.iter().copied())
 9443                            .map(|(prefix, trimmed_prefix_len)| {
 9444                                comment_prefix_range(
 9445                                    snapshot.deref(),
 9446                                    row,
 9447                                    &prefix[..trimmed_prefix_len],
 9448                                    &prefix[trimmed_prefix_len..],
 9449                                    ignore_indent,
 9450                                )
 9451                            })
 9452                            .max_by_key(|range| range.end.column - range.start.column)
 9453                            .expect("prefixes is non-empty");
 9454
 9455                        if prefix_range.is_empty() {
 9456                            all_selection_lines_are_comments = false;
 9457                        }
 9458
 9459                        selection_edit_ranges.push(prefix_range);
 9460                    }
 9461
 9462                    if all_selection_lines_are_comments {
 9463                        edits.extend(
 9464                            selection_edit_ranges
 9465                                .iter()
 9466                                .cloned()
 9467                                .map(|range| (range, empty_str.clone())),
 9468                        );
 9469                    } else {
 9470                        let min_column = selection_edit_ranges
 9471                            .iter()
 9472                            .map(|range| range.start.column)
 9473                            .min()
 9474                            .unwrap_or(0);
 9475                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9476                            let position = Point::new(range.start.row, min_column);
 9477                            (position..position, first_prefix.clone())
 9478                        }));
 9479                    }
 9480                } else if let Some((full_comment_prefix, comment_suffix)) =
 9481                    language.block_comment_delimiters()
 9482                {
 9483                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9484                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9485                    let prefix_range = comment_prefix_range(
 9486                        snapshot.deref(),
 9487                        start_row,
 9488                        comment_prefix,
 9489                        comment_prefix_whitespace,
 9490                        ignore_indent,
 9491                    );
 9492                    let suffix_range = comment_suffix_range(
 9493                        snapshot.deref(),
 9494                        end_row,
 9495                        comment_suffix.trim_start_matches(' '),
 9496                        comment_suffix.starts_with(' '),
 9497                    );
 9498
 9499                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9500                        edits.push((
 9501                            prefix_range.start..prefix_range.start,
 9502                            full_comment_prefix.clone(),
 9503                        ));
 9504                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9505                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9506                    } else {
 9507                        edits.push((prefix_range, empty_str.clone()));
 9508                        edits.push((suffix_range, empty_str.clone()));
 9509                    }
 9510                } else {
 9511                    continue;
 9512                }
 9513            }
 9514
 9515            drop(snapshot);
 9516            this.buffer.update(cx, |buffer, cx| {
 9517                buffer.edit(edits, None, cx);
 9518            });
 9519
 9520            // Adjust selections so that they end before any comment suffixes that
 9521            // were inserted.
 9522            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9523            let mut selections = this.selections.all::<Point>(cx);
 9524            let snapshot = this.buffer.read(cx).read(cx);
 9525            for selection in &mut selections {
 9526                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9527                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9528                        Ordering::Less => {
 9529                            suffixes_inserted.next();
 9530                            continue;
 9531                        }
 9532                        Ordering::Greater => break,
 9533                        Ordering::Equal => {
 9534                            if selection.end.column == snapshot.line_len(row) {
 9535                                if selection.is_empty() {
 9536                                    selection.start.column -= suffix_len as u32;
 9537                                }
 9538                                selection.end.column -= suffix_len as u32;
 9539                            }
 9540                            break;
 9541                        }
 9542                    }
 9543                }
 9544            }
 9545
 9546            drop(snapshot);
 9547            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9548                s.select(selections)
 9549            });
 9550
 9551            let selections = this.selections.all::<Point>(cx);
 9552            let selections_on_single_row = selections.windows(2).all(|selections| {
 9553                selections[0].start.row == selections[1].start.row
 9554                    && selections[0].end.row == selections[1].end.row
 9555                    && selections[0].start.row == selections[0].end.row
 9556            });
 9557            let selections_selecting = selections
 9558                .iter()
 9559                .any(|selection| selection.start != selection.end);
 9560            let advance_downwards = action.advance_downwards
 9561                && selections_on_single_row
 9562                && !selections_selecting
 9563                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9564
 9565            if advance_downwards {
 9566                let snapshot = this.buffer.read(cx).snapshot(cx);
 9567
 9568                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9569                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9570                        let mut point = display_point.to_point(display_snapshot);
 9571                        point.row += 1;
 9572                        point = snapshot.clip_point(point, Bias::Left);
 9573                        let display_point = point.to_display_point(display_snapshot);
 9574                        let goal = SelectionGoal::HorizontalPosition(
 9575                            display_snapshot
 9576                                .x_for_display_point(display_point, text_layout_details)
 9577                                .into(),
 9578                        );
 9579                        (display_point, goal)
 9580                    })
 9581                });
 9582            }
 9583        });
 9584    }
 9585
 9586    pub fn select_enclosing_symbol(
 9587        &mut self,
 9588        _: &SelectEnclosingSymbol,
 9589        window: &mut Window,
 9590        cx: &mut Context<Self>,
 9591    ) {
 9592        let buffer = self.buffer.read(cx).snapshot(cx);
 9593        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9594
 9595        fn update_selection(
 9596            selection: &Selection<usize>,
 9597            buffer_snap: &MultiBufferSnapshot,
 9598        ) -> Option<Selection<usize>> {
 9599            let cursor = selection.head();
 9600            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9601            for symbol in symbols.iter().rev() {
 9602                let start = symbol.range.start.to_offset(buffer_snap);
 9603                let end = symbol.range.end.to_offset(buffer_snap);
 9604                let new_range = start..end;
 9605                if start < selection.start || end > selection.end {
 9606                    return Some(Selection {
 9607                        id: selection.id,
 9608                        start: new_range.start,
 9609                        end: new_range.end,
 9610                        goal: SelectionGoal::None,
 9611                        reversed: selection.reversed,
 9612                    });
 9613                }
 9614            }
 9615            None
 9616        }
 9617
 9618        let mut selected_larger_symbol = false;
 9619        let new_selections = old_selections
 9620            .iter()
 9621            .map(|selection| match update_selection(selection, &buffer) {
 9622                Some(new_selection) => {
 9623                    if new_selection.range() != selection.range() {
 9624                        selected_larger_symbol = true;
 9625                    }
 9626                    new_selection
 9627                }
 9628                None => selection.clone(),
 9629            })
 9630            .collect::<Vec<_>>();
 9631
 9632        if selected_larger_symbol {
 9633            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9634                s.select(new_selections);
 9635            });
 9636        }
 9637    }
 9638
 9639    pub fn select_larger_syntax_node(
 9640        &mut self,
 9641        _: &SelectLargerSyntaxNode,
 9642        window: &mut Window,
 9643        cx: &mut Context<Self>,
 9644    ) {
 9645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9646        let buffer = self.buffer.read(cx).snapshot(cx);
 9647        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9648
 9649        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9650        let mut selected_larger_node = false;
 9651        let new_selections = old_selections
 9652            .iter()
 9653            .map(|selection| {
 9654                let old_range = selection.start..selection.end;
 9655                let mut new_range = old_range.clone();
 9656                let mut new_node = None;
 9657                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9658                {
 9659                    new_node = Some(node);
 9660                    new_range = containing_range;
 9661                    if !display_map.intersects_fold(new_range.start)
 9662                        && !display_map.intersects_fold(new_range.end)
 9663                    {
 9664                        break;
 9665                    }
 9666                }
 9667
 9668                if let Some(node) = new_node {
 9669                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9670                    // nodes. Parent and grandparent are also logged because this operation will not
 9671                    // visit nodes that have the same range as their parent.
 9672                    log::info!("Node: {node:?}");
 9673                    let parent = node.parent();
 9674                    log::info!("Parent: {parent:?}");
 9675                    let grandparent = parent.and_then(|x| x.parent());
 9676                    log::info!("Grandparent: {grandparent:?}");
 9677                }
 9678
 9679                selected_larger_node |= new_range != old_range;
 9680                Selection {
 9681                    id: selection.id,
 9682                    start: new_range.start,
 9683                    end: new_range.end,
 9684                    goal: SelectionGoal::None,
 9685                    reversed: selection.reversed,
 9686                }
 9687            })
 9688            .collect::<Vec<_>>();
 9689
 9690        if selected_larger_node {
 9691            stack.push(old_selections);
 9692            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9693                s.select(new_selections);
 9694            });
 9695        }
 9696        self.select_larger_syntax_node_stack = stack;
 9697    }
 9698
 9699    pub fn select_smaller_syntax_node(
 9700        &mut self,
 9701        _: &SelectSmallerSyntaxNode,
 9702        window: &mut Window,
 9703        cx: &mut Context<Self>,
 9704    ) {
 9705        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9706        if let Some(selections) = stack.pop() {
 9707            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9708                s.select(selections.to_vec());
 9709            });
 9710        }
 9711        self.select_larger_syntax_node_stack = stack;
 9712    }
 9713
 9714    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9715        if !EditorSettings::get_global(cx).gutter.runnables {
 9716            self.clear_tasks();
 9717            return Task::ready(());
 9718        }
 9719        let project = self.project.as_ref().map(Entity::downgrade);
 9720        cx.spawn_in(window, |this, mut cx| async move {
 9721            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9722            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9723                return;
 9724            };
 9725            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9726                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9727            }) else {
 9728                return;
 9729            };
 9730
 9731            let hide_runnables = project
 9732                .update(&mut cx, |project, cx| {
 9733                    // Do not display any test indicators in non-dev server remote projects.
 9734                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9735                })
 9736                .unwrap_or(true);
 9737            if hide_runnables {
 9738                return;
 9739            }
 9740            let new_rows =
 9741                cx.background_executor()
 9742                    .spawn({
 9743                        let snapshot = display_snapshot.clone();
 9744                        async move {
 9745                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9746                        }
 9747                    })
 9748                    .await;
 9749
 9750            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9751            this.update(&mut cx, |this, _| {
 9752                this.clear_tasks();
 9753                for (key, value) in rows {
 9754                    this.insert_tasks(key, value);
 9755                }
 9756            })
 9757            .ok();
 9758        })
 9759    }
 9760    fn fetch_runnable_ranges(
 9761        snapshot: &DisplaySnapshot,
 9762        range: Range<Anchor>,
 9763    ) -> Vec<language::RunnableRange> {
 9764        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9765    }
 9766
 9767    fn runnable_rows(
 9768        project: Entity<Project>,
 9769        snapshot: DisplaySnapshot,
 9770        runnable_ranges: Vec<RunnableRange>,
 9771        mut cx: AsyncWindowContext,
 9772    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9773        runnable_ranges
 9774            .into_iter()
 9775            .filter_map(|mut runnable| {
 9776                let tasks = cx
 9777                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9778                    .ok()?;
 9779                if tasks.is_empty() {
 9780                    return None;
 9781                }
 9782
 9783                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9784
 9785                let row = snapshot
 9786                    .buffer_snapshot
 9787                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9788                    .1
 9789                    .start
 9790                    .row;
 9791
 9792                let context_range =
 9793                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9794                Some((
 9795                    (runnable.buffer_id, row),
 9796                    RunnableTasks {
 9797                        templates: tasks,
 9798                        offset: MultiBufferOffset(runnable.run_range.start),
 9799                        context_range,
 9800                        column: point.column,
 9801                        extra_variables: runnable.extra_captures,
 9802                    },
 9803                ))
 9804            })
 9805            .collect()
 9806    }
 9807
 9808    fn templates_with_tags(
 9809        project: &Entity<Project>,
 9810        runnable: &mut Runnable,
 9811        cx: &mut App,
 9812    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9813        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9814            let (worktree_id, file) = project
 9815                .buffer_for_id(runnable.buffer, cx)
 9816                .and_then(|buffer| buffer.read(cx).file())
 9817                .map(|file| (file.worktree_id(cx), file.clone()))
 9818                .unzip();
 9819
 9820            (
 9821                project.task_store().read(cx).task_inventory().cloned(),
 9822                worktree_id,
 9823                file,
 9824            )
 9825        });
 9826
 9827        let tags = mem::take(&mut runnable.tags);
 9828        let mut tags: Vec<_> = tags
 9829            .into_iter()
 9830            .flat_map(|tag| {
 9831                let tag = tag.0.clone();
 9832                inventory
 9833                    .as_ref()
 9834                    .into_iter()
 9835                    .flat_map(|inventory| {
 9836                        inventory.read(cx).list_tasks(
 9837                            file.clone(),
 9838                            Some(runnable.language.clone()),
 9839                            worktree_id,
 9840                            cx,
 9841                        )
 9842                    })
 9843                    .filter(move |(_, template)| {
 9844                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9845                    })
 9846            })
 9847            .sorted_by_key(|(kind, _)| kind.to_owned())
 9848            .collect();
 9849        if let Some((leading_tag_source, _)) = tags.first() {
 9850            // Strongest source wins; if we have worktree tag binding, prefer that to
 9851            // global and language bindings;
 9852            // if we have a global binding, prefer that to language binding.
 9853            let first_mismatch = tags
 9854                .iter()
 9855                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9856            if let Some(index) = first_mismatch {
 9857                tags.truncate(index);
 9858            }
 9859        }
 9860
 9861        tags
 9862    }
 9863
 9864    pub fn move_to_enclosing_bracket(
 9865        &mut self,
 9866        _: &MoveToEnclosingBracket,
 9867        window: &mut Window,
 9868        cx: &mut Context<Self>,
 9869    ) {
 9870        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9871            s.move_offsets_with(|snapshot, selection| {
 9872                let Some(enclosing_bracket_ranges) =
 9873                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9874                else {
 9875                    return;
 9876                };
 9877
 9878                let mut best_length = usize::MAX;
 9879                let mut best_inside = false;
 9880                let mut best_in_bracket_range = false;
 9881                let mut best_destination = None;
 9882                for (open, close) in enclosing_bracket_ranges {
 9883                    let close = close.to_inclusive();
 9884                    let length = close.end() - open.start;
 9885                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9886                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9887                        || close.contains(&selection.head());
 9888
 9889                    // If best is next to a bracket and current isn't, skip
 9890                    if !in_bracket_range && best_in_bracket_range {
 9891                        continue;
 9892                    }
 9893
 9894                    // Prefer smaller lengths unless best is inside and current isn't
 9895                    if length > best_length && (best_inside || !inside) {
 9896                        continue;
 9897                    }
 9898
 9899                    best_length = length;
 9900                    best_inside = inside;
 9901                    best_in_bracket_range = in_bracket_range;
 9902                    best_destination = Some(
 9903                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9904                            if inside {
 9905                                open.end
 9906                            } else {
 9907                                open.start
 9908                            }
 9909                        } else if inside {
 9910                            *close.start()
 9911                        } else {
 9912                            *close.end()
 9913                        },
 9914                    );
 9915                }
 9916
 9917                if let Some(destination) = best_destination {
 9918                    selection.collapse_to(destination, SelectionGoal::None);
 9919                }
 9920            })
 9921        });
 9922    }
 9923
 9924    pub fn undo_selection(
 9925        &mut self,
 9926        _: &UndoSelection,
 9927        window: &mut Window,
 9928        cx: &mut Context<Self>,
 9929    ) {
 9930        self.end_selection(window, cx);
 9931        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9932        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9933            self.change_selections(None, window, cx, |s| {
 9934                s.select_anchors(entry.selections.to_vec())
 9935            });
 9936            self.select_next_state = entry.select_next_state;
 9937            self.select_prev_state = entry.select_prev_state;
 9938            self.add_selections_state = entry.add_selections_state;
 9939            self.request_autoscroll(Autoscroll::newest(), cx);
 9940        }
 9941        self.selection_history.mode = SelectionHistoryMode::Normal;
 9942    }
 9943
 9944    pub fn redo_selection(
 9945        &mut self,
 9946        _: &RedoSelection,
 9947        window: &mut Window,
 9948        cx: &mut Context<Self>,
 9949    ) {
 9950        self.end_selection(window, cx);
 9951        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9952        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9953            self.change_selections(None, window, cx, |s| {
 9954                s.select_anchors(entry.selections.to_vec())
 9955            });
 9956            self.select_next_state = entry.select_next_state;
 9957            self.select_prev_state = entry.select_prev_state;
 9958            self.add_selections_state = entry.add_selections_state;
 9959            self.request_autoscroll(Autoscroll::newest(), cx);
 9960        }
 9961        self.selection_history.mode = SelectionHistoryMode::Normal;
 9962    }
 9963
 9964    pub fn expand_excerpts(
 9965        &mut self,
 9966        action: &ExpandExcerpts,
 9967        _: &mut Window,
 9968        cx: &mut Context<Self>,
 9969    ) {
 9970        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9971    }
 9972
 9973    pub fn expand_excerpts_down(
 9974        &mut self,
 9975        action: &ExpandExcerptsDown,
 9976        _: &mut Window,
 9977        cx: &mut Context<Self>,
 9978    ) {
 9979        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9980    }
 9981
 9982    pub fn expand_excerpts_up(
 9983        &mut self,
 9984        action: &ExpandExcerptsUp,
 9985        _: &mut Window,
 9986        cx: &mut Context<Self>,
 9987    ) {
 9988        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9989    }
 9990
 9991    pub fn expand_excerpts_for_direction(
 9992        &mut self,
 9993        lines: u32,
 9994        direction: ExpandExcerptDirection,
 9995
 9996        cx: &mut Context<Self>,
 9997    ) {
 9998        let selections = self.selections.disjoint_anchors();
 9999
10000        let lines = if lines == 0 {
10001            EditorSettings::get_global(cx).expand_excerpt_lines
10002        } else {
10003            lines
10004        };
10005
10006        self.buffer.update(cx, |buffer, cx| {
10007            let snapshot = buffer.snapshot(cx);
10008            let mut excerpt_ids = selections
10009                .iter()
10010                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10011                .collect::<Vec<_>>();
10012            excerpt_ids.sort();
10013            excerpt_ids.dedup();
10014            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10015        })
10016    }
10017
10018    pub fn expand_excerpt(
10019        &mut self,
10020        excerpt: ExcerptId,
10021        direction: ExpandExcerptDirection,
10022        cx: &mut Context<Self>,
10023    ) {
10024        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10025        self.buffer.update(cx, |buffer, cx| {
10026            buffer.expand_excerpts([excerpt], lines, direction, cx)
10027        })
10028    }
10029
10030    pub fn go_to_singleton_buffer_point(
10031        &mut self,
10032        point: Point,
10033        window: &mut Window,
10034        cx: &mut Context<Self>,
10035    ) {
10036        self.go_to_singleton_buffer_range(point..point, window, cx);
10037    }
10038
10039    pub fn go_to_singleton_buffer_range(
10040        &mut self,
10041        range: Range<Point>,
10042        window: &mut Window,
10043        cx: &mut Context<Self>,
10044    ) {
10045        let multibuffer = self.buffer().read(cx);
10046        let Some(buffer) = multibuffer.as_singleton() else {
10047            return;
10048        };
10049        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10050            return;
10051        };
10052        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10053            return;
10054        };
10055        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10056            s.select_anchor_ranges([start..end])
10057        });
10058    }
10059
10060    fn go_to_diagnostic(
10061        &mut self,
10062        _: &GoToDiagnostic,
10063        window: &mut Window,
10064        cx: &mut Context<Self>,
10065    ) {
10066        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10067    }
10068
10069    fn go_to_prev_diagnostic(
10070        &mut self,
10071        _: &GoToPrevDiagnostic,
10072        window: &mut Window,
10073        cx: &mut Context<Self>,
10074    ) {
10075        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10076    }
10077
10078    pub fn go_to_diagnostic_impl(
10079        &mut self,
10080        direction: Direction,
10081        window: &mut Window,
10082        cx: &mut Context<Self>,
10083    ) {
10084        let buffer = self.buffer.read(cx).snapshot(cx);
10085        let selection = self.selections.newest::<usize>(cx);
10086
10087        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10088        if direction == Direction::Next {
10089            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10090                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10091                    return;
10092                };
10093                self.activate_diagnostics(
10094                    buffer_id,
10095                    popover.local_diagnostic.diagnostic.group_id,
10096                    window,
10097                    cx,
10098                );
10099                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10100                    let primary_range_start = active_diagnostics.primary_range.start;
10101                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10102                        let mut new_selection = s.newest_anchor().clone();
10103                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10104                        s.select_anchors(vec![new_selection.clone()]);
10105                    });
10106                    self.refresh_inline_completion(false, true, window, cx);
10107                }
10108                return;
10109            }
10110        }
10111
10112        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10113            active_diagnostics
10114                .primary_range
10115                .to_offset(&buffer)
10116                .to_inclusive()
10117        });
10118        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10119            if active_primary_range.contains(&selection.head()) {
10120                *active_primary_range.start()
10121            } else {
10122                selection.head()
10123            }
10124        } else {
10125            selection.head()
10126        };
10127        let snapshot = self.snapshot(window, cx);
10128        loop {
10129            let mut diagnostics;
10130            if direction == Direction::Prev {
10131                diagnostics = buffer
10132                    .diagnostics_in_range::<_, usize>(0..search_start)
10133                    .collect::<Vec<_>>();
10134                diagnostics.reverse();
10135            } else {
10136                diagnostics = buffer
10137                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10138                    .collect::<Vec<_>>();
10139            };
10140            let group = diagnostics
10141                .into_iter()
10142                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10143                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10144                // be sorted in a stable way
10145                // skip until we are at current active diagnostic, if it exists
10146                .skip_while(|entry| {
10147                    let is_in_range = match direction {
10148                        Direction::Prev => entry.range.end > search_start,
10149                        Direction::Next => entry.range.start < search_start,
10150                    };
10151                    is_in_range
10152                        && self
10153                            .active_diagnostics
10154                            .as_ref()
10155                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10156                })
10157                .find_map(|entry| {
10158                    if entry.diagnostic.is_primary
10159                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10160                        && entry.range.start != entry.range.end
10161                        // if we match with the active diagnostic, skip it
10162                        && Some(entry.diagnostic.group_id)
10163                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10164                    {
10165                        Some((entry.range, entry.diagnostic.group_id))
10166                    } else {
10167                        None
10168                    }
10169                });
10170
10171            if let Some((primary_range, group_id)) = group {
10172                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10173                    return;
10174                };
10175                self.activate_diagnostics(buffer_id, group_id, window, cx);
10176                if self.active_diagnostics.is_some() {
10177                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10178                        s.select(vec![Selection {
10179                            id: selection.id,
10180                            start: primary_range.start,
10181                            end: primary_range.start,
10182                            reversed: false,
10183                            goal: SelectionGoal::None,
10184                        }]);
10185                    });
10186                    self.refresh_inline_completion(false, true, window, cx);
10187                }
10188                break;
10189            } else {
10190                // Cycle around to the start of the buffer, potentially moving back to the start of
10191                // the currently active diagnostic.
10192                active_primary_range.take();
10193                if direction == Direction::Prev {
10194                    if search_start == buffer.len() {
10195                        break;
10196                    } else {
10197                        search_start = buffer.len();
10198                    }
10199                } else if search_start == 0 {
10200                    break;
10201                } else {
10202                    search_start = 0;
10203                }
10204            }
10205        }
10206    }
10207
10208    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10209        let snapshot = self.snapshot(window, cx);
10210        let selection = self.selections.newest::<Point>(cx);
10211        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10212    }
10213
10214    fn go_to_hunk_after_position(
10215        &mut self,
10216        snapshot: &EditorSnapshot,
10217        position: Point,
10218        window: &mut Window,
10219        cx: &mut Context<Editor>,
10220    ) -> Option<MultiBufferDiffHunk> {
10221        let mut hunk = snapshot
10222            .buffer_snapshot
10223            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10224            .find(|hunk| hunk.row_range.start.0 > position.row);
10225        if hunk.is_none() {
10226            hunk = snapshot
10227                .buffer_snapshot
10228                .diff_hunks_in_range(Point::zero()..position)
10229                .find(|hunk| hunk.row_range.end.0 < position.row)
10230        }
10231        if let Some(hunk) = &hunk {
10232            let destination = Point::new(hunk.row_range.start.0, 0);
10233            self.unfold_ranges(&[destination..destination], false, false, cx);
10234            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10235                s.select_ranges(vec![destination..destination]);
10236            });
10237        }
10238
10239        hunk
10240    }
10241
10242    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10243        let snapshot = self.snapshot(window, cx);
10244        let selection = self.selections.newest::<Point>(cx);
10245        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10246    }
10247
10248    fn go_to_hunk_before_position(
10249        &mut self,
10250        snapshot: &EditorSnapshot,
10251        position: Point,
10252        window: &mut Window,
10253        cx: &mut Context<Editor>,
10254    ) -> Option<MultiBufferDiffHunk> {
10255        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10256        if hunk.is_none() {
10257            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10258        }
10259        if let Some(hunk) = &hunk {
10260            let destination = Point::new(hunk.row_range.start.0, 0);
10261            self.unfold_ranges(&[destination..destination], false, false, cx);
10262            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10263                s.select_ranges(vec![destination..destination]);
10264            });
10265        }
10266
10267        hunk
10268    }
10269
10270    pub fn go_to_definition(
10271        &mut self,
10272        _: &GoToDefinition,
10273        window: &mut Window,
10274        cx: &mut Context<Self>,
10275    ) -> Task<Result<Navigated>> {
10276        let definition =
10277            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10278        cx.spawn_in(window, |editor, mut cx| async move {
10279            if definition.await? == Navigated::Yes {
10280                return Ok(Navigated::Yes);
10281            }
10282            match editor.update_in(&mut cx, |editor, window, cx| {
10283                editor.find_all_references(&FindAllReferences, window, cx)
10284            })? {
10285                Some(references) => references.await,
10286                None => Ok(Navigated::No),
10287            }
10288        })
10289    }
10290
10291    pub fn go_to_declaration(
10292        &mut self,
10293        _: &GoToDeclaration,
10294        window: &mut Window,
10295        cx: &mut Context<Self>,
10296    ) -> Task<Result<Navigated>> {
10297        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10298    }
10299
10300    pub fn go_to_declaration_split(
10301        &mut self,
10302        _: &GoToDeclaration,
10303        window: &mut Window,
10304        cx: &mut Context<Self>,
10305    ) -> Task<Result<Navigated>> {
10306        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10307    }
10308
10309    pub fn go_to_implementation(
10310        &mut self,
10311        _: &GoToImplementation,
10312        window: &mut Window,
10313        cx: &mut Context<Self>,
10314    ) -> Task<Result<Navigated>> {
10315        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10316    }
10317
10318    pub fn go_to_implementation_split(
10319        &mut self,
10320        _: &GoToImplementationSplit,
10321        window: &mut Window,
10322        cx: &mut Context<Self>,
10323    ) -> Task<Result<Navigated>> {
10324        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10325    }
10326
10327    pub fn go_to_type_definition(
10328        &mut self,
10329        _: &GoToTypeDefinition,
10330        window: &mut Window,
10331        cx: &mut Context<Self>,
10332    ) -> Task<Result<Navigated>> {
10333        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10334    }
10335
10336    pub fn go_to_definition_split(
10337        &mut self,
10338        _: &GoToDefinitionSplit,
10339        window: &mut Window,
10340        cx: &mut Context<Self>,
10341    ) -> Task<Result<Navigated>> {
10342        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10343    }
10344
10345    pub fn go_to_type_definition_split(
10346        &mut self,
10347        _: &GoToTypeDefinitionSplit,
10348        window: &mut Window,
10349        cx: &mut Context<Self>,
10350    ) -> Task<Result<Navigated>> {
10351        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10352    }
10353
10354    fn go_to_definition_of_kind(
10355        &mut self,
10356        kind: GotoDefinitionKind,
10357        split: bool,
10358        window: &mut Window,
10359        cx: &mut Context<Self>,
10360    ) -> Task<Result<Navigated>> {
10361        let Some(provider) = self.semantics_provider.clone() else {
10362            return Task::ready(Ok(Navigated::No));
10363        };
10364        let head = self.selections.newest::<usize>(cx).head();
10365        let buffer = self.buffer.read(cx);
10366        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10367            text_anchor
10368        } else {
10369            return Task::ready(Ok(Navigated::No));
10370        };
10371
10372        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10373            return Task::ready(Ok(Navigated::No));
10374        };
10375
10376        cx.spawn_in(window, |editor, mut cx| async move {
10377            let definitions = definitions.await?;
10378            let navigated = editor
10379                .update_in(&mut cx, |editor, window, cx| {
10380                    editor.navigate_to_hover_links(
10381                        Some(kind),
10382                        definitions
10383                            .into_iter()
10384                            .filter(|location| {
10385                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10386                            })
10387                            .map(HoverLink::Text)
10388                            .collect::<Vec<_>>(),
10389                        split,
10390                        window,
10391                        cx,
10392                    )
10393                })?
10394                .await?;
10395            anyhow::Ok(navigated)
10396        })
10397    }
10398
10399    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10400        let selection = self.selections.newest_anchor();
10401        let head = selection.head();
10402        let tail = selection.tail();
10403
10404        let Some((buffer, start_position)) =
10405            self.buffer.read(cx).text_anchor_for_position(head, cx)
10406        else {
10407            return;
10408        };
10409
10410        let end_position = if head != tail {
10411            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10412                return;
10413            };
10414            Some(pos)
10415        } else {
10416            None
10417        };
10418
10419        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10420            let url = if let Some(end_pos) = end_position {
10421                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10422            } else {
10423                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10424            };
10425
10426            if let Some(url) = url {
10427                editor.update(&mut cx, |_, cx| {
10428                    cx.open_url(&url);
10429                })
10430            } else {
10431                Ok(())
10432            }
10433        });
10434
10435        url_finder.detach();
10436    }
10437
10438    pub fn open_selected_filename(
10439        &mut self,
10440        _: &OpenSelectedFilename,
10441        window: &mut Window,
10442        cx: &mut Context<Self>,
10443    ) {
10444        let Some(workspace) = self.workspace() else {
10445            return;
10446        };
10447
10448        let position = self.selections.newest_anchor().head();
10449
10450        let Some((buffer, buffer_position)) =
10451            self.buffer.read(cx).text_anchor_for_position(position, cx)
10452        else {
10453            return;
10454        };
10455
10456        let project = self.project.clone();
10457
10458        cx.spawn_in(window, |_, mut cx| async move {
10459            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10460
10461            if let Some((_, path)) = result {
10462                workspace
10463                    .update_in(&mut cx, |workspace, window, cx| {
10464                        workspace.open_resolved_path(path, window, cx)
10465                    })?
10466                    .await?;
10467            }
10468            anyhow::Ok(())
10469        })
10470        .detach();
10471    }
10472
10473    pub(crate) fn navigate_to_hover_links(
10474        &mut self,
10475        kind: Option<GotoDefinitionKind>,
10476        mut definitions: Vec<HoverLink>,
10477        split: bool,
10478        window: &mut Window,
10479        cx: &mut Context<Editor>,
10480    ) -> Task<Result<Navigated>> {
10481        // If there is one definition, just open it directly
10482        if definitions.len() == 1 {
10483            let definition = definitions.pop().unwrap();
10484
10485            enum TargetTaskResult {
10486                Location(Option<Location>),
10487                AlreadyNavigated,
10488            }
10489
10490            let target_task = match definition {
10491                HoverLink::Text(link) => {
10492                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10493                }
10494                HoverLink::InlayHint(lsp_location, server_id) => {
10495                    let computation =
10496                        self.compute_target_location(lsp_location, server_id, window, cx);
10497                    cx.background_executor().spawn(async move {
10498                        let location = computation.await?;
10499                        Ok(TargetTaskResult::Location(location))
10500                    })
10501                }
10502                HoverLink::Url(url) => {
10503                    cx.open_url(&url);
10504                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10505                }
10506                HoverLink::File(path) => {
10507                    if let Some(workspace) = self.workspace() {
10508                        cx.spawn_in(window, |_, mut cx| async move {
10509                            workspace
10510                                .update_in(&mut cx, |workspace, window, cx| {
10511                                    workspace.open_resolved_path(path, window, cx)
10512                                })?
10513                                .await
10514                                .map(|_| TargetTaskResult::AlreadyNavigated)
10515                        })
10516                    } else {
10517                        Task::ready(Ok(TargetTaskResult::Location(None)))
10518                    }
10519                }
10520            };
10521            cx.spawn_in(window, |editor, mut cx| async move {
10522                let target = match target_task.await.context("target resolution task")? {
10523                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10524                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10525                    TargetTaskResult::Location(Some(target)) => target,
10526                };
10527
10528                editor.update_in(&mut cx, |editor, window, cx| {
10529                    let Some(workspace) = editor.workspace() else {
10530                        return Navigated::No;
10531                    };
10532                    let pane = workspace.read(cx).active_pane().clone();
10533
10534                    let range = target.range.to_point(target.buffer.read(cx));
10535                    let range = editor.range_for_match(&range);
10536                    let range = collapse_multiline_range(range);
10537
10538                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10539                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10540                    } else {
10541                        window.defer(cx, move |window, cx| {
10542                            let target_editor: Entity<Self> =
10543                                workspace.update(cx, |workspace, cx| {
10544                                    let pane = if split {
10545                                        workspace.adjacent_pane(window, cx)
10546                                    } else {
10547                                        workspace.active_pane().clone()
10548                                    };
10549
10550                                    workspace.open_project_item(
10551                                        pane,
10552                                        target.buffer.clone(),
10553                                        true,
10554                                        true,
10555                                        window,
10556                                        cx,
10557                                    )
10558                                });
10559                            target_editor.update(cx, |target_editor, cx| {
10560                                // When selecting a definition in a different buffer, disable the nav history
10561                                // to avoid creating a history entry at the previous cursor location.
10562                                pane.update(cx, |pane, _| pane.disable_history());
10563                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10564                                pane.update(cx, |pane, _| pane.enable_history());
10565                            });
10566                        });
10567                    }
10568                    Navigated::Yes
10569                })
10570            })
10571        } else if !definitions.is_empty() {
10572            cx.spawn_in(window, |editor, mut cx| async move {
10573                let (title, location_tasks, workspace) = editor
10574                    .update_in(&mut cx, |editor, window, cx| {
10575                        let tab_kind = match kind {
10576                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10577                            _ => "Definitions",
10578                        };
10579                        let title = definitions
10580                            .iter()
10581                            .find_map(|definition| match definition {
10582                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10583                                    let buffer = origin.buffer.read(cx);
10584                                    format!(
10585                                        "{} for {}",
10586                                        tab_kind,
10587                                        buffer
10588                                            .text_for_range(origin.range.clone())
10589                                            .collect::<String>()
10590                                    )
10591                                }),
10592                                HoverLink::InlayHint(_, _) => None,
10593                                HoverLink::Url(_) => None,
10594                                HoverLink::File(_) => None,
10595                            })
10596                            .unwrap_or(tab_kind.to_string());
10597                        let location_tasks = definitions
10598                            .into_iter()
10599                            .map(|definition| match definition {
10600                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10601                                HoverLink::InlayHint(lsp_location, server_id) => editor
10602                                    .compute_target_location(lsp_location, server_id, window, cx),
10603                                HoverLink::Url(_) => Task::ready(Ok(None)),
10604                                HoverLink::File(_) => Task::ready(Ok(None)),
10605                            })
10606                            .collect::<Vec<_>>();
10607                        (title, location_tasks, editor.workspace().clone())
10608                    })
10609                    .context("location tasks preparation")?;
10610
10611                let locations = future::join_all(location_tasks)
10612                    .await
10613                    .into_iter()
10614                    .filter_map(|location| location.transpose())
10615                    .collect::<Result<_>>()
10616                    .context("location tasks")?;
10617
10618                let Some(workspace) = workspace else {
10619                    return Ok(Navigated::No);
10620                };
10621                let opened = workspace
10622                    .update_in(&mut cx, |workspace, window, cx| {
10623                        Self::open_locations_in_multibuffer(
10624                            workspace,
10625                            locations,
10626                            title,
10627                            split,
10628                            MultibufferSelectionMode::First,
10629                            window,
10630                            cx,
10631                        )
10632                    })
10633                    .ok();
10634
10635                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10636            })
10637        } else {
10638            Task::ready(Ok(Navigated::No))
10639        }
10640    }
10641
10642    fn compute_target_location(
10643        &self,
10644        lsp_location: lsp::Location,
10645        server_id: LanguageServerId,
10646        window: &mut Window,
10647        cx: &mut Context<Self>,
10648    ) -> Task<anyhow::Result<Option<Location>>> {
10649        let Some(project) = self.project.clone() else {
10650            return Task::ready(Ok(None));
10651        };
10652
10653        cx.spawn_in(window, move |editor, mut cx| async move {
10654            let location_task = editor.update(&mut cx, |_, cx| {
10655                project.update(cx, |project, cx| {
10656                    let language_server_name = project
10657                        .language_server_statuses(cx)
10658                        .find(|(id, _)| server_id == *id)
10659                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10660                    language_server_name.map(|language_server_name| {
10661                        project.open_local_buffer_via_lsp(
10662                            lsp_location.uri.clone(),
10663                            server_id,
10664                            language_server_name,
10665                            cx,
10666                        )
10667                    })
10668                })
10669            })?;
10670            let location = match location_task {
10671                Some(task) => Some({
10672                    let target_buffer_handle = task.await.context("open local buffer")?;
10673                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10674                        let target_start = target_buffer
10675                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10676                        let target_end = target_buffer
10677                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10678                        target_buffer.anchor_after(target_start)
10679                            ..target_buffer.anchor_before(target_end)
10680                    })?;
10681                    Location {
10682                        buffer: target_buffer_handle,
10683                        range,
10684                    }
10685                }),
10686                None => None,
10687            };
10688            Ok(location)
10689        })
10690    }
10691
10692    pub fn find_all_references(
10693        &mut self,
10694        _: &FindAllReferences,
10695        window: &mut Window,
10696        cx: &mut Context<Self>,
10697    ) -> Option<Task<Result<Navigated>>> {
10698        let selection = self.selections.newest::<usize>(cx);
10699        let multi_buffer = self.buffer.read(cx);
10700        let head = selection.head();
10701
10702        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10703        let head_anchor = multi_buffer_snapshot.anchor_at(
10704            head,
10705            if head < selection.tail() {
10706                Bias::Right
10707            } else {
10708                Bias::Left
10709            },
10710        );
10711
10712        match self
10713            .find_all_references_task_sources
10714            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10715        {
10716            Ok(_) => {
10717                log::info!(
10718                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10719                );
10720                return None;
10721            }
10722            Err(i) => {
10723                self.find_all_references_task_sources.insert(i, head_anchor);
10724            }
10725        }
10726
10727        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10728        let workspace = self.workspace()?;
10729        let project = workspace.read(cx).project().clone();
10730        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10731        Some(cx.spawn_in(window, |editor, mut cx| async move {
10732            let _cleanup = defer({
10733                let mut cx = cx.clone();
10734                move || {
10735                    let _ = editor.update(&mut cx, |editor, _| {
10736                        if let Ok(i) =
10737                            editor
10738                                .find_all_references_task_sources
10739                                .binary_search_by(|anchor| {
10740                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10741                                })
10742                        {
10743                            editor.find_all_references_task_sources.remove(i);
10744                        }
10745                    });
10746                }
10747            });
10748
10749            let locations = references.await?;
10750            if locations.is_empty() {
10751                return anyhow::Ok(Navigated::No);
10752            }
10753
10754            workspace.update_in(&mut cx, |workspace, window, cx| {
10755                let title = locations
10756                    .first()
10757                    .as_ref()
10758                    .map(|location| {
10759                        let buffer = location.buffer.read(cx);
10760                        format!(
10761                            "References to `{}`",
10762                            buffer
10763                                .text_for_range(location.range.clone())
10764                                .collect::<String>()
10765                        )
10766                    })
10767                    .unwrap();
10768                Self::open_locations_in_multibuffer(
10769                    workspace,
10770                    locations,
10771                    title,
10772                    false,
10773                    MultibufferSelectionMode::First,
10774                    window,
10775                    cx,
10776                );
10777                Navigated::Yes
10778            })
10779        }))
10780    }
10781
10782    /// Opens a multibuffer with the given project locations in it
10783    pub fn open_locations_in_multibuffer(
10784        workspace: &mut Workspace,
10785        mut locations: Vec<Location>,
10786        title: String,
10787        split: bool,
10788        multibuffer_selection_mode: MultibufferSelectionMode,
10789        window: &mut Window,
10790        cx: &mut Context<Workspace>,
10791    ) {
10792        // If there are multiple definitions, open them in a multibuffer
10793        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10794        let mut locations = locations.into_iter().peekable();
10795        let mut ranges = Vec::new();
10796        let capability = workspace.project().read(cx).capability();
10797
10798        let excerpt_buffer = cx.new(|cx| {
10799            let mut multibuffer = MultiBuffer::new(capability);
10800            while let Some(location) = locations.next() {
10801                let buffer = location.buffer.read(cx);
10802                let mut ranges_for_buffer = Vec::new();
10803                let range = location.range.to_offset(buffer);
10804                ranges_for_buffer.push(range.clone());
10805
10806                while let Some(next_location) = locations.peek() {
10807                    if next_location.buffer == location.buffer {
10808                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10809                        locations.next();
10810                    } else {
10811                        break;
10812                    }
10813                }
10814
10815                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10816                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10817                    location.buffer.clone(),
10818                    ranges_for_buffer,
10819                    DEFAULT_MULTIBUFFER_CONTEXT,
10820                    cx,
10821                ))
10822            }
10823
10824            multibuffer.with_title(title)
10825        });
10826
10827        let editor = cx.new(|cx| {
10828            Editor::for_multibuffer(
10829                excerpt_buffer,
10830                Some(workspace.project().clone()),
10831                true,
10832                window,
10833                cx,
10834            )
10835        });
10836        editor.update(cx, |editor, cx| {
10837            match multibuffer_selection_mode {
10838                MultibufferSelectionMode::First => {
10839                    if let Some(first_range) = ranges.first() {
10840                        editor.change_selections(None, window, cx, |selections| {
10841                            selections.clear_disjoint();
10842                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10843                        });
10844                    }
10845                    editor.highlight_background::<Self>(
10846                        &ranges,
10847                        |theme| theme.editor_highlighted_line_background,
10848                        cx,
10849                    );
10850                }
10851                MultibufferSelectionMode::All => {
10852                    editor.change_selections(None, window, cx, |selections| {
10853                        selections.clear_disjoint();
10854                        selections.select_anchor_ranges(ranges);
10855                    });
10856                }
10857            }
10858            editor.register_buffers_with_language_servers(cx);
10859        });
10860
10861        let item = Box::new(editor);
10862        let item_id = item.item_id();
10863
10864        if split {
10865            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10866        } else {
10867            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10868                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10869                    pane.close_current_preview_item(window, cx)
10870                } else {
10871                    None
10872                }
10873            });
10874            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10875        }
10876        workspace.active_pane().update(cx, |pane, cx| {
10877            pane.set_preview_item_id(Some(item_id), cx);
10878        });
10879    }
10880
10881    pub fn rename(
10882        &mut self,
10883        _: &Rename,
10884        window: &mut Window,
10885        cx: &mut Context<Self>,
10886    ) -> Option<Task<Result<()>>> {
10887        use language::ToOffset as _;
10888
10889        let provider = self.semantics_provider.clone()?;
10890        let selection = self.selections.newest_anchor().clone();
10891        let (cursor_buffer, cursor_buffer_position) = self
10892            .buffer
10893            .read(cx)
10894            .text_anchor_for_position(selection.head(), cx)?;
10895        let (tail_buffer, cursor_buffer_position_end) = self
10896            .buffer
10897            .read(cx)
10898            .text_anchor_for_position(selection.tail(), cx)?;
10899        if tail_buffer != cursor_buffer {
10900            return None;
10901        }
10902
10903        let snapshot = cursor_buffer.read(cx).snapshot();
10904        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10905        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10906        let prepare_rename = provider
10907            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10908            .unwrap_or_else(|| Task::ready(Ok(None)));
10909        drop(snapshot);
10910
10911        Some(cx.spawn_in(window, |this, mut cx| async move {
10912            let rename_range = if let Some(range) = prepare_rename.await? {
10913                Some(range)
10914            } else {
10915                this.update(&mut cx, |this, cx| {
10916                    let buffer = this.buffer.read(cx).snapshot(cx);
10917                    let mut buffer_highlights = this
10918                        .document_highlights_for_position(selection.head(), &buffer)
10919                        .filter(|highlight| {
10920                            highlight.start.excerpt_id == selection.head().excerpt_id
10921                                && highlight.end.excerpt_id == selection.head().excerpt_id
10922                        });
10923                    buffer_highlights
10924                        .next()
10925                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10926                })?
10927            };
10928            if let Some(rename_range) = rename_range {
10929                this.update_in(&mut cx, |this, window, cx| {
10930                    let snapshot = cursor_buffer.read(cx).snapshot();
10931                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10932                    let cursor_offset_in_rename_range =
10933                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10934                    let cursor_offset_in_rename_range_end =
10935                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10936
10937                    this.take_rename(false, window, cx);
10938                    let buffer = this.buffer.read(cx).read(cx);
10939                    let cursor_offset = selection.head().to_offset(&buffer);
10940                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10941                    let rename_end = rename_start + rename_buffer_range.len();
10942                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10943                    let mut old_highlight_id = None;
10944                    let old_name: Arc<str> = buffer
10945                        .chunks(rename_start..rename_end, true)
10946                        .map(|chunk| {
10947                            if old_highlight_id.is_none() {
10948                                old_highlight_id = chunk.syntax_highlight_id;
10949                            }
10950                            chunk.text
10951                        })
10952                        .collect::<String>()
10953                        .into();
10954
10955                    drop(buffer);
10956
10957                    // Position the selection in the rename editor so that it matches the current selection.
10958                    this.show_local_selections = false;
10959                    let rename_editor = cx.new(|cx| {
10960                        let mut editor = Editor::single_line(window, cx);
10961                        editor.buffer.update(cx, |buffer, cx| {
10962                            buffer.edit([(0..0, old_name.clone())], None, cx)
10963                        });
10964                        let rename_selection_range = match cursor_offset_in_rename_range
10965                            .cmp(&cursor_offset_in_rename_range_end)
10966                        {
10967                            Ordering::Equal => {
10968                                editor.select_all(&SelectAll, window, cx);
10969                                return editor;
10970                            }
10971                            Ordering::Less => {
10972                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10973                            }
10974                            Ordering::Greater => {
10975                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10976                            }
10977                        };
10978                        if rename_selection_range.end > old_name.len() {
10979                            editor.select_all(&SelectAll, window, cx);
10980                        } else {
10981                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10982                                s.select_ranges([rename_selection_range]);
10983                            });
10984                        }
10985                        editor
10986                    });
10987                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10988                        if e == &EditorEvent::Focused {
10989                            cx.emit(EditorEvent::FocusedIn)
10990                        }
10991                    })
10992                    .detach();
10993
10994                    let write_highlights =
10995                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10996                    let read_highlights =
10997                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10998                    let ranges = write_highlights
10999                        .iter()
11000                        .flat_map(|(_, ranges)| ranges.iter())
11001                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11002                        .cloned()
11003                        .collect();
11004
11005                    this.highlight_text::<Rename>(
11006                        ranges,
11007                        HighlightStyle {
11008                            fade_out: Some(0.6),
11009                            ..Default::default()
11010                        },
11011                        cx,
11012                    );
11013                    let rename_focus_handle = rename_editor.focus_handle(cx);
11014                    window.focus(&rename_focus_handle);
11015                    let block_id = this.insert_blocks(
11016                        [BlockProperties {
11017                            style: BlockStyle::Flex,
11018                            placement: BlockPlacement::Below(range.start),
11019                            height: 1,
11020                            render: Arc::new({
11021                                let rename_editor = rename_editor.clone();
11022                                move |cx: &mut BlockContext| {
11023                                    let mut text_style = cx.editor_style.text.clone();
11024                                    if let Some(highlight_style) = old_highlight_id
11025                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11026                                    {
11027                                        text_style = text_style.highlight(highlight_style);
11028                                    }
11029                                    div()
11030                                        .block_mouse_down()
11031                                        .pl(cx.anchor_x)
11032                                        .child(EditorElement::new(
11033                                            &rename_editor,
11034                                            EditorStyle {
11035                                                background: cx.theme().system().transparent,
11036                                                local_player: cx.editor_style.local_player,
11037                                                text: text_style,
11038                                                scrollbar_width: cx.editor_style.scrollbar_width,
11039                                                syntax: cx.editor_style.syntax.clone(),
11040                                                status: cx.editor_style.status.clone(),
11041                                                inlay_hints_style: HighlightStyle {
11042                                                    font_weight: Some(FontWeight::BOLD),
11043                                                    ..make_inlay_hints_style(cx.app)
11044                                                },
11045                                                inline_completion_styles: make_suggestion_styles(
11046                                                    cx.app,
11047                                                ),
11048                                                ..EditorStyle::default()
11049                                            },
11050                                        ))
11051                                        .into_any_element()
11052                                }
11053                            }),
11054                            priority: 0,
11055                        }],
11056                        Some(Autoscroll::fit()),
11057                        cx,
11058                    )[0];
11059                    this.pending_rename = Some(RenameState {
11060                        range,
11061                        old_name,
11062                        editor: rename_editor,
11063                        block_id,
11064                    });
11065                })?;
11066            }
11067
11068            Ok(())
11069        }))
11070    }
11071
11072    pub fn confirm_rename(
11073        &mut self,
11074        _: &ConfirmRename,
11075        window: &mut Window,
11076        cx: &mut Context<Self>,
11077    ) -> Option<Task<Result<()>>> {
11078        let rename = self.take_rename(false, window, cx)?;
11079        let workspace = self.workspace()?.downgrade();
11080        let (buffer, start) = self
11081            .buffer
11082            .read(cx)
11083            .text_anchor_for_position(rename.range.start, cx)?;
11084        let (end_buffer, _) = self
11085            .buffer
11086            .read(cx)
11087            .text_anchor_for_position(rename.range.end, cx)?;
11088        if buffer != end_buffer {
11089            return None;
11090        }
11091
11092        let old_name = rename.old_name;
11093        let new_name = rename.editor.read(cx).text(cx);
11094
11095        let rename = self.semantics_provider.as_ref()?.perform_rename(
11096            &buffer,
11097            start,
11098            new_name.clone(),
11099            cx,
11100        )?;
11101
11102        Some(cx.spawn_in(window, |editor, mut cx| async move {
11103            let project_transaction = rename.await?;
11104            Self::open_project_transaction(
11105                &editor,
11106                workspace,
11107                project_transaction,
11108                format!("Rename: {}{}", old_name, new_name),
11109                cx.clone(),
11110            )
11111            .await?;
11112
11113            editor.update(&mut cx, |editor, cx| {
11114                editor.refresh_document_highlights(cx);
11115            })?;
11116            Ok(())
11117        }))
11118    }
11119
11120    fn take_rename(
11121        &mut self,
11122        moving_cursor: bool,
11123        window: &mut Window,
11124        cx: &mut Context<Self>,
11125    ) -> Option<RenameState> {
11126        let rename = self.pending_rename.take()?;
11127        if rename.editor.focus_handle(cx).is_focused(window) {
11128            window.focus(&self.focus_handle);
11129        }
11130
11131        self.remove_blocks(
11132            [rename.block_id].into_iter().collect(),
11133            Some(Autoscroll::fit()),
11134            cx,
11135        );
11136        self.clear_highlights::<Rename>(cx);
11137        self.show_local_selections = true;
11138
11139        if moving_cursor {
11140            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11141                editor.selections.newest::<usize>(cx).head()
11142            });
11143
11144            // Update the selection to match the position of the selection inside
11145            // the rename editor.
11146            let snapshot = self.buffer.read(cx).read(cx);
11147            let rename_range = rename.range.to_offset(&snapshot);
11148            let cursor_in_editor = snapshot
11149                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11150                .min(rename_range.end);
11151            drop(snapshot);
11152
11153            self.change_selections(None, window, cx, |s| {
11154                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11155            });
11156        } else {
11157            self.refresh_document_highlights(cx);
11158        }
11159
11160        Some(rename)
11161    }
11162
11163    pub fn pending_rename(&self) -> Option<&RenameState> {
11164        self.pending_rename.as_ref()
11165    }
11166
11167    fn format(
11168        &mut self,
11169        _: &Format,
11170        window: &mut Window,
11171        cx: &mut Context<Self>,
11172    ) -> Option<Task<Result<()>>> {
11173        let project = match &self.project {
11174            Some(project) => project.clone(),
11175            None => return None,
11176        };
11177
11178        Some(self.perform_format(
11179            project,
11180            FormatTrigger::Manual,
11181            FormatTarget::Buffers,
11182            window,
11183            cx,
11184        ))
11185    }
11186
11187    fn format_selections(
11188        &mut self,
11189        _: &FormatSelections,
11190        window: &mut Window,
11191        cx: &mut Context<Self>,
11192    ) -> Option<Task<Result<()>>> {
11193        let project = match &self.project {
11194            Some(project) => project.clone(),
11195            None => return None,
11196        };
11197
11198        let ranges = self
11199            .selections
11200            .all_adjusted(cx)
11201            .into_iter()
11202            .map(|selection| selection.range())
11203            .collect_vec();
11204
11205        Some(self.perform_format(
11206            project,
11207            FormatTrigger::Manual,
11208            FormatTarget::Ranges(ranges),
11209            window,
11210            cx,
11211        ))
11212    }
11213
11214    fn perform_format(
11215        &mut self,
11216        project: Entity<Project>,
11217        trigger: FormatTrigger,
11218        target: FormatTarget,
11219        window: &mut Window,
11220        cx: &mut Context<Self>,
11221    ) -> Task<Result<()>> {
11222        let buffer = self.buffer.clone();
11223        let (buffers, target) = match target {
11224            FormatTarget::Buffers => {
11225                let mut buffers = buffer.read(cx).all_buffers();
11226                if trigger == FormatTrigger::Save {
11227                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11228                }
11229                (buffers, LspFormatTarget::Buffers)
11230            }
11231            FormatTarget::Ranges(selection_ranges) => {
11232                let multi_buffer = buffer.read(cx);
11233                let snapshot = multi_buffer.read(cx);
11234                let mut buffers = HashSet::default();
11235                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11236                    BTreeMap::new();
11237                for selection_range in selection_ranges {
11238                    for (buffer, buffer_range, _) in
11239                        snapshot.range_to_buffer_ranges(selection_range)
11240                    {
11241                        let buffer_id = buffer.remote_id();
11242                        let start = buffer.anchor_before(buffer_range.start);
11243                        let end = buffer.anchor_after(buffer_range.end);
11244                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11245                        buffer_id_to_ranges
11246                            .entry(buffer_id)
11247                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11248                            .or_insert_with(|| vec![start..end]);
11249                    }
11250                }
11251                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11252            }
11253        };
11254
11255        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11256        let format = project.update(cx, |project, cx| {
11257            project.format(buffers, target, true, trigger, cx)
11258        });
11259
11260        cx.spawn_in(window, |_, mut cx| async move {
11261            let transaction = futures::select_biased! {
11262                () = timeout => {
11263                    log::warn!("timed out waiting for formatting");
11264                    None
11265                }
11266                transaction = format.log_err().fuse() => transaction,
11267            };
11268
11269            buffer
11270                .update(&mut cx, |buffer, cx| {
11271                    if let Some(transaction) = transaction {
11272                        if !buffer.is_singleton() {
11273                            buffer.push_transaction(&transaction.0, cx);
11274                        }
11275                    }
11276
11277                    cx.notify();
11278                })
11279                .ok();
11280
11281            Ok(())
11282        })
11283    }
11284
11285    fn restart_language_server(
11286        &mut self,
11287        _: &RestartLanguageServer,
11288        _: &mut Window,
11289        cx: &mut Context<Self>,
11290    ) {
11291        if let Some(project) = self.project.clone() {
11292            self.buffer.update(cx, |multi_buffer, cx| {
11293                project.update(cx, |project, cx| {
11294                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11295                });
11296            })
11297        }
11298    }
11299
11300    fn cancel_language_server_work(
11301        &mut self,
11302        _: &actions::CancelLanguageServerWork,
11303        _: &mut Window,
11304        cx: &mut Context<Self>,
11305    ) {
11306        if let Some(project) = self.project.clone() {
11307            self.buffer.update(cx, |multi_buffer, cx| {
11308                project.update(cx, |project, cx| {
11309                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11310                });
11311            })
11312        }
11313    }
11314
11315    fn show_character_palette(
11316        &mut self,
11317        _: &ShowCharacterPalette,
11318        window: &mut Window,
11319        _: &mut Context<Self>,
11320    ) {
11321        window.show_character_palette();
11322    }
11323
11324    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11325        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11326            let buffer = self.buffer.read(cx).snapshot(cx);
11327            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11328            let is_valid = buffer
11329                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11330                .any(|entry| {
11331                    entry.diagnostic.is_primary
11332                        && !entry.range.is_empty()
11333                        && entry.range.start == primary_range_start
11334                        && entry.diagnostic.message == active_diagnostics.primary_message
11335                });
11336
11337            if is_valid != active_diagnostics.is_valid {
11338                active_diagnostics.is_valid = is_valid;
11339                let mut new_styles = HashMap::default();
11340                for (block_id, diagnostic) in &active_diagnostics.blocks {
11341                    new_styles.insert(
11342                        *block_id,
11343                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11344                    );
11345                }
11346                self.display_map.update(cx, |display_map, _cx| {
11347                    display_map.replace_blocks(new_styles)
11348                });
11349            }
11350        }
11351    }
11352
11353    fn activate_diagnostics(
11354        &mut self,
11355        buffer_id: BufferId,
11356        group_id: usize,
11357        window: &mut Window,
11358        cx: &mut Context<Self>,
11359    ) {
11360        self.dismiss_diagnostics(cx);
11361        let snapshot = self.snapshot(window, cx);
11362        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11363            let buffer = self.buffer.read(cx).snapshot(cx);
11364
11365            let mut primary_range = None;
11366            let mut primary_message = None;
11367            let diagnostic_group = buffer
11368                .diagnostic_group(buffer_id, group_id)
11369                .filter_map(|entry| {
11370                    let start = entry.range.start;
11371                    let end = entry.range.end;
11372                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11373                        && (start.row == end.row
11374                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11375                    {
11376                        return None;
11377                    }
11378                    if entry.diagnostic.is_primary {
11379                        primary_range = Some(entry.range.clone());
11380                        primary_message = Some(entry.diagnostic.message.clone());
11381                    }
11382                    Some(entry)
11383                })
11384                .collect::<Vec<_>>();
11385            let primary_range = primary_range?;
11386            let primary_message = primary_message?;
11387
11388            let blocks = display_map
11389                .insert_blocks(
11390                    diagnostic_group.iter().map(|entry| {
11391                        let diagnostic = entry.diagnostic.clone();
11392                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11393                        BlockProperties {
11394                            style: BlockStyle::Fixed,
11395                            placement: BlockPlacement::Below(
11396                                buffer.anchor_after(entry.range.start),
11397                            ),
11398                            height: message_height,
11399                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11400                            priority: 0,
11401                        }
11402                    }),
11403                    cx,
11404                )
11405                .into_iter()
11406                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11407                .collect();
11408
11409            Some(ActiveDiagnosticGroup {
11410                primary_range: buffer.anchor_before(primary_range.start)
11411                    ..buffer.anchor_after(primary_range.end),
11412                primary_message,
11413                group_id,
11414                blocks,
11415                is_valid: true,
11416            })
11417        });
11418    }
11419
11420    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11421        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11422            self.display_map.update(cx, |display_map, cx| {
11423                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11424            });
11425            cx.notify();
11426        }
11427    }
11428
11429    pub fn set_selections_from_remote(
11430        &mut self,
11431        selections: Vec<Selection<Anchor>>,
11432        pending_selection: Option<Selection<Anchor>>,
11433        window: &mut Window,
11434        cx: &mut Context<Self>,
11435    ) {
11436        let old_cursor_position = self.selections.newest_anchor().head();
11437        self.selections.change_with(cx, |s| {
11438            s.select_anchors(selections);
11439            if let Some(pending_selection) = pending_selection {
11440                s.set_pending(pending_selection, SelectMode::Character);
11441            } else {
11442                s.clear_pending();
11443            }
11444        });
11445        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11446    }
11447
11448    fn push_to_selection_history(&mut self) {
11449        self.selection_history.push(SelectionHistoryEntry {
11450            selections: self.selections.disjoint_anchors(),
11451            select_next_state: self.select_next_state.clone(),
11452            select_prev_state: self.select_prev_state.clone(),
11453            add_selections_state: self.add_selections_state.clone(),
11454        });
11455    }
11456
11457    pub fn transact(
11458        &mut self,
11459        window: &mut Window,
11460        cx: &mut Context<Self>,
11461        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11462    ) -> Option<TransactionId> {
11463        self.start_transaction_at(Instant::now(), window, cx);
11464        update(self, window, cx);
11465        self.end_transaction_at(Instant::now(), cx)
11466    }
11467
11468    pub fn start_transaction_at(
11469        &mut self,
11470        now: Instant,
11471        window: &mut Window,
11472        cx: &mut Context<Self>,
11473    ) {
11474        self.end_selection(window, cx);
11475        if let Some(tx_id) = self
11476            .buffer
11477            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11478        {
11479            self.selection_history
11480                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11481            cx.emit(EditorEvent::TransactionBegun {
11482                transaction_id: tx_id,
11483            })
11484        }
11485    }
11486
11487    pub fn end_transaction_at(
11488        &mut self,
11489        now: Instant,
11490        cx: &mut Context<Self>,
11491    ) -> Option<TransactionId> {
11492        if let Some(transaction_id) = self
11493            .buffer
11494            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11495        {
11496            if let Some((_, end_selections)) =
11497                self.selection_history.transaction_mut(transaction_id)
11498            {
11499                *end_selections = Some(self.selections.disjoint_anchors());
11500            } else {
11501                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11502            }
11503
11504            cx.emit(EditorEvent::Edited { transaction_id });
11505            Some(transaction_id)
11506        } else {
11507            None
11508        }
11509    }
11510
11511    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11512        if self.selection_mark_mode {
11513            self.change_selections(None, window, cx, |s| {
11514                s.move_with(|_, sel| {
11515                    sel.collapse_to(sel.head(), SelectionGoal::None);
11516                });
11517            })
11518        }
11519        self.selection_mark_mode = true;
11520        cx.notify();
11521    }
11522
11523    pub fn swap_selection_ends(
11524        &mut self,
11525        _: &actions::SwapSelectionEnds,
11526        window: &mut Window,
11527        cx: &mut Context<Self>,
11528    ) {
11529        self.change_selections(None, window, cx, |s| {
11530            s.move_with(|_, sel| {
11531                if sel.start != sel.end {
11532                    sel.reversed = !sel.reversed
11533                }
11534            });
11535        });
11536        self.request_autoscroll(Autoscroll::newest(), cx);
11537        cx.notify();
11538    }
11539
11540    pub fn toggle_fold(
11541        &mut self,
11542        _: &actions::ToggleFold,
11543        window: &mut Window,
11544        cx: &mut Context<Self>,
11545    ) {
11546        if self.is_singleton(cx) {
11547            let selection = self.selections.newest::<Point>(cx);
11548
11549            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11550            let range = if selection.is_empty() {
11551                let point = selection.head().to_display_point(&display_map);
11552                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11553                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11554                    .to_point(&display_map);
11555                start..end
11556            } else {
11557                selection.range()
11558            };
11559            if display_map.folds_in_range(range).next().is_some() {
11560                self.unfold_lines(&Default::default(), window, cx)
11561            } else {
11562                self.fold(&Default::default(), window, cx)
11563            }
11564        } else {
11565            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11566            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11567                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11568                .map(|(snapshot, _, _)| snapshot.remote_id())
11569                .collect();
11570
11571            for buffer_id in buffer_ids {
11572                if self.is_buffer_folded(buffer_id, cx) {
11573                    self.unfold_buffer(buffer_id, cx);
11574                } else {
11575                    self.fold_buffer(buffer_id, cx);
11576                }
11577            }
11578        }
11579    }
11580
11581    pub fn toggle_fold_recursive(
11582        &mut self,
11583        _: &actions::ToggleFoldRecursive,
11584        window: &mut Window,
11585        cx: &mut Context<Self>,
11586    ) {
11587        let selection = self.selections.newest::<Point>(cx);
11588
11589        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11590        let range = if selection.is_empty() {
11591            let point = selection.head().to_display_point(&display_map);
11592            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11593            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11594                .to_point(&display_map);
11595            start..end
11596        } else {
11597            selection.range()
11598        };
11599        if display_map.folds_in_range(range).next().is_some() {
11600            self.unfold_recursive(&Default::default(), window, cx)
11601        } else {
11602            self.fold_recursive(&Default::default(), window, cx)
11603        }
11604    }
11605
11606    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11607        if self.is_singleton(cx) {
11608            let mut to_fold = Vec::new();
11609            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11610            let selections = self.selections.all_adjusted(cx);
11611
11612            for selection in selections {
11613                let range = selection.range().sorted();
11614                let buffer_start_row = range.start.row;
11615
11616                if range.start.row != range.end.row {
11617                    let mut found = false;
11618                    let mut row = range.start.row;
11619                    while row <= range.end.row {
11620                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11621                        {
11622                            found = true;
11623                            row = crease.range().end.row + 1;
11624                            to_fold.push(crease);
11625                        } else {
11626                            row += 1
11627                        }
11628                    }
11629                    if found {
11630                        continue;
11631                    }
11632                }
11633
11634                for row in (0..=range.start.row).rev() {
11635                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11636                        if crease.range().end.row >= buffer_start_row {
11637                            to_fold.push(crease);
11638                            if row <= range.start.row {
11639                                break;
11640                            }
11641                        }
11642                    }
11643                }
11644            }
11645
11646            self.fold_creases(to_fold, true, window, cx);
11647        } else {
11648            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11649
11650            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11651                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11652                .map(|(snapshot, _, _)| snapshot.remote_id())
11653                .collect();
11654            for buffer_id in buffer_ids {
11655                self.fold_buffer(buffer_id, cx);
11656            }
11657        }
11658    }
11659
11660    fn fold_at_level(
11661        &mut self,
11662        fold_at: &FoldAtLevel,
11663        window: &mut Window,
11664        cx: &mut Context<Self>,
11665    ) {
11666        if !self.buffer.read(cx).is_singleton() {
11667            return;
11668        }
11669
11670        let fold_at_level = fold_at.level;
11671        let snapshot = self.buffer.read(cx).snapshot(cx);
11672        let mut to_fold = Vec::new();
11673        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11674
11675        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11676            while start_row < end_row {
11677                match self
11678                    .snapshot(window, cx)
11679                    .crease_for_buffer_row(MultiBufferRow(start_row))
11680                {
11681                    Some(crease) => {
11682                        let nested_start_row = crease.range().start.row + 1;
11683                        let nested_end_row = crease.range().end.row;
11684
11685                        if current_level < fold_at_level {
11686                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11687                        } else if current_level == fold_at_level {
11688                            to_fold.push(crease);
11689                        }
11690
11691                        start_row = nested_end_row + 1;
11692                    }
11693                    None => start_row += 1,
11694                }
11695            }
11696        }
11697
11698        self.fold_creases(to_fold, true, window, cx);
11699    }
11700
11701    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11702        if self.buffer.read(cx).is_singleton() {
11703            let mut fold_ranges = Vec::new();
11704            let snapshot = self.buffer.read(cx).snapshot(cx);
11705
11706            for row in 0..snapshot.max_row().0 {
11707                if let Some(foldable_range) = self
11708                    .snapshot(window, cx)
11709                    .crease_for_buffer_row(MultiBufferRow(row))
11710                {
11711                    fold_ranges.push(foldable_range);
11712                }
11713            }
11714
11715            self.fold_creases(fold_ranges, true, window, cx);
11716        } else {
11717            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11718                editor
11719                    .update_in(&mut cx, |editor, _, cx| {
11720                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11721                            editor.fold_buffer(buffer_id, cx);
11722                        }
11723                    })
11724                    .ok();
11725            });
11726        }
11727    }
11728
11729    pub fn fold_function_bodies(
11730        &mut self,
11731        _: &actions::FoldFunctionBodies,
11732        window: &mut Window,
11733        cx: &mut Context<Self>,
11734    ) {
11735        let snapshot = self.buffer.read(cx).snapshot(cx);
11736
11737        let ranges = snapshot
11738            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11739            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11740            .collect::<Vec<_>>();
11741
11742        let creases = ranges
11743            .into_iter()
11744            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11745            .collect();
11746
11747        self.fold_creases(creases, true, window, cx);
11748    }
11749
11750    pub fn fold_recursive(
11751        &mut self,
11752        _: &actions::FoldRecursive,
11753        window: &mut Window,
11754        cx: &mut Context<Self>,
11755    ) {
11756        let mut to_fold = Vec::new();
11757        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11758        let selections = self.selections.all_adjusted(cx);
11759
11760        for selection in selections {
11761            let range = selection.range().sorted();
11762            let buffer_start_row = range.start.row;
11763
11764            if range.start.row != range.end.row {
11765                let mut found = false;
11766                for row in range.start.row..=range.end.row {
11767                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11768                        found = true;
11769                        to_fold.push(crease);
11770                    }
11771                }
11772                if found {
11773                    continue;
11774                }
11775            }
11776
11777            for row in (0..=range.start.row).rev() {
11778                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11779                    if crease.range().end.row >= buffer_start_row {
11780                        to_fold.push(crease);
11781                    } else {
11782                        break;
11783                    }
11784                }
11785            }
11786        }
11787
11788        self.fold_creases(to_fold, true, window, cx);
11789    }
11790
11791    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11792        let buffer_row = fold_at.buffer_row;
11793        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11794
11795        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11796            let autoscroll = self
11797                .selections
11798                .all::<Point>(cx)
11799                .iter()
11800                .any(|selection| crease.range().overlaps(&selection.range()));
11801
11802            self.fold_creases(vec![crease], autoscroll, window, cx);
11803        }
11804    }
11805
11806    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11807        if self.is_singleton(cx) {
11808            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11809            let buffer = &display_map.buffer_snapshot;
11810            let selections = self.selections.all::<Point>(cx);
11811            let ranges = selections
11812                .iter()
11813                .map(|s| {
11814                    let range = s.display_range(&display_map).sorted();
11815                    let mut start = range.start.to_point(&display_map);
11816                    let mut end = range.end.to_point(&display_map);
11817                    start.column = 0;
11818                    end.column = buffer.line_len(MultiBufferRow(end.row));
11819                    start..end
11820                })
11821                .collect::<Vec<_>>();
11822
11823            self.unfold_ranges(&ranges, true, true, cx);
11824        } else {
11825            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11826            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11827                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11828                .map(|(snapshot, _, _)| snapshot.remote_id())
11829                .collect();
11830            for buffer_id in buffer_ids {
11831                self.unfold_buffer(buffer_id, cx);
11832            }
11833        }
11834    }
11835
11836    pub fn unfold_recursive(
11837        &mut self,
11838        _: &UnfoldRecursive,
11839        _window: &mut Window,
11840        cx: &mut Context<Self>,
11841    ) {
11842        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11843        let selections = self.selections.all::<Point>(cx);
11844        let ranges = selections
11845            .iter()
11846            .map(|s| {
11847                let mut range = s.display_range(&display_map).sorted();
11848                *range.start.column_mut() = 0;
11849                *range.end.column_mut() = display_map.line_len(range.end.row());
11850                let start = range.start.to_point(&display_map);
11851                let end = range.end.to_point(&display_map);
11852                start..end
11853            })
11854            .collect::<Vec<_>>();
11855
11856        self.unfold_ranges(&ranges, true, true, cx);
11857    }
11858
11859    pub fn unfold_at(
11860        &mut self,
11861        unfold_at: &UnfoldAt,
11862        _window: &mut Window,
11863        cx: &mut Context<Self>,
11864    ) {
11865        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11866
11867        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11868            ..Point::new(
11869                unfold_at.buffer_row.0,
11870                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11871            );
11872
11873        let autoscroll = self
11874            .selections
11875            .all::<Point>(cx)
11876            .iter()
11877            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11878
11879        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11880    }
11881
11882    pub fn unfold_all(
11883        &mut self,
11884        _: &actions::UnfoldAll,
11885        _window: &mut Window,
11886        cx: &mut Context<Self>,
11887    ) {
11888        if self.buffer.read(cx).is_singleton() {
11889            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11890            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11891        } else {
11892            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11893                editor
11894                    .update(&mut cx, |editor, cx| {
11895                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11896                            editor.unfold_buffer(buffer_id, cx);
11897                        }
11898                    })
11899                    .ok();
11900            });
11901        }
11902    }
11903
11904    pub fn fold_selected_ranges(
11905        &mut self,
11906        _: &FoldSelectedRanges,
11907        window: &mut Window,
11908        cx: &mut Context<Self>,
11909    ) {
11910        let selections = self.selections.all::<Point>(cx);
11911        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11912        let line_mode = self.selections.line_mode;
11913        let ranges = selections
11914            .into_iter()
11915            .map(|s| {
11916                if line_mode {
11917                    let start = Point::new(s.start.row, 0);
11918                    let end = Point::new(
11919                        s.end.row,
11920                        display_map
11921                            .buffer_snapshot
11922                            .line_len(MultiBufferRow(s.end.row)),
11923                    );
11924                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11925                } else {
11926                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11927                }
11928            })
11929            .collect::<Vec<_>>();
11930        self.fold_creases(ranges, true, window, cx);
11931    }
11932
11933    pub fn fold_ranges<T: ToOffset + Clone>(
11934        &mut self,
11935        ranges: Vec<Range<T>>,
11936        auto_scroll: bool,
11937        window: &mut Window,
11938        cx: &mut Context<Self>,
11939    ) {
11940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941        let ranges = ranges
11942            .into_iter()
11943            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11944            .collect::<Vec<_>>();
11945        self.fold_creases(ranges, auto_scroll, window, cx);
11946    }
11947
11948    pub fn fold_creases<T: ToOffset + Clone>(
11949        &mut self,
11950        creases: Vec<Crease<T>>,
11951        auto_scroll: bool,
11952        window: &mut Window,
11953        cx: &mut Context<Self>,
11954    ) {
11955        if creases.is_empty() {
11956            return;
11957        }
11958
11959        let mut buffers_affected = HashSet::default();
11960        let multi_buffer = self.buffer().read(cx);
11961        for crease in &creases {
11962            if let Some((_, buffer, _)) =
11963                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11964            {
11965                buffers_affected.insert(buffer.read(cx).remote_id());
11966            };
11967        }
11968
11969        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11970
11971        if auto_scroll {
11972            self.request_autoscroll(Autoscroll::fit(), cx);
11973        }
11974
11975        cx.notify();
11976
11977        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11978            // Clear diagnostics block when folding a range that contains it.
11979            let snapshot = self.snapshot(window, cx);
11980            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11981                drop(snapshot);
11982                self.active_diagnostics = Some(active_diagnostics);
11983                self.dismiss_diagnostics(cx);
11984            } else {
11985                self.active_diagnostics = Some(active_diagnostics);
11986            }
11987        }
11988
11989        self.scrollbar_marker_state.dirty = true;
11990    }
11991
11992    /// Removes any folds whose ranges intersect any of the given ranges.
11993    pub fn unfold_ranges<T: ToOffset + Clone>(
11994        &mut self,
11995        ranges: &[Range<T>],
11996        inclusive: bool,
11997        auto_scroll: bool,
11998        cx: &mut Context<Self>,
11999    ) {
12000        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12001            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12002        });
12003    }
12004
12005    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12006        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12007            return;
12008        }
12009        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12010        self.display_map
12011            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12012        cx.emit(EditorEvent::BufferFoldToggled {
12013            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12014            folded: true,
12015        });
12016        cx.notify();
12017    }
12018
12019    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12020        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12021            return;
12022        }
12023        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12024        self.display_map.update(cx, |display_map, cx| {
12025            display_map.unfold_buffer(buffer_id, cx);
12026        });
12027        cx.emit(EditorEvent::BufferFoldToggled {
12028            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12029            folded: false,
12030        });
12031        cx.notify();
12032    }
12033
12034    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12035        self.display_map.read(cx).is_buffer_folded(buffer)
12036    }
12037
12038    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12039        self.display_map.read(cx).folded_buffers()
12040    }
12041
12042    /// Removes any folds with the given ranges.
12043    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12044        &mut self,
12045        ranges: &[Range<T>],
12046        type_id: TypeId,
12047        auto_scroll: bool,
12048        cx: &mut Context<Self>,
12049    ) {
12050        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12051            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12052        });
12053    }
12054
12055    fn remove_folds_with<T: ToOffset + Clone>(
12056        &mut self,
12057        ranges: &[Range<T>],
12058        auto_scroll: bool,
12059        cx: &mut Context<Self>,
12060        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12061    ) {
12062        if ranges.is_empty() {
12063            return;
12064        }
12065
12066        let mut buffers_affected = HashSet::default();
12067        let multi_buffer = self.buffer().read(cx);
12068        for range in ranges {
12069            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12070                buffers_affected.insert(buffer.read(cx).remote_id());
12071            };
12072        }
12073
12074        self.display_map.update(cx, update);
12075
12076        if auto_scroll {
12077            self.request_autoscroll(Autoscroll::fit(), cx);
12078        }
12079
12080        cx.notify();
12081        self.scrollbar_marker_state.dirty = true;
12082        self.active_indent_guides_state.dirty = true;
12083    }
12084
12085    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12086        self.display_map.read(cx).fold_placeholder.clone()
12087    }
12088
12089    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12090        self.buffer.update(cx, |buffer, cx| {
12091            buffer.set_all_diff_hunks_expanded(cx);
12092        });
12093    }
12094
12095    pub fn expand_all_diff_hunks(
12096        &mut self,
12097        _: &ExpandAllHunkDiffs,
12098        _window: &mut Window,
12099        cx: &mut Context<Self>,
12100    ) {
12101        self.buffer.update(cx, |buffer, cx| {
12102            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12103        });
12104    }
12105
12106    pub fn toggle_selected_diff_hunks(
12107        &mut self,
12108        _: &ToggleSelectedDiffHunks,
12109        _window: &mut Window,
12110        cx: &mut Context<Self>,
12111    ) {
12112        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12113        self.toggle_diff_hunks_in_ranges(ranges, cx);
12114    }
12115
12116    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12117        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12118        self.buffer
12119            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12120    }
12121
12122    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12123        self.buffer.update(cx, |buffer, cx| {
12124            let ranges = vec![Anchor::min()..Anchor::max()];
12125            if !buffer.all_diff_hunks_expanded()
12126                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12127            {
12128                buffer.collapse_diff_hunks(ranges, cx);
12129                true
12130            } else {
12131                false
12132            }
12133        })
12134    }
12135
12136    fn toggle_diff_hunks_in_ranges(
12137        &mut self,
12138        ranges: Vec<Range<Anchor>>,
12139        cx: &mut Context<'_, Editor>,
12140    ) {
12141        self.buffer.update(cx, |buffer, cx| {
12142            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12143                buffer.collapse_diff_hunks(ranges, cx)
12144            } else {
12145                buffer.expand_diff_hunks(ranges, cx)
12146            }
12147        })
12148    }
12149
12150    pub(crate) fn apply_all_diff_hunks(
12151        &mut self,
12152        _: &ApplyAllDiffHunks,
12153        window: &mut Window,
12154        cx: &mut Context<Self>,
12155    ) {
12156        let buffers = self.buffer.read(cx).all_buffers();
12157        for branch_buffer in buffers {
12158            branch_buffer.update(cx, |branch_buffer, cx| {
12159                branch_buffer.merge_into_base(Vec::new(), cx);
12160            });
12161        }
12162
12163        if let Some(project) = self.project.clone() {
12164            self.save(true, project, window, cx).detach_and_log_err(cx);
12165        }
12166    }
12167
12168    pub(crate) fn apply_selected_diff_hunks(
12169        &mut self,
12170        _: &ApplyDiffHunk,
12171        window: &mut Window,
12172        cx: &mut Context<Self>,
12173    ) {
12174        let snapshot = self.snapshot(window, cx);
12175        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12176        let mut ranges_by_buffer = HashMap::default();
12177        self.transact(window, cx, |editor, _window, cx| {
12178            for hunk in hunks {
12179                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12180                    ranges_by_buffer
12181                        .entry(buffer.clone())
12182                        .or_insert_with(Vec::new)
12183                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12184                }
12185            }
12186
12187            for (buffer, ranges) in ranges_by_buffer {
12188                buffer.update(cx, |buffer, cx| {
12189                    buffer.merge_into_base(ranges, cx);
12190                });
12191            }
12192        });
12193
12194        if let Some(project) = self.project.clone() {
12195            self.save(true, project, window, cx).detach_and_log_err(cx);
12196        }
12197    }
12198
12199    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12200        if hovered != self.gutter_hovered {
12201            self.gutter_hovered = hovered;
12202            cx.notify();
12203        }
12204    }
12205
12206    pub fn insert_blocks(
12207        &mut self,
12208        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12209        autoscroll: Option<Autoscroll>,
12210        cx: &mut Context<Self>,
12211    ) -> Vec<CustomBlockId> {
12212        let blocks = self
12213            .display_map
12214            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12215        if let Some(autoscroll) = autoscroll {
12216            self.request_autoscroll(autoscroll, cx);
12217        }
12218        cx.notify();
12219        blocks
12220    }
12221
12222    pub fn resize_blocks(
12223        &mut self,
12224        heights: HashMap<CustomBlockId, u32>,
12225        autoscroll: Option<Autoscroll>,
12226        cx: &mut Context<Self>,
12227    ) {
12228        self.display_map
12229            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12230        if let Some(autoscroll) = autoscroll {
12231            self.request_autoscroll(autoscroll, cx);
12232        }
12233        cx.notify();
12234    }
12235
12236    pub fn replace_blocks(
12237        &mut self,
12238        renderers: HashMap<CustomBlockId, RenderBlock>,
12239        autoscroll: Option<Autoscroll>,
12240        cx: &mut Context<Self>,
12241    ) {
12242        self.display_map
12243            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12244        if let Some(autoscroll) = autoscroll {
12245            self.request_autoscroll(autoscroll, cx);
12246        }
12247        cx.notify();
12248    }
12249
12250    pub fn remove_blocks(
12251        &mut self,
12252        block_ids: HashSet<CustomBlockId>,
12253        autoscroll: Option<Autoscroll>,
12254        cx: &mut Context<Self>,
12255    ) {
12256        self.display_map.update(cx, |display_map, cx| {
12257            display_map.remove_blocks(block_ids, cx)
12258        });
12259        if let Some(autoscroll) = autoscroll {
12260            self.request_autoscroll(autoscroll, cx);
12261        }
12262        cx.notify();
12263    }
12264
12265    pub fn row_for_block(
12266        &self,
12267        block_id: CustomBlockId,
12268        cx: &mut Context<Self>,
12269    ) -> Option<DisplayRow> {
12270        self.display_map
12271            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12272    }
12273
12274    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12275        self.focused_block = Some(focused_block);
12276    }
12277
12278    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12279        self.focused_block.take()
12280    }
12281
12282    pub fn insert_creases(
12283        &mut self,
12284        creases: impl IntoIterator<Item = Crease<Anchor>>,
12285        cx: &mut Context<Self>,
12286    ) -> Vec<CreaseId> {
12287        self.display_map
12288            .update(cx, |map, cx| map.insert_creases(creases, cx))
12289    }
12290
12291    pub fn remove_creases(
12292        &mut self,
12293        ids: impl IntoIterator<Item = CreaseId>,
12294        cx: &mut Context<Self>,
12295    ) {
12296        self.display_map
12297            .update(cx, |map, cx| map.remove_creases(ids, cx));
12298    }
12299
12300    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12301        self.display_map
12302            .update(cx, |map, cx| map.snapshot(cx))
12303            .longest_row()
12304    }
12305
12306    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12307        self.display_map
12308            .update(cx, |map, cx| map.snapshot(cx))
12309            .max_point()
12310    }
12311
12312    pub fn text(&self, cx: &App) -> String {
12313        self.buffer.read(cx).read(cx).text()
12314    }
12315
12316    pub fn is_empty(&self, cx: &App) -> bool {
12317        self.buffer.read(cx).read(cx).is_empty()
12318    }
12319
12320    pub fn text_option(&self, cx: &App) -> Option<String> {
12321        let text = self.text(cx);
12322        let text = text.trim();
12323
12324        if text.is_empty() {
12325            return None;
12326        }
12327
12328        Some(text.to_string())
12329    }
12330
12331    pub fn set_text(
12332        &mut self,
12333        text: impl Into<Arc<str>>,
12334        window: &mut Window,
12335        cx: &mut Context<Self>,
12336    ) {
12337        self.transact(window, cx, |this, _, cx| {
12338            this.buffer
12339                .read(cx)
12340                .as_singleton()
12341                .expect("you can only call set_text on editors for singleton buffers")
12342                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12343        });
12344    }
12345
12346    pub fn display_text(&self, cx: &mut App) -> String {
12347        self.display_map
12348            .update(cx, |map, cx| map.snapshot(cx))
12349            .text()
12350    }
12351
12352    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12353        let mut wrap_guides = smallvec::smallvec![];
12354
12355        if self.show_wrap_guides == Some(false) {
12356            return wrap_guides;
12357        }
12358
12359        let settings = self.buffer.read(cx).settings_at(0, cx);
12360        if settings.show_wrap_guides {
12361            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12362                wrap_guides.push((soft_wrap as usize, true));
12363            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12364                wrap_guides.push((soft_wrap as usize, true));
12365            }
12366            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12367        }
12368
12369        wrap_guides
12370    }
12371
12372    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12373        let settings = self.buffer.read(cx).settings_at(0, cx);
12374        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12375        match mode {
12376            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12377                SoftWrap::None
12378            }
12379            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12380            language_settings::SoftWrap::PreferredLineLength => {
12381                SoftWrap::Column(settings.preferred_line_length)
12382            }
12383            language_settings::SoftWrap::Bounded => {
12384                SoftWrap::Bounded(settings.preferred_line_length)
12385            }
12386        }
12387    }
12388
12389    pub fn set_soft_wrap_mode(
12390        &mut self,
12391        mode: language_settings::SoftWrap,
12392
12393        cx: &mut Context<Self>,
12394    ) {
12395        self.soft_wrap_mode_override = Some(mode);
12396        cx.notify();
12397    }
12398
12399    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12400        self.text_style_refinement = Some(style);
12401    }
12402
12403    /// called by the Element so we know what style we were most recently rendered with.
12404    pub(crate) fn set_style(
12405        &mut self,
12406        style: EditorStyle,
12407        window: &mut Window,
12408        cx: &mut Context<Self>,
12409    ) {
12410        let rem_size = window.rem_size();
12411        self.display_map.update(cx, |map, cx| {
12412            map.set_font(
12413                style.text.font(),
12414                style.text.font_size.to_pixels(rem_size),
12415                cx,
12416            )
12417        });
12418        self.style = Some(style);
12419    }
12420
12421    pub fn style(&self) -> Option<&EditorStyle> {
12422        self.style.as_ref()
12423    }
12424
12425    // Called by the element. This method is not designed to be called outside of the editor
12426    // element's layout code because it does not notify when rewrapping is computed synchronously.
12427    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12428        self.display_map
12429            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12430    }
12431
12432    pub fn set_soft_wrap(&mut self) {
12433        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12434    }
12435
12436    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12437        if self.soft_wrap_mode_override.is_some() {
12438            self.soft_wrap_mode_override.take();
12439        } else {
12440            let soft_wrap = match self.soft_wrap_mode(cx) {
12441                SoftWrap::GitDiff => return,
12442                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12443                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12444                    language_settings::SoftWrap::None
12445                }
12446            };
12447            self.soft_wrap_mode_override = Some(soft_wrap);
12448        }
12449        cx.notify();
12450    }
12451
12452    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12453        let Some(workspace) = self.workspace() else {
12454            return;
12455        };
12456        let fs = workspace.read(cx).app_state().fs.clone();
12457        let current_show = TabBarSettings::get_global(cx).show;
12458        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12459            setting.show = Some(!current_show);
12460        });
12461    }
12462
12463    pub fn toggle_indent_guides(
12464        &mut self,
12465        _: &ToggleIndentGuides,
12466        _: &mut Window,
12467        cx: &mut Context<Self>,
12468    ) {
12469        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12470            self.buffer
12471                .read(cx)
12472                .settings_at(0, cx)
12473                .indent_guides
12474                .enabled
12475        });
12476        self.show_indent_guides = Some(!currently_enabled);
12477        cx.notify();
12478    }
12479
12480    fn should_show_indent_guides(&self) -> Option<bool> {
12481        self.show_indent_guides
12482    }
12483
12484    pub fn toggle_line_numbers(
12485        &mut self,
12486        _: &ToggleLineNumbers,
12487        _: &mut Window,
12488        cx: &mut Context<Self>,
12489    ) {
12490        let mut editor_settings = EditorSettings::get_global(cx).clone();
12491        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12492        EditorSettings::override_global(editor_settings, cx);
12493    }
12494
12495    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12496        self.use_relative_line_numbers
12497            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12498    }
12499
12500    pub fn toggle_relative_line_numbers(
12501        &mut self,
12502        _: &ToggleRelativeLineNumbers,
12503        _: &mut Window,
12504        cx: &mut Context<Self>,
12505    ) {
12506        let is_relative = self.should_use_relative_line_numbers(cx);
12507        self.set_relative_line_number(Some(!is_relative), cx)
12508    }
12509
12510    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12511        self.use_relative_line_numbers = is_relative;
12512        cx.notify();
12513    }
12514
12515    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12516        self.show_gutter = show_gutter;
12517        cx.notify();
12518    }
12519
12520    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12521        self.show_scrollbars = show_scrollbars;
12522        cx.notify();
12523    }
12524
12525    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12526        self.show_line_numbers = Some(show_line_numbers);
12527        cx.notify();
12528    }
12529
12530    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12531        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12532        cx.notify();
12533    }
12534
12535    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12536        self.show_code_actions = Some(show_code_actions);
12537        cx.notify();
12538    }
12539
12540    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12541        self.show_runnables = Some(show_runnables);
12542        cx.notify();
12543    }
12544
12545    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12546        if self.display_map.read(cx).masked != masked {
12547            self.display_map.update(cx, |map, _| map.masked = masked);
12548        }
12549        cx.notify()
12550    }
12551
12552    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12553        self.show_wrap_guides = Some(show_wrap_guides);
12554        cx.notify();
12555    }
12556
12557    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12558        self.show_indent_guides = Some(show_indent_guides);
12559        cx.notify();
12560    }
12561
12562    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12563        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12564            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12565                if let Some(dir) = file.abs_path(cx).parent() {
12566                    return Some(dir.to_owned());
12567                }
12568            }
12569
12570            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12571                return Some(project_path.path.to_path_buf());
12572            }
12573        }
12574
12575        None
12576    }
12577
12578    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12579        self.active_excerpt(cx)?
12580            .1
12581            .read(cx)
12582            .file()
12583            .and_then(|f| f.as_local())
12584    }
12585
12586    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12587        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12588            let project_path = buffer.read(cx).project_path(cx)?;
12589            let project = self.project.as_ref()?.read(cx);
12590            project.absolute_path(&project_path, cx)
12591        })
12592    }
12593
12594    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12595        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12596            let project_path = buffer.read(cx).project_path(cx)?;
12597            let project = self.project.as_ref()?.read(cx);
12598            let entry = project.entry_for_path(&project_path, cx)?;
12599            let path = entry.path.to_path_buf();
12600            Some(path)
12601        })
12602    }
12603
12604    pub fn reveal_in_finder(
12605        &mut self,
12606        _: &RevealInFileManager,
12607        _window: &mut Window,
12608        cx: &mut Context<Self>,
12609    ) {
12610        if let Some(target) = self.target_file(cx) {
12611            cx.reveal_path(&target.abs_path(cx));
12612        }
12613    }
12614
12615    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12616        if let Some(path) = self.target_file_abs_path(cx) {
12617            if let Some(path) = path.to_str() {
12618                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12619            }
12620        }
12621    }
12622
12623    pub fn copy_relative_path(
12624        &mut self,
12625        _: &CopyRelativePath,
12626        _window: &mut Window,
12627        cx: &mut Context<Self>,
12628    ) {
12629        if let Some(path) = self.target_file_path(cx) {
12630            if let Some(path) = path.to_str() {
12631                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12632            }
12633        }
12634    }
12635
12636    pub fn toggle_git_blame(
12637        &mut self,
12638        _: &ToggleGitBlame,
12639        window: &mut Window,
12640        cx: &mut Context<Self>,
12641    ) {
12642        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12643
12644        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12645            self.start_git_blame(true, window, cx);
12646        }
12647
12648        cx.notify();
12649    }
12650
12651    pub fn toggle_git_blame_inline(
12652        &mut self,
12653        _: &ToggleGitBlameInline,
12654        window: &mut Window,
12655        cx: &mut Context<Self>,
12656    ) {
12657        self.toggle_git_blame_inline_internal(true, window, cx);
12658        cx.notify();
12659    }
12660
12661    pub fn git_blame_inline_enabled(&self) -> bool {
12662        self.git_blame_inline_enabled
12663    }
12664
12665    pub fn toggle_selection_menu(
12666        &mut self,
12667        _: &ToggleSelectionMenu,
12668        _: &mut Window,
12669        cx: &mut Context<Self>,
12670    ) {
12671        self.show_selection_menu = self
12672            .show_selection_menu
12673            .map(|show_selections_menu| !show_selections_menu)
12674            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12675
12676        cx.notify();
12677    }
12678
12679    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12680        self.show_selection_menu
12681            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12682    }
12683
12684    fn start_git_blame(
12685        &mut self,
12686        user_triggered: bool,
12687        window: &mut Window,
12688        cx: &mut Context<Self>,
12689    ) {
12690        if let Some(project) = self.project.as_ref() {
12691            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12692                return;
12693            };
12694
12695            if buffer.read(cx).file().is_none() {
12696                return;
12697            }
12698
12699            let focused = self.focus_handle(cx).contains_focused(window, cx);
12700
12701            let project = project.clone();
12702            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12703            self.blame_subscription =
12704                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12705            self.blame = Some(blame);
12706        }
12707    }
12708
12709    fn toggle_git_blame_inline_internal(
12710        &mut self,
12711        user_triggered: bool,
12712        window: &mut Window,
12713        cx: &mut Context<Self>,
12714    ) {
12715        if self.git_blame_inline_enabled {
12716            self.git_blame_inline_enabled = false;
12717            self.show_git_blame_inline = false;
12718            self.show_git_blame_inline_delay_task.take();
12719        } else {
12720            self.git_blame_inline_enabled = true;
12721            self.start_git_blame_inline(user_triggered, window, cx);
12722        }
12723
12724        cx.notify();
12725    }
12726
12727    fn start_git_blame_inline(
12728        &mut self,
12729        user_triggered: bool,
12730        window: &mut Window,
12731        cx: &mut Context<Self>,
12732    ) {
12733        self.start_git_blame(user_triggered, window, cx);
12734
12735        if ProjectSettings::get_global(cx)
12736            .git
12737            .inline_blame_delay()
12738            .is_some()
12739        {
12740            self.start_inline_blame_timer(window, cx);
12741        } else {
12742            self.show_git_blame_inline = true
12743        }
12744    }
12745
12746    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12747        self.blame.as_ref()
12748    }
12749
12750    pub fn show_git_blame_gutter(&self) -> bool {
12751        self.show_git_blame_gutter
12752    }
12753
12754    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12755        self.show_git_blame_gutter && self.has_blame_entries(cx)
12756    }
12757
12758    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12759        self.show_git_blame_inline
12760            && self.focus_handle.is_focused(window)
12761            && !self.newest_selection_head_on_empty_line(cx)
12762            && self.has_blame_entries(cx)
12763    }
12764
12765    fn has_blame_entries(&self, cx: &App) -> bool {
12766        self.blame()
12767            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12768    }
12769
12770    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12771        let cursor_anchor = self.selections.newest_anchor().head();
12772
12773        let snapshot = self.buffer.read(cx).snapshot(cx);
12774        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12775
12776        snapshot.line_len(buffer_row) == 0
12777    }
12778
12779    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12780        let buffer_and_selection = maybe!({
12781            let selection = self.selections.newest::<Point>(cx);
12782            let selection_range = selection.range();
12783
12784            let multi_buffer = self.buffer().read(cx);
12785            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12786            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12787
12788            let (buffer, range, _) = if selection.reversed {
12789                buffer_ranges.first()
12790            } else {
12791                buffer_ranges.last()
12792            }?;
12793
12794            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12795                ..text::ToPoint::to_point(&range.end, &buffer).row;
12796            Some((
12797                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12798                selection,
12799            ))
12800        });
12801
12802        let Some((buffer, selection)) = buffer_and_selection else {
12803            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12804        };
12805
12806        let Some(project) = self.project.as_ref() else {
12807            return Task::ready(Err(anyhow!("editor does not have project")));
12808        };
12809
12810        project.update(cx, |project, cx| {
12811            project.get_permalink_to_line(&buffer, selection, cx)
12812        })
12813    }
12814
12815    pub fn copy_permalink_to_line(
12816        &mut self,
12817        _: &CopyPermalinkToLine,
12818        window: &mut Window,
12819        cx: &mut Context<Self>,
12820    ) {
12821        let permalink_task = self.get_permalink_to_line(cx);
12822        let workspace = self.workspace();
12823
12824        cx.spawn_in(window, |_, mut cx| async move {
12825            match permalink_task.await {
12826                Ok(permalink) => {
12827                    cx.update(|_, cx| {
12828                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12829                    })
12830                    .ok();
12831                }
12832                Err(err) => {
12833                    let message = format!("Failed to copy permalink: {err}");
12834
12835                    Err::<(), anyhow::Error>(err).log_err();
12836
12837                    if let Some(workspace) = workspace {
12838                        workspace
12839                            .update_in(&mut cx, |workspace, _, cx| {
12840                                struct CopyPermalinkToLine;
12841
12842                                workspace.show_toast(
12843                                    Toast::new(
12844                                        NotificationId::unique::<CopyPermalinkToLine>(),
12845                                        message,
12846                                    ),
12847                                    cx,
12848                                )
12849                            })
12850                            .ok();
12851                    }
12852                }
12853            }
12854        })
12855        .detach();
12856    }
12857
12858    pub fn copy_file_location(
12859        &mut self,
12860        _: &CopyFileLocation,
12861        _: &mut Window,
12862        cx: &mut Context<Self>,
12863    ) {
12864        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12865        if let Some(file) = self.target_file(cx) {
12866            if let Some(path) = file.path().to_str() {
12867                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12868            }
12869        }
12870    }
12871
12872    pub fn open_permalink_to_line(
12873        &mut self,
12874        _: &OpenPermalinkToLine,
12875        window: &mut Window,
12876        cx: &mut Context<Self>,
12877    ) {
12878        let permalink_task = self.get_permalink_to_line(cx);
12879        let workspace = self.workspace();
12880
12881        cx.spawn_in(window, |_, mut cx| async move {
12882            match permalink_task.await {
12883                Ok(permalink) => {
12884                    cx.update(|_, cx| {
12885                        cx.open_url(permalink.as_ref());
12886                    })
12887                    .ok();
12888                }
12889                Err(err) => {
12890                    let message = format!("Failed to open permalink: {err}");
12891
12892                    Err::<(), anyhow::Error>(err).log_err();
12893
12894                    if let Some(workspace) = workspace {
12895                        workspace
12896                            .update(&mut cx, |workspace, cx| {
12897                                struct OpenPermalinkToLine;
12898
12899                                workspace.show_toast(
12900                                    Toast::new(
12901                                        NotificationId::unique::<OpenPermalinkToLine>(),
12902                                        message,
12903                                    ),
12904                                    cx,
12905                                )
12906                            })
12907                            .ok();
12908                    }
12909                }
12910            }
12911        })
12912        .detach();
12913    }
12914
12915    pub fn insert_uuid_v4(
12916        &mut self,
12917        _: &InsertUuidV4,
12918        window: &mut Window,
12919        cx: &mut Context<Self>,
12920    ) {
12921        self.insert_uuid(UuidVersion::V4, window, cx);
12922    }
12923
12924    pub fn insert_uuid_v7(
12925        &mut self,
12926        _: &InsertUuidV7,
12927        window: &mut Window,
12928        cx: &mut Context<Self>,
12929    ) {
12930        self.insert_uuid(UuidVersion::V7, window, cx);
12931    }
12932
12933    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12934        self.transact(window, cx, |this, window, cx| {
12935            let edits = this
12936                .selections
12937                .all::<Point>(cx)
12938                .into_iter()
12939                .map(|selection| {
12940                    let uuid = match version {
12941                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12942                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12943                    };
12944
12945                    (selection.range(), uuid.to_string())
12946                });
12947            this.edit(edits, cx);
12948            this.refresh_inline_completion(true, false, window, cx);
12949        });
12950    }
12951
12952    pub fn open_selections_in_multibuffer(
12953        &mut self,
12954        _: &OpenSelectionsInMultibuffer,
12955        window: &mut Window,
12956        cx: &mut Context<Self>,
12957    ) {
12958        let multibuffer = self.buffer.read(cx);
12959
12960        let Some(buffer) = multibuffer.as_singleton() else {
12961            return;
12962        };
12963
12964        let Some(workspace) = self.workspace() else {
12965            return;
12966        };
12967
12968        let locations = self
12969            .selections
12970            .disjoint_anchors()
12971            .iter()
12972            .map(|range| Location {
12973                buffer: buffer.clone(),
12974                range: range.start.text_anchor..range.end.text_anchor,
12975            })
12976            .collect::<Vec<_>>();
12977
12978        let title = multibuffer.title(cx).to_string();
12979
12980        cx.spawn_in(window, |_, mut cx| async move {
12981            workspace.update_in(&mut cx, |workspace, window, cx| {
12982                Self::open_locations_in_multibuffer(
12983                    workspace,
12984                    locations,
12985                    format!("Selections for '{title}'"),
12986                    false,
12987                    MultibufferSelectionMode::All,
12988                    window,
12989                    cx,
12990                );
12991            })
12992        })
12993        .detach();
12994    }
12995
12996    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12997    /// last highlight added will be used.
12998    ///
12999    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13000    pub fn highlight_rows<T: 'static>(
13001        &mut self,
13002        range: Range<Anchor>,
13003        color: Hsla,
13004        should_autoscroll: bool,
13005        cx: &mut Context<Self>,
13006    ) {
13007        let snapshot = self.buffer().read(cx).snapshot(cx);
13008        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13009        let ix = row_highlights.binary_search_by(|highlight| {
13010            Ordering::Equal
13011                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13012                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13013        });
13014
13015        if let Err(mut ix) = ix {
13016            let index = post_inc(&mut self.highlight_order);
13017
13018            // If this range intersects with the preceding highlight, then merge it with
13019            // the preceding highlight. Otherwise insert a new highlight.
13020            let mut merged = false;
13021            if ix > 0 {
13022                let prev_highlight = &mut row_highlights[ix - 1];
13023                if prev_highlight
13024                    .range
13025                    .end
13026                    .cmp(&range.start, &snapshot)
13027                    .is_ge()
13028                {
13029                    ix -= 1;
13030                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13031                        prev_highlight.range.end = range.end;
13032                    }
13033                    merged = true;
13034                    prev_highlight.index = index;
13035                    prev_highlight.color = color;
13036                    prev_highlight.should_autoscroll = should_autoscroll;
13037                }
13038            }
13039
13040            if !merged {
13041                row_highlights.insert(
13042                    ix,
13043                    RowHighlight {
13044                        range: range.clone(),
13045                        index,
13046                        color,
13047                        should_autoscroll,
13048                    },
13049                );
13050            }
13051
13052            // If any of the following highlights intersect with this one, merge them.
13053            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13054                let highlight = &row_highlights[ix];
13055                if next_highlight
13056                    .range
13057                    .start
13058                    .cmp(&highlight.range.end, &snapshot)
13059                    .is_le()
13060                {
13061                    if next_highlight
13062                        .range
13063                        .end
13064                        .cmp(&highlight.range.end, &snapshot)
13065                        .is_gt()
13066                    {
13067                        row_highlights[ix].range.end = next_highlight.range.end;
13068                    }
13069                    row_highlights.remove(ix + 1);
13070                } else {
13071                    break;
13072                }
13073            }
13074        }
13075    }
13076
13077    /// Remove any highlighted row ranges of the given type that intersect the
13078    /// given ranges.
13079    pub fn remove_highlighted_rows<T: 'static>(
13080        &mut self,
13081        ranges_to_remove: Vec<Range<Anchor>>,
13082        cx: &mut Context<Self>,
13083    ) {
13084        let snapshot = self.buffer().read(cx).snapshot(cx);
13085        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13086        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13087        row_highlights.retain(|highlight| {
13088            while let Some(range_to_remove) = ranges_to_remove.peek() {
13089                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13090                    Ordering::Less | Ordering::Equal => {
13091                        ranges_to_remove.next();
13092                    }
13093                    Ordering::Greater => {
13094                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13095                            Ordering::Less | Ordering::Equal => {
13096                                return false;
13097                            }
13098                            Ordering::Greater => break,
13099                        }
13100                    }
13101                }
13102            }
13103
13104            true
13105        })
13106    }
13107
13108    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13109    pub fn clear_row_highlights<T: 'static>(&mut self) {
13110        self.highlighted_rows.remove(&TypeId::of::<T>());
13111    }
13112
13113    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13114    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13115        self.highlighted_rows
13116            .get(&TypeId::of::<T>())
13117            .map_or(&[] as &[_], |vec| vec.as_slice())
13118            .iter()
13119            .map(|highlight| (highlight.range.clone(), highlight.color))
13120    }
13121
13122    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13123    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13124    /// Allows to ignore certain kinds of highlights.
13125    pub fn highlighted_display_rows(
13126        &self,
13127        window: &mut Window,
13128        cx: &mut App,
13129    ) -> BTreeMap<DisplayRow, Hsla> {
13130        let snapshot = self.snapshot(window, cx);
13131        let mut used_highlight_orders = HashMap::default();
13132        self.highlighted_rows
13133            .iter()
13134            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13135            .fold(
13136                BTreeMap::<DisplayRow, Hsla>::new(),
13137                |mut unique_rows, highlight| {
13138                    let start = highlight.range.start.to_display_point(&snapshot);
13139                    let end = highlight.range.end.to_display_point(&snapshot);
13140                    let start_row = start.row().0;
13141                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13142                        && end.column() == 0
13143                    {
13144                        end.row().0.saturating_sub(1)
13145                    } else {
13146                        end.row().0
13147                    };
13148                    for row in start_row..=end_row {
13149                        let used_index =
13150                            used_highlight_orders.entry(row).or_insert(highlight.index);
13151                        if highlight.index >= *used_index {
13152                            *used_index = highlight.index;
13153                            unique_rows.insert(DisplayRow(row), highlight.color);
13154                        }
13155                    }
13156                    unique_rows
13157                },
13158            )
13159    }
13160
13161    pub fn highlighted_display_row_for_autoscroll(
13162        &self,
13163        snapshot: &DisplaySnapshot,
13164    ) -> Option<DisplayRow> {
13165        self.highlighted_rows
13166            .values()
13167            .flat_map(|highlighted_rows| highlighted_rows.iter())
13168            .filter_map(|highlight| {
13169                if highlight.should_autoscroll {
13170                    Some(highlight.range.start.to_display_point(snapshot).row())
13171                } else {
13172                    None
13173                }
13174            })
13175            .min()
13176    }
13177
13178    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13179        self.highlight_background::<SearchWithinRange>(
13180            ranges,
13181            |colors| colors.editor_document_highlight_read_background,
13182            cx,
13183        )
13184    }
13185
13186    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13187        self.breadcrumb_header = Some(new_header);
13188    }
13189
13190    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13191        self.clear_background_highlights::<SearchWithinRange>(cx);
13192    }
13193
13194    pub fn highlight_background<T: 'static>(
13195        &mut self,
13196        ranges: &[Range<Anchor>],
13197        color_fetcher: fn(&ThemeColors) -> Hsla,
13198        cx: &mut Context<Self>,
13199    ) {
13200        self.background_highlights
13201            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13202        self.scrollbar_marker_state.dirty = true;
13203        cx.notify();
13204    }
13205
13206    pub fn clear_background_highlights<T: 'static>(
13207        &mut self,
13208        cx: &mut Context<Self>,
13209    ) -> Option<BackgroundHighlight> {
13210        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13211        if !text_highlights.1.is_empty() {
13212            self.scrollbar_marker_state.dirty = true;
13213            cx.notify();
13214        }
13215        Some(text_highlights)
13216    }
13217
13218    pub fn highlight_gutter<T: 'static>(
13219        &mut self,
13220        ranges: &[Range<Anchor>],
13221        color_fetcher: fn(&App) -> Hsla,
13222        cx: &mut Context<Self>,
13223    ) {
13224        self.gutter_highlights
13225            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13226        cx.notify();
13227    }
13228
13229    pub fn clear_gutter_highlights<T: 'static>(
13230        &mut self,
13231        cx: &mut Context<Self>,
13232    ) -> Option<GutterHighlight> {
13233        cx.notify();
13234        self.gutter_highlights.remove(&TypeId::of::<T>())
13235    }
13236
13237    #[cfg(feature = "test-support")]
13238    pub fn all_text_background_highlights(
13239        &self,
13240        window: &mut Window,
13241        cx: &mut Context<Self>,
13242    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13243        let snapshot = self.snapshot(window, cx);
13244        let buffer = &snapshot.buffer_snapshot;
13245        let start = buffer.anchor_before(0);
13246        let end = buffer.anchor_after(buffer.len());
13247        let theme = cx.theme().colors();
13248        self.background_highlights_in_range(start..end, &snapshot, theme)
13249    }
13250
13251    #[cfg(feature = "test-support")]
13252    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13253        let snapshot = self.buffer().read(cx).snapshot(cx);
13254
13255        let highlights = self
13256            .background_highlights
13257            .get(&TypeId::of::<items::BufferSearchHighlights>());
13258
13259        if let Some((_color, ranges)) = highlights {
13260            ranges
13261                .iter()
13262                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13263                .collect_vec()
13264        } else {
13265            vec![]
13266        }
13267    }
13268
13269    fn document_highlights_for_position<'a>(
13270        &'a self,
13271        position: Anchor,
13272        buffer: &'a MultiBufferSnapshot,
13273    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13274        let read_highlights = self
13275            .background_highlights
13276            .get(&TypeId::of::<DocumentHighlightRead>())
13277            .map(|h| &h.1);
13278        let write_highlights = self
13279            .background_highlights
13280            .get(&TypeId::of::<DocumentHighlightWrite>())
13281            .map(|h| &h.1);
13282        let left_position = position.bias_left(buffer);
13283        let right_position = position.bias_right(buffer);
13284        read_highlights
13285            .into_iter()
13286            .chain(write_highlights)
13287            .flat_map(move |ranges| {
13288                let start_ix = match ranges.binary_search_by(|probe| {
13289                    let cmp = probe.end.cmp(&left_position, buffer);
13290                    if cmp.is_ge() {
13291                        Ordering::Greater
13292                    } else {
13293                        Ordering::Less
13294                    }
13295                }) {
13296                    Ok(i) | Err(i) => i,
13297                };
13298
13299                ranges[start_ix..]
13300                    .iter()
13301                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13302            })
13303    }
13304
13305    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13306        self.background_highlights
13307            .get(&TypeId::of::<T>())
13308            .map_or(false, |(_, highlights)| !highlights.is_empty())
13309    }
13310
13311    pub fn background_highlights_in_range(
13312        &self,
13313        search_range: Range<Anchor>,
13314        display_snapshot: &DisplaySnapshot,
13315        theme: &ThemeColors,
13316    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13317        let mut results = Vec::new();
13318        for (color_fetcher, ranges) in self.background_highlights.values() {
13319            let color = color_fetcher(theme);
13320            let start_ix = match ranges.binary_search_by(|probe| {
13321                let cmp = probe
13322                    .end
13323                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13324                if cmp.is_gt() {
13325                    Ordering::Greater
13326                } else {
13327                    Ordering::Less
13328                }
13329            }) {
13330                Ok(i) | Err(i) => i,
13331            };
13332            for range in &ranges[start_ix..] {
13333                if range
13334                    .start
13335                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13336                    .is_ge()
13337                {
13338                    break;
13339                }
13340
13341                let start = range.start.to_display_point(display_snapshot);
13342                let end = range.end.to_display_point(display_snapshot);
13343                results.push((start..end, color))
13344            }
13345        }
13346        results
13347    }
13348
13349    pub fn background_highlight_row_ranges<T: 'static>(
13350        &self,
13351        search_range: Range<Anchor>,
13352        display_snapshot: &DisplaySnapshot,
13353        count: usize,
13354    ) -> Vec<RangeInclusive<DisplayPoint>> {
13355        let mut results = Vec::new();
13356        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13357            return vec![];
13358        };
13359
13360        let start_ix = match ranges.binary_search_by(|probe| {
13361            let cmp = probe
13362                .end
13363                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13364            if cmp.is_gt() {
13365                Ordering::Greater
13366            } else {
13367                Ordering::Less
13368            }
13369        }) {
13370            Ok(i) | Err(i) => i,
13371        };
13372        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13373            if let (Some(start_display), Some(end_display)) = (start, end) {
13374                results.push(
13375                    start_display.to_display_point(display_snapshot)
13376                        ..=end_display.to_display_point(display_snapshot),
13377                );
13378            }
13379        };
13380        let mut start_row: Option<Point> = None;
13381        let mut end_row: Option<Point> = None;
13382        if ranges.len() > count {
13383            return Vec::new();
13384        }
13385        for range in &ranges[start_ix..] {
13386            if range
13387                .start
13388                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13389                .is_ge()
13390            {
13391                break;
13392            }
13393            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13394            if let Some(current_row) = &end_row {
13395                if end.row == current_row.row {
13396                    continue;
13397                }
13398            }
13399            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13400            if start_row.is_none() {
13401                assert_eq!(end_row, None);
13402                start_row = Some(start);
13403                end_row = Some(end);
13404                continue;
13405            }
13406            if let Some(current_end) = end_row.as_mut() {
13407                if start.row > current_end.row + 1 {
13408                    push_region(start_row, end_row);
13409                    start_row = Some(start);
13410                    end_row = Some(end);
13411                } else {
13412                    // Merge two hunks.
13413                    *current_end = end;
13414                }
13415            } else {
13416                unreachable!();
13417            }
13418        }
13419        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13420        push_region(start_row, end_row);
13421        results
13422    }
13423
13424    pub fn gutter_highlights_in_range(
13425        &self,
13426        search_range: Range<Anchor>,
13427        display_snapshot: &DisplaySnapshot,
13428        cx: &App,
13429    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13430        let mut results = Vec::new();
13431        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13432            let color = color_fetcher(cx);
13433            let start_ix = match ranges.binary_search_by(|probe| {
13434                let cmp = probe
13435                    .end
13436                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13437                if cmp.is_gt() {
13438                    Ordering::Greater
13439                } else {
13440                    Ordering::Less
13441                }
13442            }) {
13443                Ok(i) | Err(i) => i,
13444            };
13445            for range in &ranges[start_ix..] {
13446                if range
13447                    .start
13448                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13449                    .is_ge()
13450                {
13451                    break;
13452                }
13453
13454                let start = range.start.to_display_point(display_snapshot);
13455                let end = range.end.to_display_point(display_snapshot);
13456                results.push((start..end, color))
13457            }
13458        }
13459        results
13460    }
13461
13462    /// Get the text ranges corresponding to the redaction query
13463    pub fn redacted_ranges(
13464        &self,
13465        search_range: Range<Anchor>,
13466        display_snapshot: &DisplaySnapshot,
13467        cx: &App,
13468    ) -> Vec<Range<DisplayPoint>> {
13469        display_snapshot
13470            .buffer_snapshot
13471            .redacted_ranges(search_range, |file| {
13472                if let Some(file) = file {
13473                    file.is_private()
13474                        && EditorSettings::get(
13475                            Some(SettingsLocation {
13476                                worktree_id: file.worktree_id(cx),
13477                                path: file.path().as_ref(),
13478                            }),
13479                            cx,
13480                        )
13481                        .redact_private_values
13482                } else {
13483                    false
13484                }
13485            })
13486            .map(|range| {
13487                range.start.to_display_point(display_snapshot)
13488                    ..range.end.to_display_point(display_snapshot)
13489            })
13490            .collect()
13491    }
13492
13493    pub fn highlight_text<T: 'static>(
13494        &mut self,
13495        ranges: Vec<Range<Anchor>>,
13496        style: HighlightStyle,
13497        cx: &mut Context<Self>,
13498    ) {
13499        self.display_map.update(cx, |map, _| {
13500            map.highlight_text(TypeId::of::<T>(), ranges, style)
13501        });
13502        cx.notify();
13503    }
13504
13505    pub(crate) fn highlight_inlays<T: 'static>(
13506        &mut self,
13507        highlights: Vec<InlayHighlight>,
13508        style: HighlightStyle,
13509        cx: &mut Context<Self>,
13510    ) {
13511        self.display_map.update(cx, |map, _| {
13512            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13513        });
13514        cx.notify();
13515    }
13516
13517    pub fn text_highlights<'a, T: 'static>(
13518        &'a self,
13519        cx: &'a App,
13520    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13521        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13522    }
13523
13524    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13525        let cleared = self
13526            .display_map
13527            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13528        if cleared {
13529            cx.notify();
13530        }
13531    }
13532
13533    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13534        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13535            && self.focus_handle.is_focused(window)
13536    }
13537
13538    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13539        self.show_cursor_when_unfocused = is_enabled;
13540        cx.notify();
13541    }
13542
13543    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13544        self.project
13545            .as_ref()
13546            .map(|project| project.read(cx).lsp_store())
13547    }
13548
13549    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13550        cx.notify();
13551    }
13552
13553    fn on_buffer_event(
13554        &mut self,
13555        multibuffer: &Entity<MultiBuffer>,
13556        event: &multi_buffer::Event,
13557        window: &mut Window,
13558        cx: &mut Context<Self>,
13559    ) {
13560        match event {
13561            multi_buffer::Event::Edited {
13562                singleton_buffer_edited,
13563                edited_buffer: buffer_edited,
13564            } => {
13565                self.scrollbar_marker_state.dirty = true;
13566                self.active_indent_guides_state.dirty = true;
13567                self.refresh_active_diagnostics(cx);
13568                self.refresh_code_actions(window, cx);
13569                if self.has_active_inline_completion() {
13570                    self.update_visible_inline_completion(window, cx);
13571                }
13572                if let Some(buffer) = buffer_edited {
13573                    let buffer_id = buffer.read(cx).remote_id();
13574                    if !self.registered_buffers.contains_key(&buffer_id) {
13575                        if let Some(lsp_store) = self.lsp_store(cx) {
13576                            lsp_store.update(cx, |lsp_store, cx| {
13577                                self.registered_buffers.insert(
13578                                    buffer_id,
13579                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13580                                );
13581                            })
13582                        }
13583                    }
13584                }
13585                cx.emit(EditorEvent::BufferEdited);
13586                cx.emit(SearchEvent::MatchesInvalidated);
13587                if *singleton_buffer_edited {
13588                    if let Some(project) = &self.project {
13589                        let project = project.read(cx);
13590                        #[allow(clippy::mutable_key_type)]
13591                        let languages_affected = multibuffer
13592                            .read(cx)
13593                            .all_buffers()
13594                            .into_iter()
13595                            .filter_map(|buffer| {
13596                                let buffer = buffer.read(cx);
13597                                let language = buffer.language()?;
13598                                if project.is_local()
13599                                    && project
13600                                        .language_servers_for_local_buffer(buffer, cx)
13601                                        .count()
13602                                        == 0
13603                                {
13604                                    None
13605                                } else {
13606                                    Some(language)
13607                                }
13608                            })
13609                            .cloned()
13610                            .collect::<HashSet<_>>();
13611                        if !languages_affected.is_empty() {
13612                            self.refresh_inlay_hints(
13613                                InlayHintRefreshReason::BufferEdited(languages_affected),
13614                                cx,
13615                            );
13616                        }
13617                    }
13618                }
13619
13620                let Some(project) = &self.project else { return };
13621                let (telemetry, is_via_ssh) = {
13622                    let project = project.read(cx);
13623                    let telemetry = project.client().telemetry().clone();
13624                    let is_via_ssh = project.is_via_ssh();
13625                    (telemetry, is_via_ssh)
13626                };
13627                refresh_linked_ranges(self, window, cx);
13628                telemetry.log_edit_event("editor", is_via_ssh);
13629            }
13630            multi_buffer::Event::ExcerptsAdded {
13631                buffer,
13632                predecessor,
13633                excerpts,
13634            } => {
13635                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13636                let buffer_id = buffer.read(cx).remote_id();
13637                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13638                    if let Some(project) = &self.project {
13639                        get_unstaged_changes_for_buffers(
13640                            project,
13641                            [buffer.clone()],
13642                            self.buffer.clone(),
13643                            cx,
13644                        );
13645                    }
13646                }
13647                cx.emit(EditorEvent::ExcerptsAdded {
13648                    buffer: buffer.clone(),
13649                    predecessor: *predecessor,
13650                    excerpts: excerpts.clone(),
13651                });
13652                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13653            }
13654            multi_buffer::Event::ExcerptsRemoved { ids } => {
13655                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13656                let buffer = self.buffer.read(cx);
13657                self.registered_buffers
13658                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13659                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13660            }
13661            multi_buffer::Event::ExcerptsEdited { ids } => {
13662                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13663            }
13664            multi_buffer::Event::ExcerptsExpanded { ids } => {
13665                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13666                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13667            }
13668            multi_buffer::Event::Reparsed(buffer_id) => {
13669                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13670
13671                cx.emit(EditorEvent::Reparsed(*buffer_id));
13672            }
13673            multi_buffer::Event::DiffHunksToggled => {
13674                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13675            }
13676            multi_buffer::Event::LanguageChanged(buffer_id) => {
13677                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13678                cx.emit(EditorEvent::Reparsed(*buffer_id));
13679                cx.notify();
13680            }
13681            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13682            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13683            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13684                cx.emit(EditorEvent::TitleChanged)
13685            }
13686            // multi_buffer::Event::DiffBaseChanged => {
13687            //     self.scrollbar_marker_state.dirty = true;
13688            //     cx.emit(EditorEvent::DiffBaseChanged);
13689            //     cx.notify();
13690            // }
13691            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13692            multi_buffer::Event::DiagnosticsUpdated => {
13693                self.refresh_active_diagnostics(cx);
13694                self.scrollbar_marker_state.dirty = true;
13695                cx.notify();
13696            }
13697            _ => {}
13698        };
13699    }
13700
13701    fn on_display_map_changed(
13702        &mut self,
13703        _: Entity<DisplayMap>,
13704        _: &mut Window,
13705        cx: &mut Context<Self>,
13706    ) {
13707        cx.notify();
13708    }
13709
13710    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13711        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13712        self.refresh_inline_completion(true, false, window, cx);
13713        self.refresh_inlay_hints(
13714            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13715                self.selections.newest_anchor().head(),
13716                &self.buffer.read(cx).snapshot(cx),
13717                cx,
13718            )),
13719            cx,
13720        );
13721
13722        let old_cursor_shape = self.cursor_shape;
13723
13724        {
13725            let editor_settings = EditorSettings::get_global(cx);
13726            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13727            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13728            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13729        }
13730
13731        if old_cursor_shape != self.cursor_shape {
13732            cx.emit(EditorEvent::CursorShapeChanged);
13733        }
13734
13735        let project_settings = ProjectSettings::get_global(cx);
13736        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13737
13738        if self.mode == EditorMode::Full {
13739            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13740            if self.git_blame_inline_enabled != inline_blame_enabled {
13741                self.toggle_git_blame_inline_internal(false, window, cx);
13742            }
13743        }
13744
13745        cx.notify();
13746    }
13747
13748    pub fn set_searchable(&mut self, searchable: bool) {
13749        self.searchable = searchable;
13750    }
13751
13752    pub fn searchable(&self) -> bool {
13753        self.searchable
13754    }
13755
13756    fn open_proposed_changes_editor(
13757        &mut self,
13758        _: &OpenProposedChangesEditor,
13759        window: &mut Window,
13760        cx: &mut Context<Self>,
13761    ) {
13762        let Some(workspace) = self.workspace() else {
13763            cx.propagate();
13764            return;
13765        };
13766
13767        let selections = self.selections.all::<usize>(cx);
13768        let multi_buffer = self.buffer.read(cx);
13769        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13770        let mut new_selections_by_buffer = HashMap::default();
13771        for selection in selections {
13772            for (buffer, range, _) in
13773                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13774            {
13775                let mut range = range.to_point(buffer);
13776                range.start.column = 0;
13777                range.end.column = buffer.line_len(range.end.row);
13778                new_selections_by_buffer
13779                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13780                    .or_insert(Vec::new())
13781                    .push(range)
13782            }
13783        }
13784
13785        let proposed_changes_buffers = new_selections_by_buffer
13786            .into_iter()
13787            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13788            .collect::<Vec<_>>();
13789        let proposed_changes_editor = cx.new(|cx| {
13790            ProposedChangesEditor::new(
13791                "Proposed changes",
13792                proposed_changes_buffers,
13793                self.project.clone(),
13794                window,
13795                cx,
13796            )
13797        });
13798
13799        window.defer(cx, move |window, cx| {
13800            workspace.update(cx, |workspace, cx| {
13801                workspace.active_pane().update(cx, |pane, cx| {
13802                    pane.add_item(
13803                        Box::new(proposed_changes_editor),
13804                        true,
13805                        true,
13806                        None,
13807                        window,
13808                        cx,
13809                    );
13810                });
13811            });
13812        });
13813    }
13814
13815    pub fn open_excerpts_in_split(
13816        &mut self,
13817        _: &OpenExcerptsSplit,
13818        window: &mut Window,
13819        cx: &mut Context<Self>,
13820    ) {
13821        self.open_excerpts_common(None, true, window, cx)
13822    }
13823
13824    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13825        self.open_excerpts_common(None, false, window, cx)
13826    }
13827
13828    fn open_excerpts_common(
13829        &mut self,
13830        jump_data: Option<JumpData>,
13831        split: bool,
13832        window: &mut Window,
13833        cx: &mut Context<Self>,
13834    ) {
13835        let Some(workspace) = self.workspace() else {
13836            cx.propagate();
13837            return;
13838        };
13839
13840        if self.buffer.read(cx).is_singleton() {
13841            cx.propagate();
13842            return;
13843        }
13844
13845        let mut new_selections_by_buffer = HashMap::default();
13846        match &jump_data {
13847            Some(JumpData::MultiBufferPoint {
13848                excerpt_id,
13849                position,
13850                anchor,
13851                line_offset_from_top,
13852            }) => {
13853                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13854                if let Some(buffer) = multi_buffer_snapshot
13855                    .buffer_id_for_excerpt(*excerpt_id)
13856                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13857                {
13858                    let buffer_snapshot = buffer.read(cx).snapshot();
13859                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13860                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13861                    } else {
13862                        buffer_snapshot.clip_point(*position, Bias::Left)
13863                    };
13864                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13865                    new_selections_by_buffer.insert(
13866                        buffer,
13867                        (
13868                            vec![jump_to_offset..jump_to_offset],
13869                            Some(*line_offset_from_top),
13870                        ),
13871                    );
13872                }
13873            }
13874            Some(JumpData::MultiBufferRow {
13875                row,
13876                line_offset_from_top,
13877            }) => {
13878                let point = MultiBufferPoint::new(row.0, 0);
13879                if let Some((buffer, buffer_point, _)) =
13880                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13881                {
13882                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13883                    new_selections_by_buffer
13884                        .entry(buffer)
13885                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13886                        .0
13887                        .push(buffer_offset..buffer_offset)
13888                }
13889            }
13890            None => {
13891                let selections = self.selections.all::<usize>(cx);
13892                let multi_buffer = self.buffer.read(cx);
13893                for selection in selections {
13894                    for (buffer, mut range, _) in multi_buffer
13895                        .snapshot(cx)
13896                        .range_to_buffer_ranges(selection.range())
13897                    {
13898                        // When editing branch buffers, jump to the corresponding location
13899                        // in their base buffer.
13900                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13901                        let buffer = buffer_handle.read(cx);
13902                        if let Some(base_buffer) = buffer.base_buffer() {
13903                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13904                            buffer_handle = base_buffer;
13905                        }
13906
13907                        if selection.reversed {
13908                            mem::swap(&mut range.start, &mut range.end);
13909                        }
13910                        new_selections_by_buffer
13911                            .entry(buffer_handle)
13912                            .or_insert((Vec::new(), None))
13913                            .0
13914                            .push(range)
13915                    }
13916                }
13917            }
13918        }
13919
13920        if new_selections_by_buffer.is_empty() {
13921            return;
13922        }
13923
13924        // We defer the pane interaction because we ourselves are a workspace item
13925        // and activating a new item causes the pane to call a method on us reentrantly,
13926        // which panics if we're on the stack.
13927        window.defer(cx, move |window, cx| {
13928            workspace.update(cx, |workspace, cx| {
13929                let pane = if split {
13930                    workspace.adjacent_pane(window, cx)
13931                } else {
13932                    workspace.active_pane().clone()
13933                };
13934
13935                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13936                    let editor = buffer
13937                        .read(cx)
13938                        .file()
13939                        .is_none()
13940                        .then(|| {
13941                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13942                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13943                            // Instead, we try to activate the existing editor in the pane first.
13944                            let (editor, pane_item_index) =
13945                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13946                                    let editor = item.downcast::<Editor>()?;
13947                                    let singleton_buffer =
13948                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13949                                    if singleton_buffer == buffer {
13950                                        Some((editor, i))
13951                                    } else {
13952                                        None
13953                                    }
13954                                })?;
13955                            pane.update(cx, |pane, cx| {
13956                                pane.activate_item(pane_item_index, true, true, window, cx)
13957                            });
13958                            Some(editor)
13959                        })
13960                        .flatten()
13961                        .unwrap_or_else(|| {
13962                            workspace.open_project_item::<Self>(
13963                                pane.clone(),
13964                                buffer,
13965                                true,
13966                                true,
13967                                window,
13968                                cx,
13969                            )
13970                        });
13971
13972                    editor.update(cx, |editor, cx| {
13973                        let autoscroll = match scroll_offset {
13974                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13975                            None => Autoscroll::newest(),
13976                        };
13977                        let nav_history = editor.nav_history.take();
13978                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13979                            s.select_ranges(ranges);
13980                        });
13981                        editor.nav_history = nav_history;
13982                    });
13983                }
13984            })
13985        });
13986    }
13987
13988    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13989        let snapshot = self.buffer.read(cx).read(cx);
13990        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13991        Some(
13992            ranges
13993                .iter()
13994                .map(move |range| {
13995                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13996                })
13997                .collect(),
13998        )
13999    }
14000
14001    fn selection_replacement_ranges(
14002        &self,
14003        range: Range<OffsetUtf16>,
14004        cx: &mut App,
14005    ) -> Vec<Range<OffsetUtf16>> {
14006        let selections = self.selections.all::<OffsetUtf16>(cx);
14007        let newest_selection = selections
14008            .iter()
14009            .max_by_key(|selection| selection.id)
14010            .unwrap();
14011        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14012        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14013        let snapshot = self.buffer.read(cx).read(cx);
14014        selections
14015            .into_iter()
14016            .map(|mut selection| {
14017                selection.start.0 =
14018                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14019                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14020                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14021                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14022            })
14023            .collect()
14024    }
14025
14026    fn report_editor_event(
14027        &self,
14028        event_type: &'static str,
14029        file_extension: Option<String>,
14030        cx: &App,
14031    ) {
14032        if cfg!(any(test, feature = "test-support")) {
14033            return;
14034        }
14035
14036        let Some(project) = &self.project else { return };
14037
14038        // If None, we are in a file without an extension
14039        let file = self
14040            .buffer
14041            .read(cx)
14042            .as_singleton()
14043            .and_then(|b| b.read(cx).file());
14044        let file_extension = file_extension.or(file
14045            .as_ref()
14046            .and_then(|file| Path::new(file.file_name(cx)).extension())
14047            .and_then(|e| e.to_str())
14048            .map(|a| a.to_string()));
14049
14050        let vim_mode = cx
14051            .global::<SettingsStore>()
14052            .raw_user_settings()
14053            .get("vim_mode")
14054            == Some(&serde_json::Value::Bool(true));
14055
14056        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14057            == language::language_settings::InlineCompletionProvider::Copilot;
14058        let copilot_enabled_for_language = self
14059            .buffer
14060            .read(cx)
14061            .settings_at(0, cx)
14062            .show_inline_completions;
14063
14064        let project = project.read(cx);
14065        telemetry::event!(
14066            event_type,
14067            file_extension,
14068            vim_mode,
14069            copilot_enabled,
14070            copilot_enabled_for_language,
14071            is_via_ssh = project.is_via_ssh(),
14072        );
14073    }
14074
14075    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14076    /// with each line being an array of {text, highlight} objects.
14077    fn copy_highlight_json(
14078        &mut self,
14079        _: &CopyHighlightJson,
14080        window: &mut Window,
14081        cx: &mut Context<Self>,
14082    ) {
14083        #[derive(Serialize)]
14084        struct Chunk<'a> {
14085            text: String,
14086            highlight: Option<&'a str>,
14087        }
14088
14089        let snapshot = self.buffer.read(cx).snapshot(cx);
14090        let range = self
14091            .selected_text_range(false, window, cx)
14092            .and_then(|selection| {
14093                if selection.range.is_empty() {
14094                    None
14095                } else {
14096                    Some(selection.range)
14097                }
14098            })
14099            .unwrap_or_else(|| 0..snapshot.len());
14100
14101        let chunks = snapshot.chunks(range, true);
14102        let mut lines = Vec::new();
14103        let mut line: VecDeque<Chunk> = VecDeque::new();
14104
14105        let Some(style) = self.style.as_ref() else {
14106            return;
14107        };
14108
14109        for chunk in chunks {
14110            let highlight = chunk
14111                .syntax_highlight_id
14112                .and_then(|id| id.name(&style.syntax));
14113            let mut chunk_lines = chunk.text.split('\n').peekable();
14114            while let Some(text) = chunk_lines.next() {
14115                let mut merged_with_last_token = false;
14116                if let Some(last_token) = line.back_mut() {
14117                    if last_token.highlight == highlight {
14118                        last_token.text.push_str(text);
14119                        merged_with_last_token = true;
14120                    }
14121                }
14122
14123                if !merged_with_last_token {
14124                    line.push_back(Chunk {
14125                        text: text.into(),
14126                        highlight,
14127                    });
14128                }
14129
14130                if chunk_lines.peek().is_some() {
14131                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14132                        line.pop_front();
14133                    }
14134                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14135                        line.pop_back();
14136                    }
14137
14138                    lines.push(mem::take(&mut line));
14139                }
14140            }
14141        }
14142
14143        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14144            return;
14145        };
14146        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14147    }
14148
14149    pub fn open_context_menu(
14150        &mut self,
14151        _: &OpenContextMenu,
14152        window: &mut Window,
14153        cx: &mut Context<Self>,
14154    ) {
14155        self.request_autoscroll(Autoscroll::newest(), cx);
14156        let position = self.selections.newest_display(cx).start;
14157        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14158    }
14159
14160    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14161        &self.inlay_hint_cache
14162    }
14163
14164    pub fn replay_insert_event(
14165        &mut self,
14166        text: &str,
14167        relative_utf16_range: Option<Range<isize>>,
14168        window: &mut Window,
14169        cx: &mut Context<Self>,
14170    ) {
14171        if !self.input_enabled {
14172            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14173            return;
14174        }
14175        if let Some(relative_utf16_range) = relative_utf16_range {
14176            let selections = self.selections.all::<OffsetUtf16>(cx);
14177            self.change_selections(None, window, cx, |s| {
14178                let new_ranges = selections.into_iter().map(|range| {
14179                    let start = OffsetUtf16(
14180                        range
14181                            .head()
14182                            .0
14183                            .saturating_add_signed(relative_utf16_range.start),
14184                    );
14185                    let end = OffsetUtf16(
14186                        range
14187                            .head()
14188                            .0
14189                            .saturating_add_signed(relative_utf16_range.end),
14190                    );
14191                    start..end
14192                });
14193                s.select_ranges(new_ranges);
14194            });
14195        }
14196
14197        self.handle_input(text, window, cx);
14198    }
14199
14200    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14201        let Some(provider) = self.semantics_provider.as_ref() else {
14202            return false;
14203        };
14204
14205        let mut supports = false;
14206        self.buffer().read(cx).for_each_buffer(|buffer| {
14207            supports |= provider.supports_inlay_hints(buffer, cx);
14208        });
14209        supports
14210    }
14211    pub fn is_focused(&self, window: &mut Window) -> bool {
14212        self.focus_handle.is_focused(window)
14213    }
14214
14215    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14216        cx.emit(EditorEvent::Focused);
14217
14218        if let Some(descendant) = self
14219            .last_focused_descendant
14220            .take()
14221            .and_then(|descendant| descendant.upgrade())
14222        {
14223            window.focus(&descendant);
14224        } else {
14225            if let Some(blame) = self.blame.as_ref() {
14226                blame.update(cx, GitBlame::focus)
14227            }
14228
14229            self.blink_manager.update(cx, BlinkManager::enable);
14230            self.show_cursor_names(window, cx);
14231            self.buffer.update(cx, |buffer, cx| {
14232                buffer.finalize_last_transaction(cx);
14233                if self.leader_peer_id.is_none() {
14234                    buffer.set_active_selections(
14235                        &self.selections.disjoint_anchors(),
14236                        self.selections.line_mode,
14237                        self.cursor_shape,
14238                        cx,
14239                    );
14240                }
14241            });
14242        }
14243    }
14244
14245    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14246        cx.emit(EditorEvent::FocusedIn)
14247    }
14248
14249    fn handle_focus_out(
14250        &mut self,
14251        event: FocusOutEvent,
14252        _window: &mut Window,
14253        _cx: &mut Context<Self>,
14254    ) {
14255        if event.blurred != self.focus_handle {
14256            self.last_focused_descendant = Some(event.blurred);
14257        }
14258    }
14259
14260    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14261        self.blink_manager.update(cx, BlinkManager::disable);
14262        self.buffer
14263            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14264
14265        if let Some(blame) = self.blame.as_ref() {
14266            blame.update(cx, GitBlame::blur)
14267        }
14268        if !self.hover_state.focused(window, cx) {
14269            hide_hover(self, cx);
14270        }
14271
14272        self.hide_context_menu(window, cx);
14273        cx.emit(EditorEvent::Blurred);
14274        cx.notify();
14275    }
14276
14277    pub fn register_action<A: Action>(
14278        &mut self,
14279        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14280    ) -> Subscription {
14281        let id = self.next_editor_action_id.post_inc();
14282        let listener = Arc::new(listener);
14283        self.editor_actions.borrow_mut().insert(
14284            id,
14285            Box::new(move |window, _| {
14286                let listener = listener.clone();
14287                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14288                    let action = action.downcast_ref().unwrap();
14289                    if phase == DispatchPhase::Bubble {
14290                        listener(action, window, cx)
14291                    }
14292                })
14293            }),
14294        );
14295
14296        let editor_actions = self.editor_actions.clone();
14297        Subscription::new(move || {
14298            editor_actions.borrow_mut().remove(&id);
14299        })
14300    }
14301
14302    pub fn file_header_size(&self) -> u32 {
14303        FILE_HEADER_HEIGHT
14304    }
14305
14306    pub fn revert(
14307        &mut self,
14308        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14309        window: &mut Window,
14310        cx: &mut Context<Self>,
14311    ) {
14312        self.buffer().update(cx, |multi_buffer, cx| {
14313            for (buffer_id, changes) in revert_changes {
14314                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14315                    buffer.update(cx, |buffer, cx| {
14316                        buffer.edit(
14317                            changes.into_iter().map(|(range, text)| {
14318                                (range, text.to_string().map(Arc::<str>::from))
14319                            }),
14320                            None,
14321                            cx,
14322                        );
14323                    });
14324                }
14325            }
14326        });
14327        self.change_selections(None, window, cx, |selections| selections.refresh());
14328    }
14329
14330    pub fn to_pixel_point(
14331        &self,
14332        source: multi_buffer::Anchor,
14333        editor_snapshot: &EditorSnapshot,
14334        window: &mut Window,
14335    ) -> Option<gpui::Point<Pixels>> {
14336        let source_point = source.to_display_point(editor_snapshot);
14337        self.display_to_pixel_point(source_point, editor_snapshot, window)
14338    }
14339
14340    pub fn display_to_pixel_point(
14341        &self,
14342        source: DisplayPoint,
14343        editor_snapshot: &EditorSnapshot,
14344        window: &mut Window,
14345    ) -> Option<gpui::Point<Pixels>> {
14346        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14347        let text_layout_details = self.text_layout_details(window);
14348        let scroll_top = text_layout_details
14349            .scroll_anchor
14350            .scroll_position(editor_snapshot)
14351            .y;
14352
14353        if source.row().as_f32() < scroll_top.floor() {
14354            return None;
14355        }
14356        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14357        let source_y = line_height * (source.row().as_f32() - scroll_top);
14358        Some(gpui::Point::new(source_x, source_y))
14359    }
14360
14361    pub fn has_active_completions_menu(&self) -> bool {
14362        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14363            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14364        })
14365    }
14366
14367    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14368        self.addons
14369            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14370    }
14371
14372    pub fn unregister_addon<T: Addon>(&mut self) {
14373        self.addons.remove(&std::any::TypeId::of::<T>());
14374    }
14375
14376    pub fn addon<T: Addon>(&self) -> Option<&T> {
14377        let type_id = std::any::TypeId::of::<T>();
14378        self.addons
14379            .get(&type_id)
14380            .and_then(|item| item.to_any().downcast_ref::<T>())
14381    }
14382
14383    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14384        let text_layout_details = self.text_layout_details(window);
14385        let style = &text_layout_details.editor_style;
14386        let font_id = window.text_system().resolve_font(&style.text.font());
14387        let font_size = style.text.font_size.to_pixels(window.rem_size());
14388        let line_height = style.text.line_height_in_pixels(window.rem_size());
14389        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14390
14391        gpui::Point::new(em_width, line_height)
14392    }
14393}
14394
14395fn get_unstaged_changes_for_buffers(
14396    project: &Entity<Project>,
14397    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14398    buffer: Entity<MultiBuffer>,
14399    cx: &mut App,
14400) {
14401    let mut tasks = Vec::new();
14402    project.update(cx, |project, cx| {
14403        for buffer in buffers {
14404            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14405        }
14406    });
14407    cx.spawn(|mut cx| async move {
14408        let change_sets = futures::future::join_all(tasks).await;
14409        buffer
14410            .update(&mut cx, |buffer, cx| {
14411                for change_set in change_sets {
14412                    if let Some(change_set) = change_set.log_err() {
14413                        buffer.add_change_set(change_set, cx);
14414                    }
14415                }
14416            })
14417            .ok();
14418    })
14419    .detach();
14420}
14421
14422fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14423    let tab_size = tab_size.get() as usize;
14424    let mut width = offset;
14425
14426    for ch in text.chars() {
14427        width += if ch == '\t' {
14428            tab_size - (width % tab_size)
14429        } else {
14430            1
14431        };
14432    }
14433
14434    width - offset
14435}
14436
14437#[cfg(test)]
14438mod tests {
14439    use super::*;
14440
14441    #[test]
14442    fn test_string_size_with_expanded_tabs() {
14443        let nz = |val| NonZeroU32::new(val).unwrap();
14444        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14445        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14446        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14447        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14448        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14449        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14450        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14451        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14452    }
14453}
14454
14455/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14456struct WordBreakingTokenizer<'a> {
14457    input: &'a str,
14458}
14459
14460impl<'a> WordBreakingTokenizer<'a> {
14461    fn new(input: &'a str) -> Self {
14462        Self { input }
14463    }
14464}
14465
14466fn is_char_ideographic(ch: char) -> bool {
14467    use unicode_script::Script::*;
14468    use unicode_script::UnicodeScript;
14469    matches!(ch.script(), Han | Tangut | Yi)
14470}
14471
14472fn is_grapheme_ideographic(text: &str) -> bool {
14473    text.chars().any(is_char_ideographic)
14474}
14475
14476fn is_grapheme_whitespace(text: &str) -> bool {
14477    text.chars().any(|x| x.is_whitespace())
14478}
14479
14480fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14481    text.chars().next().map_or(false, |ch| {
14482        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14483    })
14484}
14485
14486#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14487struct WordBreakToken<'a> {
14488    token: &'a str,
14489    grapheme_len: usize,
14490    is_whitespace: bool,
14491}
14492
14493impl<'a> Iterator for WordBreakingTokenizer<'a> {
14494    /// Yields a span, the count of graphemes in the token, and whether it was
14495    /// whitespace. Note that it also breaks at word boundaries.
14496    type Item = WordBreakToken<'a>;
14497
14498    fn next(&mut self) -> Option<Self::Item> {
14499        use unicode_segmentation::UnicodeSegmentation;
14500        if self.input.is_empty() {
14501            return None;
14502        }
14503
14504        let mut iter = self.input.graphemes(true).peekable();
14505        let mut offset = 0;
14506        let mut graphemes = 0;
14507        if let Some(first_grapheme) = iter.next() {
14508            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14509            offset += first_grapheme.len();
14510            graphemes += 1;
14511            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14512                if let Some(grapheme) = iter.peek().copied() {
14513                    if should_stay_with_preceding_ideograph(grapheme) {
14514                        offset += grapheme.len();
14515                        graphemes += 1;
14516                    }
14517                }
14518            } else {
14519                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14520                let mut next_word_bound = words.peek().copied();
14521                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14522                    next_word_bound = words.next();
14523                }
14524                while let Some(grapheme) = iter.peek().copied() {
14525                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14526                        break;
14527                    };
14528                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14529                        break;
14530                    };
14531                    offset += grapheme.len();
14532                    graphemes += 1;
14533                    iter.next();
14534                }
14535            }
14536            let token = &self.input[..offset];
14537            self.input = &self.input[offset..];
14538            if is_whitespace {
14539                Some(WordBreakToken {
14540                    token: " ",
14541                    grapheme_len: 1,
14542                    is_whitespace: true,
14543                })
14544            } else {
14545                Some(WordBreakToken {
14546                    token,
14547                    grapheme_len: graphemes,
14548                    is_whitespace: false,
14549                })
14550            }
14551        } else {
14552            None
14553        }
14554    }
14555}
14556
14557#[test]
14558fn test_word_breaking_tokenizer() {
14559    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14560        ("", &[]),
14561        ("  ", &[(" ", 1, true)]),
14562        ("Ʒ", &[("Ʒ", 1, false)]),
14563        ("Ǽ", &[("Ǽ", 1, false)]),
14564        ("", &[("", 1, false)]),
14565        ("⋑⋑", &[("⋑⋑", 2, false)]),
14566        (
14567            "原理,进而",
14568            &[
14569                ("", 1, false),
14570                ("理,", 2, false),
14571                ("", 1, false),
14572                ("", 1, false),
14573            ],
14574        ),
14575        (
14576            "hello world",
14577            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14578        ),
14579        (
14580            "hello, world",
14581            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14582        ),
14583        (
14584            "  hello world",
14585            &[
14586                (" ", 1, true),
14587                ("hello", 5, false),
14588                (" ", 1, true),
14589                ("world", 5, false),
14590            ],
14591        ),
14592        (
14593            "这是什么 \n 钢笔",
14594            &[
14595                ("", 1, false),
14596                ("", 1, false),
14597                ("", 1, false),
14598                ("", 1, false),
14599                (" ", 1, true),
14600                ("", 1, false),
14601                ("", 1, false),
14602            ],
14603        ),
14604        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14605    ];
14606
14607    for (input, result) in tests {
14608        assert_eq!(
14609            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14610            result
14611                .iter()
14612                .copied()
14613                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14614                    token,
14615                    grapheme_len,
14616                    is_whitespace,
14617                })
14618                .collect::<Vec<_>>()
14619        );
14620    }
14621}
14622
14623fn wrap_with_prefix(
14624    line_prefix: String,
14625    unwrapped_text: String,
14626    wrap_column: usize,
14627    tab_size: NonZeroU32,
14628) -> String {
14629    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14630    let mut wrapped_text = String::new();
14631    let mut current_line = line_prefix.clone();
14632
14633    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14634    let mut current_line_len = line_prefix_len;
14635    for WordBreakToken {
14636        token,
14637        grapheme_len,
14638        is_whitespace,
14639    } in tokenizer
14640    {
14641        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14642            wrapped_text.push_str(current_line.trim_end());
14643            wrapped_text.push('\n');
14644            current_line.truncate(line_prefix.len());
14645            current_line_len = line_prefix_len;
14646            if !is_whitespace {
14647                current_line.push_str(token);
14648                current_line_len += grapheme_len;
14649            }
14650        } else if !is_whitespace {
14651            current_line.push_str(token);
14652            current_line_len += grapheme_len;
14653        } else if current_line_len != line_prefix_len {
14654            current_line.push(' ');
14655            current_line_len += 1;
14656        }
14657    }
14658
14659    if !current_line.is_empty() {
14660        wrapped_text.push_str(&current_line);
14661    }
14662    wrapped_text
14663}
14664
14665#[test]
14666fn test_wrap_with_prefix() {
14667    assert_eq!(
14668        wrap_with_prefix(
14669            "# ".to_string(),
14670            "abcdefg".to_string(),
14671            4,
14672            NonZeroU32::new(4).unwrap()
14673        ),
14674        "# abcdefg"
14675    );
14676    assert_eq!(
14677        wrap_with_prefix(
14678            "".to_string(),
14679            "\thello world".to_string(),
14680            8,
14681            NonZeroU32::new(4).unwrap()
14682        ),
14683        "hello\nworld"
14684    );
14685    assert_eq!(
14686        wrap_with_prefix(
14687            "// ".to_string(),
14688            "xx \nyy zz aa bb cc".to_string(),
14689            12,
14690            NonZeroU32::new(4).unwrap()
14691        ),
14692        "// xx yy zz\n// aa bb cc"
14693    );
14694    assert_eq!(
14695        wrap_with_prefix(
14696            String::new(),
14697            "这是什么 \n 钢笔".to_string(),
14698            3,
14699            NonZeroU32::new(4).unwrap()
14700        ),
14701        "这是什\n么 钢\n"
14702    );
14703}
14704
14705pub trait CollaborationHub {
14706    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14707    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14708    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14709}
14710
14711impl CollaborationHub for Entity<Project> {
14712    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14713        self.read(cx).collaborators()
14714    }
14715
14716    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14717        self.read(cx).user_store().read(cx).participant_indices()
14718    }
14719
14720    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14721        let this = self.read(cx);
14722        let user_ids = this.collaborators().values().map(|c| c.user_id);
14723        this.user_store().read_with(cx, |user_store, cx| {
14724            user_store.participant_names(user_ids, cx)
14725        })
14726    }
14727}
14728
14729pub trait SemanticsProvider {
14730    fn hover(
14731        &self,
14732        buffer: &Entity<Buffer>,
14733        position: text::Anchor,
14734        cx: &mut App,
14735    ) -> Option<Task<Vec<project::Hover>>>;
14736
14737    fn inlay_hints(
14738        &self,
14739        buffer_handle: Entity<Buffer>,
14740        range: Range<text::Anchor>,
14741        cx: &mut App,
14742    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14743
14744    fn resolve_inlay_hint(
14745        &self,
14746        hint: InlayHint,
14747        buffer_handle: Entity<Buffer>,
14748        server_id: LanguageServerId,
14749        cx: &mut App,
14750    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14751
14752    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14753
14754    fn document_highlights(
14755        &self,
14756        buffer: &Entity<Buffer>,
14757        position: text::Anchor,
14758        cx: &mut App,
14759    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14760
14761    fn definitions(
14762        &self,
14763        buffer: &Entity<Buffer>,
14764        position: text::Anchor,
14765        kind: GotoDefinitionKind,
14766        cx: &mut App,
14767    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14768
14769    fn range_for_rename(
14770        &self,
14771        buffer: &Entity<Buffer>,
14772        position: text::Anchor,
14773        cx: &mut App,
14774    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14775
14776    fn perform_rename(
14777        &self,
14778        buffer: &Entity<Buffer>,
14779        position: text::Anchor,
14780        new_name: String,
14781        cx: &mut App,
14782    ) -> Option<Task<Result<ProjectTransaction>>>;
14783}
14784
14785pub trait CompletionProvider {
14786    fn completions(
14787        &self,
14788        buffer: &Entity<Buffer>,
14789        buffer_position: text::Anchor,
14790        trigger: CompletionContext,
14791        window: &mut Window,
14792        cx: &mut Context<Editor>,
14793    ) -> Task<Result<Vec<Completion>>>;
14794
14795    fn resolve_completions(
14796        &self,
14797        buffer: Entity<Buffer>,
14798        completion_indices: Vec<usize>,
14799        completions: Rc<RefCell<Box<[Completion]>>>,
14800        cx: &mut Context<Editor>,
14801    ) -> Task<Result<bool>>;
14802
14803    fn apply_additional_edits_for_completion(
14804        &self,
14805        _buffer: Entity<Buffer>,
14806        _completions: Rc<RefCell<Box<[Completion]>>>,
14807        _completion_index: usize,
14808        _push_to_history: bool,
14809        _cx: &mut Context<Editor>,
14810    ) -> Task<Result<Option<language::Transaction>>> {
14811        Task::ready(Ok(None))
14812    }
14813
14814    fn is_completion_trigger(
14815        &self,
14816        buffer: &Entity<Buffer>,
14817        position: language::Anchor,
14818        text: &str,
14819        trigger_in_words: bool,
14820        cx: &mut Context<Editor>,
14821    ) -> bool;
14822
14823    fn sort_completions(&self) -> bool {
14824        true
14825    }
14826}
14827
14828pub trait CodeActionProvider {
14829    fn id(&self) -> Arc<str>;
14830
14831    fn code_actions(
14832        &self,
14833        buffer: &Entity<Buffer>,
14834        range: Range<text::Anchor>,
14835        window: &mut Window,
14836        cx: &mut App,
14837    ) -> Task<Result<Vec<CodeAction>>>;
14838
14839    fn apply_code_action(
14840        &self,
14841        buffer_handle: Entity<Buffer>,
14842        action: CodeAction,
14843        excerpt_id: ExcerptId,
14844        push_to_history: bool,
14845        window: &mut Window,
14846        cx: &mut App,
14847    ) -> Task<Result<ProjectTransaction>>;
14848}
14849
14850impl CodeActionProvider for Entity<Project> {
14851    fn id(&self) -> Arc<str> {
14852        "project".into()
14853    }
14854
14855    fn code_actions(
14856        &self,
14857        buffer: &Entity<Buffer>,
14858        range: Range<text::Anchor>,
14859        _window: &mut Window,
14860        cx: &mut App,
14861    ) -> Task<Result<Vec<CodeAction>>> {
14862        self.update(cx, |project, cx| {
14863            project.code_actions(buffer, range, None, cx)
14864        })
14865    }
14866
14867    fn apply_code_action(
14868        &self,
14869        buffer_handle: Entity<Buffer>,
14870        action: CodeAction,
14871        _excerpt_id: ExcerptId,
14872        push_to_history: bool,
14873        _window: &mut Window,
14874        cx: &mut App,
14875    ) -> Task<Result<ProjectTransaction>> {
14876        self.update(cx, |project, cx| {
14877            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14878        })
14879    }
14880}
14881
14882fn snippet_completions(
14883    project: &Project,
14884    buffer: &Entity<Buffer>,
14885    buffer_position: text::Anchor,
14886    cx: &mut App,
14887) -> Task<Result<Vec<Completion>>> {
14888    let language = buffer.read(cx).language_at(buffer_position);
14889    let language_name = language.as_ref().map(|language| language.lsp_id());
14890    let snippet_store = project.snippets().read(cx);
14891    let snippets = snippet_store.snippets_for(language_name, cx);
14892
14893    if snippets.is_empty() {
14894        return Task::ready(Ok(vec![]));
14895    }
14896    let snapshot = buffer.read(cx).text_snapshot();
14897    let chars: String = snapshot
14898        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14899        .collect();
14900
14901    let scope = language.map(|language| language.default_scope());
14902    let executor = cx.background_executor().clone();
14903
14904    cx.background_executor().spawn(async move {
14905        let classifier = CharClassifier::new(scope).for_completion(true);
14906        let mut last_word = chars
14907            .chars()
14908            .take_while(|c| classifier.is_word(*c))
14909            .collect::<String>();
14910        last_word = last_word.chars().rev().collect();
14911
14912        if last_word.is_empty() {
14913            return Ok(vec![]);
14914        }
14915
14916        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14917        let to_lsp = |point: &text::Anchor| {
14918            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14919            point_to_lsp(end)
14920        };
14921        let lsp_end = to_lsp(&buffer_position);
14922
14923        let candidates = snippets
14924            .iter()
14925            .enumerate()
14926            .flat_map(|(ix, snippet)| {
14927                snippet
14928                    .prefix
14929                    .iter()
14930                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14931            })
14932            .collect::<Vec<StringMatchCandidate>>();
14933
14934        let mut matches = fuzzy::match_strings(
14935            &candidates,
14936            &last_word,
14937            last_word.chars().any(|c| c.is_uppercase()),
14938            100,
14939            &Default::default(),
14940            executor,
14941        )
14942        .await;
14943
14944        // Remove all candidates where the query's start does not match the start of any word in the candidate
14945        if let Some(query_start) = last_word.chars().next() {
14946            matches.retain(|string_match| {
14947                split_words(&string_match.string).any(|word| {
14948                    // Check that the first codepoint of the word as lowercase matches the first
14949                    // codepoint of the query as lowercase
14950                    word.chars()
14951                        .flat_map(|codepoint| codepoint.to_lowercase())
14952                        .zip(query_start.to_lowercase())
14953                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14954                })
14955            });
14956        }
14957
14958        let matched_strings = matches
14959            .into_iter()
14960            .map(|m| m.string)
14961            .collect::<HashSet<_>>();
14962
14963        let result: Vec<Completion> = snippets
14964            .into_iter()
14965            .filter_map(|snippet| {
14966                let matching_prefix = snippet
14967                    .prefix
14968                    .iter()
14969                    .find(|prefix| matched_strings.contains(*prefix))?;
14970                let start = as_offset - last_word.len();
14971                let start = snapshot.anchor_before(start);
14972                let range = start..buffer_position;
14973                let lsp_start = to_lsp(&start);
14974                let lsp_range = lsp::Range {
14975                    start: lsp_start,
14976                    end: lsp_end,
14977                };
14978                Some(Completion {
14979                    old_range: range,
14980                    new_text: snippet.body.clone(),
14981                    resolved: false,
14982                    label: CodeLabel {
14983                        text: matching_prefix.clone(),
14984                        runs: vec![],
14985                        filter_range: 0..matching_prefix.len(),
14986                    },
14987                    server_id: LanguageServerId(usize::MAX),
14988                    documentation: snippet
14989                        .description
14990                        .clone()
14991                        .map(CompletionDocumentation::SingleLine),
14992                    lsp_completion: lsp::CompletionItem {
14993                        label: snippet.prefix.first().unwrap().clone(),
14994                        kind: Some(CompletionItemKind::SNIPPET),
14995                        label_details: snippet.description.as_ref().map(|description| {
14996                            lsp::CompletionItemLabelDetails {
14997                                detail: Some(description.clone()),
14998                                description: None,
14999                            }
15000                        }),
15001                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15002                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15003                            lsp::InsertReplaceEdit {
15004                                new_text: snippet.body.clone(),
15005                                insert: lsp_range,
15006                                replace: lsp_range,
15007                            },
15008                        )),
15009                        filter_text: Some(snippet.body.clone()),
15010                        sort_text: Some(char::MAX.to_string()),
15011                        ..Default::default()
15012                    },
15013                    confirm: None,
15014                })
15015            })
15016            .collect();
15017
15018        Ok(result)
15019    })
15020}
15021
15022impl CompletionProvider for Entity<Project> {
15023    fn completions(
15024        &self,
15025        buffer: &Entity<Buffer>,
15026        buffer_position: text::Anchor,
15027        options: CompletionContext,
15028        _window: &mut Window,
15029        cx: &mut Context<Editor>,
15030    ) -> Task<Result<Vec<Completion>>> {
15031        self.update(cx, |project, cx| {
15032            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15033            let project_completions = project.completions(buffer, buffer_position, options, cx);
15034            cx.background_executor().spawn(async move {
15035                let mut completions = project_completions.await?;
15036                let snippets_completions = snippets.await?;
15037                completions.extend(snippets_completions);
15038                Ok(completions)
15039            })
15040        })
15041    }
15042
15043    fn resolve_completions(
15044        &self,
15045        buffer: Entity<Buffer>,
15046        completion_indices: Vec<usize>,
15047        completions: Rc<RefCell<Box<[Completion]>>>,
15048        cx: &mut Context<Editor>,
15049    ) -> Task<Result<bool>> {
15050        self.update(cx, |project, cx| {
15051            project.lsp_store().update(cx, |lsp_store, cx| {
15052                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15053            })
15054        })
15055    }
15056
15057    fn apply_additional_edits_for_completion(
15058        &self,
15059        buffer: Entity<Buffer>,
15060        completions: Rc<RefCell<Box<[Completion]>>>,
15061        completion_index: usize,
15062        push_to_history: bool,
15063        cx: &mut Context<Editor>,
15064    ) -> Task<Result<Option<language::Transaction>>> {
15065        self.update(cx, |project, cx| {
15066            project.lsp_store().update(cx, |lsp_store, cx| {
15067                lsp_store.apply_additional_edits_for_completion(
15068                    buffer,
15069                    completions,
15070                    completion_index,
15071                    push_to_history,
15072                    cx,
15073                )
15074            })
15075        })
15076    }
15077
15078    fn is_completion_trigger(
15079        &self,
15080        buffer: &Entity<Buffer>,
15081        position: language::Anchor,
15082        text: &str,
15083        trigger_in_words: bool,
15084        cx: &mut Context<Editor>,
15085    ) -> bool {
15086        let mut chars = text.chars();
15087        let char = if let Some(char) = chars.next() {
15088            char
15089        } else {
15090            return false;
15091        };
15092        if chars.next().is_some() {
15093            return false;
15094        }
15095
15096        let buffer = buffer.read(cx);
15097        let snapshot = buffer.snapshot();
15098        if !snapshot.settings_at(position, cx).show_completions_on_input {
15099            return false;
15100        }
15101        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15102        if trigger_in_words && classifier.is_word(char) {
15103            return true;
15104        }
15105
15106        buffer.completion_triggers().contains(text)
15107    }
15108}
15109
15110impl SemanticsProvider for Entity<Project> {
15111    fn hover(
15112        &self,
15113        buffer: &Entity<Buffer>,
15114        position: text::Anchor,
15115        cx: &mut App,
15116    ) -> Option<Task<Vec<project::Hover>>> {
15117        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15118    }
15119
15120    fn document_highlights(
15121        &self,
15122        buffer: &Entity<Buffer>,
15123        position: text::Anchor,
15124        cx: &mut App,
15125    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15126        Some(self.update(cx, |project, cx| {
15127            project.document_highlights(buffer, position, cx)
15128        }))
15129    }
15130
15131    fn definitions(
15132        &self,
15133        buffer: &Entity<Buffer>,
15134        position: text::Anchor,
15135        kind: GotoDefinitionKind,
15136        cx: &mut App,
15137    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15138        Some(self.update(cx, |project, cx| match kind {
15139            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15140            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15141            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15142            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15143        }))
15144    }
15145
15146    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15147        // TODO: make this work for remote projects
15148        self.read(cx)
15149            .language_servers_for_local_buffer(buffer.read(cx), cx)
15150            .any(
15151                |(_, server)| match server.capabilities().inlay_hint_provider {
15152                    Some(lsp::OneOf::Left(enabled)) => enabled,
15153                    Some(lsp::OneOf::Right(_)) => true,
15154                    None => false,
15155                },
15156            )
15157    }
15158
15159    fn inlay_hints(
15160        &self,
15161        buffer_handle: Entity<Buffer>,
15162        range: Range<text::Anchor>,
15163        cx: &mut App,
15164    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15165        Some(self.update(cx, |project, cx| {
15166            project.inlay_hints(buffer_handle, range, cx)
15167        }))
15168    }
15169
15170    fn resolve_inlay_hint(
15171        &self,
15172        hint: InlayHint,
15173        buffer_handle: Entity<Buffer>,
15174        server_id: LanguageServerId,
15175        cx: &mut App,
15176    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15177        Some(self.update(cx, |project, cx| {
15178            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15179        }))
15180    }
15181
15182    fn range_for_rename(
15183        &self,
15184        buffer: &Entity<Buffer>,
15185        position: text::Anchor,
15186        cx: &mut App,
15187    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15188        Some(self.update(cx, |project, cx| {
15189            let buffer = buffer.clone();
15190            let task = project.prepare_rename(buffer.clone(), position, cx);
15191            cx.spawn(|_, mut cx| async move {
15192                Ok(match task.await? {
15193                    PrepareRenameResponse::Success(range) => Some(range),
15194                    PrepareRenameResponse::InvalidPosition => None,
15195                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15196                        // Fallback on using TreeSitter info to determine identifier range
15197                        buffer.update(&mut cx, |buffer, _| {
15198                            let snapshot = buffer.snapshot();
15199                            let (range, kind) = snapshot.surrounding_word(position);
15200                            if kind != Some(CharKind::Word) {
15201                                return None;
15202                            }
15203                            Some(
15204                                snapshot.anchor_before(range.start)
15205                                    ..snapshot.anchor_after(range.end),
15206                            )
15207                        })?
15208                    }
15209                })
15210            })
15211        }))
15212    }
15213
15214    fn perform_rename(
15215        &self,
15216        buffer: &Entity<Buffer>,
15217        position: text::Anchor,
15218        new_name: String,
15219        cx: &mut App,
15220    ) -> Option<Task<Result<ProjectTransaction>>> {
15221        Some(self.update(cx, |project, cx| {
15222            project.perform_rename(buffer.clone(), position, new_name, cx)
15223        }))
15224    }
15225}
15226
15227fn inlay_hint_settings(
15228    location: Anchor,
15229    snapshot: &MultiBufferSnapshot,
15230    cx: &mut Context<Editor>,
15231) -> InlayHintSettings {
15232    let file = snapshot.file_at(location);
15233    let language = snapshot.language_at(location).map(|l| l.name());
15234    language_settings(language, file, cx).inlay_hints
15235}
15236
15237fn consume_contiguous_rows(
15238    contiguous_row_selections: &mut Vec<Selection<Point>>,
15239    selection: &Selection<Point>,
15240    display_map: &DisplaySnapshot,
15241    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15242) -> (MultiBufferRow, MultiBufferRow) {
15243    contiguous_row_selections.push(selection.clone());
15244    let start_row = MultiBufferRow(selection.start.row);
15245    let mut end_row = ending_row(selection, display_map);
15246
15247    while let Some(next_selection) = selections.peek() {
15248        if next_selection.start.row <= end_row.0 {
15249            end_row = ending_row(next_selection, display_map);
15250            contiguous_row_selections.push(selections.next().unwrap().clone());
15251        } else {
15252            break;
15253        }
15254    }
15255    (start_row, end_row)
15256}
15257
15258fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15259    if next_selection.end.column > 0 || next_selection.is_empty() {
15260        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15261    } else {
15262        MultiBufferRow(next_selection.end.row)
15263    }
15264}
15265
15266impl EditorSnapshot {
15267    pub fn remote_selections_in_range<'a>(
15268        &'a self,
15269        range: &'a Range<Anchor>,
15270        collaboration_hub: &dyn CollaborationHub,
15271        cx: &'a App,
15272    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15273        let participant_names = collaboration_hub.user_names(cx);
15274        let participant_indices = collaboration_hub.user_participant_indices(cx);
15275        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15276        let collaborators_by_replica_id = collaborators_by_peer_id
15277            .iter()
15278            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15279            .collect::<HashMap<_, _>>();
15280        self.buffer_snapshot
15281            .selections_in_range(range, false)
15282            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15283                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15284                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15285                let user_name = participant_names.get(&collaborator.user_id).cloned();
15286                Some(RemoteSelection {
15287                    replica_id,
15288                    selection,
15289                    cursor_shape,
15290                    line_mode,
15291                    participant_index,
15292                    peer_id: collaborator.peer_id,
15293                    user_name,
15294                })
15295            })
15296    }
15297
15298    pub fn hunks_for_ranges(
15299        &self,
15300        ranges: impl Iterator<Item = Range<Point>>,
15301    ) -> Vec<MultiBufferDiffHunk> {
15302        let mut hunks = Vec::new();
15303        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15304            HashMap::default();
15305        for query_range in ranges {
15306            let query_rows =
15307                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15308            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15309                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15310            ) {
15311                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15312                // when the caret is just above or just below the deleted hunk.
15313                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15314                let related_to_selection = if allow_adjacent {
15315                    hunk.row_range.overlaps(&query_rows)
15316                        || hunk.row_range.start == query_rows.end
15317                        || hunk.row_range.end == query_rows.start
15318                } else {
15319                    hunk.row_range.overlaps(&query_rows)
15320                };
15321                if related_to_selection {
15322                    if !processed_buffer_rows
15323                        .entry(hunk.buffer_id)
15324                        .or_default()
15325                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15326                    {
15327                        continue;
15328                    }
15329                    hunks.push(hunk);
15330                }
15331            }
15332        }
15333
15334        hunks
15335    }
15336
15337    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15338        self.display_snapshot.buffer_snapshot.language_at(position)
15339    }
15340
15341    pub fn is_focused(&self) -> bool {
15342        self.is_focused
15343    }
15344
15345    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15346        self.placeholder_text.as_ref()
15347    }
15348
15349    pub fn scroll_position(&self) -> gpui::Point<f32> {
15350        self.scroll_anchor.scroll_position(&self.display_snapshot)
15351    }
15352
15353    fn gutter_dimensions(
15354        &self,
15355        font_id: FontId,
15356        font_size: Pixels,
15357        max_line_number_width: Pixels,
15358        cx: &App,
15359    ) -> Option<GutterDimensions> {
15360        if !self.show_gutter {
15361            return None;
15362        }
15363
15364        let descent = cx.text_system().descent(font_id, font_size);
15365        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15366        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15367
15368        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15369            matches!(
15370                ProjectSettings::get_global(cx).git.git_gutter,
15371                Some(GitGutterSetting::TrackedFiles)
15372            )
15373        });
15374        let gutter_settings = EditorSettings::get_global(cx).gutter;
15375        let show_line_numbers = self
15376            .show_line_numbers
15377            .unwrap_or(gutter_settings.line_numbers);
15378        let line_gutter_width = if show_line_numbers {
15379            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15380            let min_width_for_number_on_gutter = em_advance * 4.0;
15381            max_line_number_width.max(min_width_for_number_on_gutter)
15382        } else {
15383            0.0.into()
15384        };
15385
15386        let show_code_actions = self
15387            .show_code_actions
15388            .unwrap_or(gutter_settings.code_actions);
15389
15390        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15391
15392        let git_blame_entries_width =
15393            self.git_blame_gutter_max_author_length
15394                .map(|max_author_length| {
15395                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15396
15397                    /// The number of characters to dedicate to gaps and margins.
15398                    const SPACING_WIDTH: usize = 4;
15399
15400                    let max_char_count = max_author_length
15401                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15402                        + ::git::SHORT_SHA_LENGTH
15403                        + MAX_RELATIVE_TIMESTAMP.len()
15404                        + SPACING_WIDTH;
15405
15406                    em_advance * max_char_count
15407                });
15408
15409        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15410        left_padding += if show_code_actions || show_runnables {
15411            em_width * 3.0
15412        } else if show_git_gutter && show_line_numbers {
15413            em_width * 2.0
15414        } else if show_git_gutter || show_line_numbers {
15415            em_width
15416        } else {
15417            px(0.)
15418        };
15419
15420        let right_padding = if gutter_settings.folds && show_line_numbers {
15421            em_width * 4.0
15422        } else if gutter_settings.folds {
15423            em_width * 3.0
15424        } else if show_line_numbers {
15425            em_width
15426        } else {
15427            px(0.)
15428        };
15429
15430        Some(GutterDimensions {
15431            left_padding,
15432            right_padding,
15433            width: line_gutter_width + left_padding + right_padding,
15434            margin: -descent,
15435            git_blame_entries_width,
15436        })
15437    }
15438
15439    pub fn render_crease_toggle(
15440        &self,
15441        buffer_row: MultiBufferRow,
15442        row_contains_cursor: bool,
15443        editor: Entity<Editor>,
15444        window: &mut Window,
15445        cx: &mut App,
15446    ) -> Option<AnyElement> {
15447        let folded = self.is_line_folded(buffer_row);
15448        let mut is_foldable = false;
15449
15450        if let Some(crease) = self
15451            .crease_snapshot
15452            .query_row(buffer_row, &self.buffer_snapshot)
15453        {
15454            is_foldable = true;
15455            match crease {
15456                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15457                    if let Some(render_toggle) = render_toggle {
15458                        let toggle_callback =
15459                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15460                                if folded {
15461                                    editor.update(cx, |editor, cx| {
15462                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15463                                    });
15464                                } else {
15465                                    editor.update(cx, |editor, cx| {
15466                                        editor.unfold_at(
15467                                            &crate::UnfoldAt { buffer_row },
15468                                            window,
15469                                            cx,
15470                                        )
15471                                    });
15472                                }
15473                            });
15474                        return Some((render_toggle)(
15475                            buffer_row,
15476                            folded,
15477                            toggle_callback,
15478                            window,
15479                            cx,
15480                        ));
15481                    }
15482                }
15483            }
15484        }
15485
15486        is_foldable |= self.starts_indent(buffer_row);
15487
15488        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15489            Some(
15490                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15491                    .toggle_state(folded)
15492                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15493                        if folded {
15494                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15495                        } else {
15496                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15497                        }
15498                    }))
15499                    .into_any_element(),
15500            )
15501        } else {
15502            None
15503        }
15504    }
15505
15506    pub fn render_crease_trailer(
15507        &self,
15508        buffer_row: MultiBufferRow,
15509        window: &mut Window,
15510        cx: &mut App,
15511    ) -> Option<AnyElement> {
15512        let folded = self.is_line_folded(buffer_row);
15513        if let Crease::Inline { render_trailer, .. } = self
15514            .crease_snapshot
15515            .query_row(buffer_row, &self.buffer_snapshot)?
15516        {
15517            let render_trailer = render_trailer.as_ref()?;
15518            Some(render_trailer(buffer_row, folded, window, cx))
15519        } else {
15520            None
15521        }
15522    }
15523}
15524
15525impl Deref for EditorSnapshot {
15526    type Target = DisplaySnapshot;
15527
15528    fn deref(&self) -> &Self::Target {
15529        &self.display_snapshot
15530    }
15531}
15532
15533#[derive(Clone, Debug, PartialEq, Eq)]
15534pub enum EditorEvent {
15535    InputIgnored {
15536        text: Arc<str>,
15537    },
15538    InputHandled {
15539        utf16_range_to_replace: Option<Range<isize>>,
15540        text: Arc<str>,
15541    },
15542    ExcerptsAdded {
15543        buffer: Entity<Buffer>,
15544        predecessor: ExcerptId,
15545        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15546    },
15547    ExcerptsRemoved {
15548        ids: Vec<ExcerptId>,
15549    },
15550    BufferFoldToggled {
15551        ids: Vec<ExcerptId>,
15552        folded: bool,
15553    },
15554    ExcerptsEdited {
15555        ids: Vec<ExcerptId>,
15556    },
15557    ExcerptsExpanded {
15558        ids: Vec<ExcerptId>,
15559    },
15560    BufferEdited,
15561    Edited {
15562        transaction_id: clock::Lamport,
15563    },
15564    Reparsed(BufferId),
15565    Focused,
15566    FocusedIn,
15567    Blurred,
15568    DirtyChanged,
15569    Saved,
15570    TitleChanged,
15571    DiffBaseChanged,
15572    SelectionsChanged {
15573        local: bool,
15574    },
15575    ScrollPositionChanged {
15576        local: bool,
15577        autoscroll: bool,
15578    },
15579    Closed,
15580    TransactionUndone {
15581        transaction_id: clock::Lamport,
15582    },
15583    TransactionBegun {
15584        transaction_id: clock::Lamport,
15585    },
15586    Reloaded,
15587    CursorShapeChanged,
15588}
15589
15590impl EventEmitter<EditorEvent> for Editor {}
15591
15592impl Focusable for Editor {
15593    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15594        self.focus_handle.clone()
15595    }
15596}
15597
15598impl Render for Editor {
15599    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15600        let settings = ThemeSettings::get_global(cx);
15601
15602        let mut text_style = match self.mode {
15603            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15604                color: cx.theme().colors().editor_foreground,
15605                font_family: settings.ui_font.family.clone(),
15606                font_features: settings.ui_font.features.clone(),
15607                font_fallbacks: settings.ui_font.fallbacks.clone(),
15608                font_size: rems(0.875).into(),
15609                font_weight: settings.ui_font.weight,
15610                line_height: relative(settings.buffer_line_height.value()),
15611                ..Default::default()
15612            },
15613            EditorMode::Full => TextStyle {
15614                color: cx.theme().colors().editor_foreground,
15615                font_family: settings.buffer_font.family.clone(),
15616                font_features: settings.buffer_font.features.clone(),
15617                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15618                font_size: settings.buffer_font_size().into(),
15619                font_weight: settings.buffer_font.weight,
15620                line_height: relative(settings.buffer_line_height.value()),
15621                ..Default::default()
15622            },
15623        };
15624        if let Some(text_style_refinement) = &self.text_style_refinement {
15625            text_style.refine(text_style_refinement)
15626        }
15627
15628        let background = match self.mode {
15629            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15630            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15631            EditorMode::Full => cx.theme().colors().editor_background,
15632        };
15633
15634        EditorElement::new(
15635            &cx.entity(),
15636            EditorStyle {
15637                background,
15638                local_player: cx.theme().players().local(),
15639                text: text_style,
15640                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15641                syntax: cx.theme().syntax().clone(),
15642                status: cx.theme().status().clone(),
15643                inlay_hints_style: make_inlay_hints_style(cx),
15644                inline_completion_styles: make_suggestion_styles(cx),
15645                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15646            },
15647        )
15648    }
15649}
15650
15651impl EntityInputHandler for Editor {
15652    fn text_for_range(
15653        &mut self,
15654        range_utf16: Range<usize>,
15655        adjusted_range: &mut Option<Range<usize>>,
15656        _: &mut Window,
15657        cx: &mut Context<Self>,
15658    ) -> Option<String> {
15659        let snapshot = self.buffer.read(cx).read(cx);
15660        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15661        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15662        if (start.0..end.0) != range_utf16 {
15663            adjusted_range.replace(start.0..end.0);
15664        }
15665        Some(snapshot.text_for_range(start..end).collect())
15666    }
15667
15668    fn selected_text_range(
15669        &mut self,
15670        ignore_disabled_input: bool,
15671        _: &mut Window,
15672        cx: &mut Context<Self>,
15673    ) -> Option<UTF16Selection> {
15674        // Prevent the IME menu from appearing when holding down an alphabetic key
15675        // while input is disabled.
15676        if !ignore_disabled_input && !self.input_enabled {
15677            return None;
15678        }
15679
15680        let selection = self.selections.newest::<OffsetUtf16>(cx);
15681        let range = selection.range();
15682
15683        Some(UTF16Selection {
15684            range: range.start.0..range.end.0,
15685            reversed: selection.reversed,
15686        })
15687    }
15688
15689    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15690        let snapshot = self.buffer.read(cx).read(cx);
15691        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15692        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15693    }
15694
15695    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15696        self.clear_highlights::<InputComposition>(cx);
15697        self.ime_transaction.take();
15698    }
15699
15700    fn replace_text_in_range(
15701        &mut self,
15702        range_utf16: Option<Range<usize>>,
15703        text: &str,
15704        window: &mut Window,
15705        cx: &mut Context<Self>,
15706    ) {
15707        if !self.input_enabled {
15708            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15709            return;
15710        }
15711
15712        self.transact(window, cx, |this, window, cx| {
15713            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15714                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15715                Some(this.selection_replacement_ranges(range_utf16, cx))
15716            } else {
15717                this.marked_text_ranges(cx)
15718            };
15719
15720            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15721                let newest_selection_id = this.selections.newest_anchor().id;
15722                this.selections
15723                    .all::<OffsetUtf16>(cx)
15724                    .iter()
15725                    .zip(ranges_to_replace.iter())
15726                    .find_map(|(selection, range)| {
15727                        if selection.id == newest_selection_id {
15728                            Some(
15729                                (range.start.0 as isize - selection.head().0 as isize)
15730                                    ..(range.end.0 as isize - selection.head().0 as isize),
15731                            )
15732                        } else {
15733                            None
15734                        }
15735                    })
15736            });
15737
15738            cx.emit(EditorEvent::InputHandled {
15739                utf16_range_to_replace: range_to_replace,
15740                text: text.into(),
15741            });
15742
15743            if let Some(new_selected_ranges) = new_selected_ranges {
15744                this.change_selections(None, window, cx, |selections| {
15745                    selections.select_ranges(new_selected_ranges)
15746                });
15747                this.backspace(&Default::default(), window, cx);
15748            }
15749
15750            this.handle_input(text, window, cx);
15751        });
15752
15753        if let Some(transaction) = self.ime_transaction {
15754            self.buffer.update(cx, |buffer, cx| {
15755                buffer.group_until_transaction(transaction, cx);
15756            });
15757        }
15758
15759        self.unmark_text(window, cx);
15760    }
15761
15762    fn replace_and_mark_text_in_range(
15763        &mut self,
15764        range_utf16: Option<Range<usize>>,
15765        text: &str,
15766        new_selected_range_utf16: Option<Range<usize>>,
15767        window: &mut Window,
15768        cx: &mut Context<Self>,
15769    ) {
15770        if !self.input_enabled {
15771            return;
15772        }
15773
15774        let transaction = self.transact(window, cx, |this, window, cx| {
15775            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15776                let snapshot = this.buffer.read(cx).read(cx);
15777                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15778                    for marked_range in &mut marked_ranges {
15779                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15780                        marked_range.start.0 += relative_range_utf16.start;
15781                        marked_range.start =
15782                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15783                        marked_range.end =
15784                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15785                    }
15786                }
15787                Some(marked_ranges)
15788            } else if let Some(range_utf16) = range_utf16 {
15789                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15790                Some(this.selection_replacement_ranges(range_utf16, cx))
15791            } else {
15792                None
15793            };
15794
15795            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15796                let newest_selection_id = this.selections.newest_anchor().id;
15797                this.selections
15798                    .all::<OffsetUtf16>(cx)
15799                    .iter()
15800                    .zip(ranges_to_replace.iter())
15801                    .find_map(|(selection, range)| {
15802                        if selection.id == newest_selection_id {
15803                            Some(
15804                                (range.start.0 as isize - selection.head().0 as isize)
15805                                    ..(range.end.0 as isize - selection.head().0 as isize),
15806                            )
15807                        } else {
15808                            None
15809                        }
15810                    })
15811            });
15812
15813            cx.emit(EditorEvent::InputHandled {
15814                utf16_range_to_replace: range_to_replace,
15815                text: text.into(),
15816            });
15817
15818            if let Some(ranges) = ranges_to_replace {
15819                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15820            }
15821
15822            let marked_ranges = {
15823                let snapshot = this.buffer.read(cx).read(cx);
15824                this.selections
15825                    .disjoint_anchors()
15826                    .iter()
15827                    .map(|selection| {
15828                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15829                    })
15830                    .collect::<Vec<_>>()
15831            };
15832
15833            if text.is_empty() {
15834                this.unmark_text(window, cx);
15835            } else {
15836                this.highlight_text::<InputComposition>(
15837                    marked_ranges.clone(),
15838                    HighlightStyle {
15839                        underline: Some(UnderlineStyle {
15840                            thickness: px(1.),
15841                            color: None,
15842                            wavy: false,
15843                        }),
15844                        ..Default::default()
15845                    },
15846                    cx,
15847                );
15848            }
15849
15850            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15851            let use_autoclose = this.use_autoclose;
15852            let use_auto_surround = this.use_auto_surround;
15853            this.set_use_autoclose(false);
15854            this.set_use_auto_surround(false);
15855            this.handle_input(text, window, cx);
15856            this.set_use_autoclose(use_autoclose);
15857            this.set_use_auto_surround(use_auto_surround);
15858
15859            if let Some(new_selected_range) = new_selected_range_utf16 {
15860                let snapshot = this.buffer.read(cx).read(cx);
15861                let new_selected_ranges = marked_ranges
15862                    .into_iter()
15863                    .map(|marked_range| {
15864                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15865                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15866                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15867                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15868                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15869                    })
15870                    .collect::<Vec<_>>();
15871
15872                drop(snapshot);
15873                this.change_selections(None, window, cx, |selections| {
15874                    selections.select_ranges(new_selected_ranges)
15875                });
15876            }
15877        });
15878
15879        self.ime_transaction = self.ime_transaction.or(transaction);
15880        if let Some(transaction) = self.ime_transaction {
15881            self.buffer.update(cx, |buffer, cx| {
15882                buffer.group_until_transaction(transaction, cx);
15883            });
15884        }
15885
15886        if self.text_highlights::<InputComposition>(cx).is_none() {
15887            self.ime_transaction.take();
15888        }
15889    }
15890
15891    fn bounds_for_range(
15892        &mut self,
15893        range_utf16: Range<usize>,
15894        element_bounds: gpui::Bounds<Pixels>,
15895        window: &mut Window,
15896        cx: &mut Context<Self>,
15897    ) -> Option<gpui::Bounds<Pixels>> {
15898        let text_layout_details = self.text_layout_details(window);
15899        let gpui::Point {
15900            x: em_width,
15901            y: line_height,
15902        } = self.character_size(window);
15903
15904        let snapshot = self.snapshot(window, cx);
15905        let scroll_position = snapshot.scroll_position();
15906        let scroll_left = scroll_position.x * em_width;
15907
15908        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15909        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15910            + self.gutter_dimensions.width
15911            + self.gutter_dimensions.margin;
15912        let y = line_height * (start.row().as_f32() - scroll_position.y);
15913
15914        Some(Bounds {
15915            origin: element_bounds.origin + point(x, y),
15916            size: size(em_width, line_height),
15917        })
15918    }
15919}
15920
15921trait SelectionExt {
15922    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15923    fn spanned_rows(
15924        &self,
15925        include_end_if_at_line_start: bool,
15926        map: &DisplaySnapshot,
15927    ) -> Range<MultiBufferRow>;
15928}
15929
15930impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15931    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15932        let start = self
15933            .start
15934            .to_point(&map.buffer_snapshot)
15935            .to_display_point(map);
15936        let end = self
15937            .end
15938            .to_point(&map.buffer_snapshot)
15939            .to_display_point(map);
15940        if self.reversed {
15941            end..start
15942        } else {
15943            start..end
15944        }
15945    }
15946
15947    fn spanned_rows(
15948        &self,
15949        include_end_if_at_line_start: bool,
15950        map: &DisplaySnapshot,
15951    ) -> Range<MultiBufferRow> {
15952        let start = self.start.to_point(&map.buffer_snapshot);
15953        let mut end = self.end.to_point(&map.buffer_snapshot);
15954        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15955            end.row -= 1;
15956        }
15957
15958        let buffer_start = map.prev_line_boundary(start).0;
15959        let buffer_end = map.next_line_boundary(end).0;
15960        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15961    }
15962}
15963
15964impl<T: InvalidationRegion> InvalidationStack<T> {
15965    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15966    where
15967        S: Clone + ToOffset,
15968    {
15969        while let Some(region) = self.last() {
15970            let all_selections_inside_invalidation_ranges =
15971                if selections.len() == region.ranges().len() {
15972                    selections
15973                        .iter()
15974                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15975                        .all(|(selection, invalidation_range)| {
15976                            let head = selection.head().to_offset(buffer);
15977                            invalidation_range.start <= head && invalidation_range.end >= head
15978                        })
15979                } else {
15980                    false
15981                };
15982
15983            if all_selections_inside_invalidation_ranges {
15984                break;
15985            } else {
15986                self.pop();
15987            }
15988        }
15989    }
15990}
15991
15992impl<T> Default for InvalidationStack<T> {
15993    fn default() -> Self {
15994        Self(Default::default())
15995    }
15996}
15997
15998impl<T> Deref for InvalidationStack<T> {
15999    type Target = Vec<T>;
16000
16001    fn deref(&self) -> &Self::Target {
16002        &self.0
16003    }
16004}
16005
16006impl<T> DerefMut for InvalidationStack<T> {
16007    fn deref_mut(&mut self) -> &mut Self::Target {
16008        &mut self.0
16009    }
16010}
16011
16012impl InvalidationRegion for SnippetState {
16013    fn ranges(&self) -> &[Range<Anchor>] {
16014        &self.ranges[self.active_index]
16015    }
16016}
16017
16018pub fn diagnostic_block_renderer(
16019    diagnostic: Diagnostic,
16020    max_message_rows: Option<u8>,
16021    allow_closing: bool,
16022    _is_valid: bool,
16023) -> RenderBlock {
16024    let (text_without_backticks, code_ranges) =
16025        highlight_diagnostic_message(&diagnostic, max_message_rows);
16026
16027    Arc::new(move |cx: &mut BlockContext| {
16028        let group_id: SharedString = cx.block_id.to_string().into();
16029
16030        let mut text_style = cx.window.text_style().clone();
16031        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16032        let theme_settings = ThemeSettings::get_global(cx);
16033        text_style.font_family = theme_settings.buffer_font.family.clone();
16034        text_style.font_style = theme_settings.buffer_font.style;
16035        text_style.font_features = theme_settings.buffer_font.features.clone();
16036        text_style.font_weight = theme_settings.buffer_font.weight;
16037
16038        let multi_line_diagnostic = diagnostic.message.contains('\n');
16039
16040        let buttons = |diagnostic: &Diagnostic| {
16041            if multi_line_diagnostic {
16042                v_flex()
16043            } else {
16044                h_flex()
16045            }
16046            .when(allow_closing, |div| {
16047                div.children(diagnostic.is_primary.then(|| {
16048                    IconButton::new("close-block", IconName::XCircle)
16049                        .icon_color(Color::Muted)
16050                        .size(ButtonSize::Compact)
16051                        .style(ButtonStyle::Transparent)
16052                        .visible_on_hover(group_id.clone())
16053                        .on_click(move |_click, window, cx| {
16054                            window.dispatch_action(Box::new(Cancel), cx)
16055                        })
16056                        .tooltip(|window, cx| {
16057                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16058                        })
16059                }))
16060            })
16061            .child(
16062                IconButton::new("copy-block", IconName::Copy)
16063                    .icon_color(Color::Muted)
16064                    .size(ButtonSize::Compact)
16065                    .style(ButtonStyle::Transparent)
16066                    .visible_on_hover(group_id.clone())
16067                    .on_click({
16068                        let message = diagnostic.message.clone();
16069                        move |_click, _, cx| {
16070                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16071                        }
16072                    })
16073                    .tooltip(Tooltip::text("Copy diagnostic message")),
16074            )
16075        };
16076
16077        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16078            AvailableSpace::min_size(),
16079            cx.window,
16080            cx.app,
16081        );
16082
16083        h_flex()
16084            .id(cx.block_id)
16085            .group(group_id.clone())
16086            .relative()
16087            .size_full()
16088            .block_mouse_down()
16089            .pl(cx.gutter_dimensions.width)
16090            .w(cx.max_width - cx.gutter_dimensions.full_width())
16091            .child(
16092                div()
16093                    .flex()
16094                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16095                    .flex_shrink(),
16096            )
16097            .child(buttons(&diagnostic))
16098            .child(div().flex().flex_shrink_0().child(
16099                StyledText::new(text_without_backticks.clone()).with_highlights(
16100                    &text_style,
16101                    code_ranges.iter().map(|range| {
16102                        (
16103                            range.clone(),
16104                            HighlightStyle {
16105                                font_weight: Some(FontWeight::BOLD),
16106                                ..Default::default()
16107                            },
16108                        )
16109                    }),
16110                ),
16111            ))
16112            .into_any_element()
16113    })
16114}
16115
16116fn inline_completion_edit_text(
16117    current_snapshot: &BufferSnapshot,
16118    edits: &[(Range<Anchor>, String)],
16119    edit_preview: &EditPreview,
16120    include_deletions: bool,
16121    cx: &App,
16122) -> HighlightedText {
16123    let edits = edits
16124        .iter()
16125        .map(|(anchor, text)| {
16126            (
16127                anchor.start.text_anchor..anchor.end.text_anchor,
16128                text.clone(),
16129            )
16130        })
16131        .collect::<Vec<_>>();
16132
16133    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16134}
16135
16136pub fn highlight_diagnostic_message(
16137    diagnostic: &Diagnostic,
16138    mut max_message_rows: Option<u8>,
16139) -> (SharedString, Vec<Range<usize>>) {
16140    let mut text_without_backticks = String::new();
16141    let mut code_ranges = Vec::new();
16142
16143    if let Some(source) = &diagnostic.source {
16144        text_without_backticks.push_str(source);
16145        code_ranges.push(0..source.len());
16146        text_without_backticks.push_str(": ");
16147    }
16148
16149    let mut prev_offset = 0;
16150    let mut in_code_block = false;
16151    let has_row_limit = max_message_rows.is_some();
16152    let mut newline_indices = diagnostic
16153        .message
16154        .match_indices('\n')
16155        .filter(|_| has_row_limit)
16156        .map(|(ix, _)| ix)
16157        .fuse()
16158        .peekable();
16159
16160    for (quote_ix, _) in diagnostic
16161        .message
16162        .match_indices('`')
16163        .chain([(diagnostic.message.len(), "")])
16164    {
16165        let mut first_newline_ix = None;
16166        let mut last_newline_ix = None;
16167        while let Some(newline_ix) = newline_indices.peek() {
16168            if *newline_ix < quote_ix {
16169                if first_newline_ix.is_none() {
16170                    first_newline_ix = Some(*newline_ix);
16171                }
16172                last_newline_ix = Some(*newline_ix);
16173
16174                if let Some(rows_left) = &mut max_message_rows {
16175                    if *rows_left == 0 {
16176                        break;
16177                    } else {
16178                        *rows_left -= 1;
16179                    }
16180                }
16181                let _ = newline_indices.next();
16182            } else {
16183                break;
16184            }
16185        }
16186        let prev_len = text_without_backticks.len();
16187        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16188        text_without_backticks.push_str(new_text);
16189        if in_code_block {
16190            code_ranges.push(prev_len..text_without_backticks.len());
16191        }
16192        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16193        in_code_block = !in_code_block;
16194        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16195            text_without_backticks.push_str("...");
16196            break;
16197        }
16198    }
16199
16200    (text_without_backticks.into(), code_ranges)
16201}
16202
16203fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16204    match severity {
16205        DiagnosticSeverity::ERROR => colors.error,
16206        DiagnosticSeverity::WARNING => colors.warning,
16207        DiagnosticSeverity::INFORMATION => colors.info,
16208        DiagnosticSeverity::HINT => colors.info,
16209        _ => colors.ignored,
16210    }
16211}
16212
16213pub fn styled_runs_for_code_label<'a>(
16214    label: &'a CodeLabel,
16215    syntax_theme: &'a theme::SyntaxTheme,
16216) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16217    let fade_out = HighlightStyle {
16218        fade_out: Some(0.35),
16219        ..Default::default()
16220    };
16221
16222    let mut prev_end = label.filter_range.end;
16223    label
16224        .runs
16225        .iter()
16226        .enumerate()
16227        .flat_map(move |(ix, (range, highlight_id))| {
16228            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16229                style
16230            } else {
16231                return Default::default();
16232            };
16233            let mut muted_style = style;
16234            muted_style.highlight(fade_out);
16235
16236            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16237            if range.start >= label.filter_range.end {
16238                if range.start > prev_end {
16239                    runs.push((prev_end..range.start, fade_out));
16240                }
16241                runs.push((range.clone(), muted_style));
16242            } else if range.end <= label.filter_range.end {
16243                runs.push((range.clone(), style));
16244            } else {
16245                runs.push((range.start..label.filter_range.end, style));
16246                runs.push((label.filter_range.end..range.end, muted_style));
16247            }
16248            prev_end = cmp::max(prev_end, range.end);
16249
16250            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16251                runs.push((prev_end..label.text.len(), fade_out));
16252            }
16253
16254            runs
16255        })
16256}
16257
16258pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16259    let mut prev_index = 0;
16260    let mut prev_codepoint: Option<char> = None;
16261    text.char_indices()
16262        .chain([(text.len(), '\0')])
16263        .filter_map(move |(index, codepoint)| {
16264            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16265            let is_boundary = index == text.len()
16266                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16267                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16268            if is_boundary {
16269                let chunk = &text[prev_index..index];
16270                prev_index = index;
16271                Some(chunk)
16272            } else {
16273                None
16274            }
16275        })
16276}
16277
16278pub trait RangeToAnchorExt: Sized {
16279    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16280
16281    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16282        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16283        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16284    }
16285}
16286
16287impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16288    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16289        let start_offset = self.start.to_offset(snapshot);
16290        let end_offset = self.end.to_offset(snapshot);
16291        if start_offset == end_offset {
16292            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16293        } else {
16294            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16295        }
16296    }
16297}
16298
16299pub trait RowExt {
16300    fn as_f32(&self) -> f32;
16301
16302    fn next_row(&self) -> Self;
16303
16304    fn previous_row(&self) -> Self;
16305
16306    fn minus(&self, other: Self) -> u32;
16307}
16308
16309impl RowExt for DisplayRow {
16310    fn as_f32(&self) -> f32 {
16311        self.0 as f32
16312    }
16313
16314    fn next_row(&self) -> Self {
16315        Self(self.0 + 1)
16316    }
16317
16318    fn previous_row(&self) -> Self {
16319        Self(self.0.saturating_sub(1))
16320    }
16321
16322    fn minus(&self, other: Self) -> u32 {
16323        self.0 - other.0
16324    }
16325}
16326
16327impl RowExt for MultiBufferRow {
16328    fn as_f32(&self) -> f32 {
16329        self.0 as f32
16330    }
16331
16332    fn next_row(&self) -> Self {
16333        Self(self.0 + 1)
16334    }
16335
16336    fn previous_row(&self) -> Self {
16337        Self(self.0.saturating_sub(1))
16338    }
16339
16340    fn minus(&self, other: Self) -> u32 {
16341        self.0 - other.0
16342    }
16343}
16344
16345trait RowRangeExt {
16346    type Row;
16347
16348    fn len(&self) -> usize;
16349
16350    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16351}
16352
16353impl RowRangeExt for Range<MultiBufferRow> {
16354    type Row = MultiBufferRow;
16355
16356    fn len(&self) -> usize {
16357        (self.end.0 - self.start.0) as usize
16358    }
16359
16360    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16361        (self.start.0..self.end.0).map(MultiBufferRow)
16362    }
16363}
16364
16365impl RowRangeExt for Range<DisplayRow> {
16366    type Row = DisplayRow;
16367
16368    fn len(&self) -> usize {
16369        (self.end.0 - self.start.0) as usize
16370    }
16371
16372    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16373        (self.start.0..self.end.0).map(DisplayRow)
16374    }
16375}
16376
16377/// If select range has more than one line, we
16378/// just point the cursor to range.start.
16379fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16380    if range.start.row == range.end.row {
16381        range
16382    } else {
16383        range.start..range.start
16384    }
16385}
16386pub struct KillRing(ClipboardItem);
16387impl Global for KillRing {}
16388
16389const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16390
16391fn all_edits_insertions_or_deletions(
16392    edits: &Vec<(Range<Anchor>, String)>,
16393    snapshot: &MultiBufferSnapshot,
16394) -> bool {
16395    let mut all_insertions = true;
16396    let mut all_deletions = true;
16397
16398    for (range, new_text) in edits.iter() {
16399        let range_is_empty = range.to_offset(&snapshot).is_empty();
16400        let text_is_empty = new_text.is_empty();
16401
16402        if range_is_empty != text_is_empty {
16403            if range_is_empty {
16404                all_deletions = false;
16405            } else {
16406                all_insertions = false;
16407            }
16408        } else {
16409            return false;
16410        }
16411
16412        if !all_insertions && !all_deletions {
16413            return false;
16414        }
16415    }
16416    all_insertions || all_deletions
16417}