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