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;
   72use zed_predict_onboarding::ZedPredictModal;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, App,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
   83    Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CursorShape, Diagnostic, Documentation, EditPreview, HighlightedEdits, IndentKind, IndentSize,
  100    Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId,
  101    TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  128};
  129use project::{
  130    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  131    project_settings::{GitGutterSetting, ProjectSettings},
  132    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  133    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  134};
  135use rand::prelude::*;
  136use rpc::{proto::*, ErrorExt};
  137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  138use selections_collection::{
  139    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  140};
  141use serde::{Deserialize, Serialize};
  142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  143use smallvec::SmallVec;
  144use snippet::Snippet;
  145use std::{
  146    any::TypeId,
  147    borrow::Cow,
  148    cell::RefCell,
  149    cmp::{self, Ordering, Reverse},
  150    mem,
  151    num::NonZeroU32,
  152    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  153    path::{Path, PathBuf},
  154    rc::Rc,
  155    sync::Arc,
  156    time::{Duration, Instant},
  157};
  158pub use sum_tree::Bias;
  159use sum_tree::TreeMap;
  160use text::{BufferId, OffsetUtf16, Rope};
  161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  162use ui::{
  163    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  164    Tooltip,
  165};
  166use util::{defer, maybe, post_inc, RangeExt, ResultExt, 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                    Editor::new_file(workspace, &Default::default(), window, cx)
  336                },
  337            )
  338            .detach();
  339        }
  340    });
  341    git::project_diff::init(cx);
  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
  468#[derive(Debug, Clone)]
  469enum InlineCompletionMenuHint {
  470    Loading,
  471    Loaded { text: InlineCompletionText },
  472    PendingTermsAcceptance,
  473    None,
  474}
  475
  476impl InlineCompletionMenuHint {
  477    pub fn label(&self) -> &'static str {
  478        match self {
  479            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  480                "Edit Prediction"
  481            }
  482            InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
  483            InlineCompletionMenuHint::None => "No Prediction",
  484        }
  485    }
  486}
  487
  488#[derive(Clone, Debug)]
  489enum InlineCompletionText {
  490    Move(SharedString),
  491    Edit(HighlightedEdits),
  492}
  493
  494pub(crate) enum EditDisplayMode {
  495    TabAccept,
  496    DiffPopover,
  497    Inline,
  498}
  499
  500enum InlineCompletion {
  501    Edit {
  502        edits: Vec<(Range<Anchor>, String)>,
  503        edit_preview: Option<EditPreview>,
  504        display_mode: EditDisplayMode,
  505        snapshot: BufferSnapshot,
  506    },
  507    Move(Anchor),
  508}
  509
  510struct InlineCompletionState {
  511    inlay_ids: Vec<InlayId>,
  512    completion: InlineCompletion,
  513    invalidation_range: Range<Anchor>,
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  524struct EditorActionId(usize);
  525
  526impl EditorActionId {
  527    pub fn post_inc(&mut self) -> Self {
  528        let answer = self.0;
  529
  530        *self = Self(answer + 1);
  531
  532        Self(answer)
  533    }
  534}
  535
  536// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  537// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  538
  539type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  540type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  541
  542#[derive(Default)]
  543struct ScrollbarMarkerState {
  544    scrollbar_size: Size<Pixels>,
  545    dirty: bool,
  546    markers: Arc<[PaintQuad]>,
  547    pending_refresh: Option<Task<Result<()>>>,
  548}
  549
  550impl ScrollbarMarkerState {
  551    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  552        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  553    }
  554}
  555
  556#[derive(Clone, Debug)]
  557struct RunnableTasks {
  558    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  559    offset: MultiBufferOffset,
  560    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  561    column: u32,
  562    // Values of all named captures, including those starting with '_'
  563    extra_variables: HashMap<String, String>,
  564    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  565    context_range: Range<BufferOffset>,
  566}
  567
  568impl RunnableTasks {
  569    fn resolve<'a>(
  570        &'a self,
  571        cx: &'a task::TaskContext,
  572    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  573        self.templates.iter().filter_map(|(kind, template)| {
  574            template
  575                .resolve_task(&kind.to_id_base(), cx)
  576                .map(|task| (kind.clone(), task))
  577        })
  578    }
  579}
  580
  581#[derive(Clone)]
  582struct ResolvedTasks {
  583    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  584    position: Anchor,
  585}
  586#[derive(Copy, Clone, Debug)]
  587struct MultiBufferOffset(usize);
  588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  589struct BufferOffset(usize);
  590
  591// Addons allow storing per-editor state in other crates (e.g. Vim)
  592pub trait Addon: 'static {
  593    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  594
  595    fn to_any(&self) -> &dyn std::any::Any;
  596}
  597
  598#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  599pub enum IsVimMode {
  600    Yes,
  601    No,
  602}
  603
  604/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  605///
  606/// See the [module level documentation](self) for more information.
  607pub struct Editor {
  608    focus_handle: FocusHandle,
  609    last_focused_descendant: Option<WeakFocusHandle>,
  610    /// The text buffer being edited
  611    buffer: Entity<MultiBuffer>,
  612    /// Map of how text in the buffer should be displayed.
  613    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  614    pub display_map: Entity<DisplayMap>,
  615    pub selections: SelectionsCollection,
  616    pub scroll_manager: ScrollManager,
  617    /// When inline assist editors are linked, they all render cursors because
  618    /// typing enters text into each of them, even the ones that aren't focused.
  619    pub(crate) show_cursor_when_unfocused: bool,
  620    columnar_selection_tail: Option<Anchor>,
  621    add_selections_state: Option<AddSelectionsState>,
  622    select_next_state: Option<SelectNextState>,
  623    select_prev_state: Option<SelectNextState>,
  624    selection_history: SelectionHistory,
  625    autoclose_regions: Vec<AutocloseRegion>,
  626    snippet_stack: InvalidationStack<SnippetState>,
  627    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  628    ime_transaction: Option<TransactionId>,
  629    active_diagnostics: Option<ActiveDiagnosticGroup>,
  630    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  631
  632    project: Option<Entity<Project>>,
  633    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  634    completion_provider: Option<Box<dyn CompletionProvider>>,
  635    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  636    blink_manager: Entity<BlinkManager>,
  637    show_cursor_names: bool,
  638    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  639    pub show_local_selections: bool,
  640    mode: EditorMode,
  641    show_breadcrumbs: bool,
  642    show_gutter: bool,
  643    show_scrollbars: bool,
  644    show_line_numbers: Option<bool>,
  645    use_relative_line_numbers: Option<bool>,
  646    show_git_diff_gutter: Option<bool>,
  647    show_code_actions: Option<bool>,
  648    show_runnables: Option<bool>,
  649    show_wrap_guides: Option<bool>,
  650    show_indent_guides: Option<bool>,
  651    placeholder_text: Option<Arc<str>>,
  652    highlight_order: usize,
  653    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  654    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  655    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  656    scrollbar_marker_state: ScrollbarMarkerState,
  657    active_indent_guides_state: ActiveIndentGuidesState,
  658    nav_history: Option<ItemNavHistory>,
  659    context_menu: RefCell<Option<CodeContextMenu>>,
  660    mouse_context_menu: Option<MouseContextMenu>,
  661    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  662    signature_help_state: SignatureHelpState,
  663    auto_signature_help: Option<bool>,
  664    find_all_references_task_sources: Vec<Anchor>,
  665    next_completion_id: CompletionId,
  666    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  667    code_actions_task: Option<Task<Result<()>>>,
  668    document_highlights_task: Option<Task<()>>,
  669    linked_editing_range_task: Option<Task<Option<()>>>,
  670    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  671    pending_rename: Option<RenameState>,
  672    searchable: bool,
  673    cursor_shape: CursorShape,
  674    current_line_highlight: Option<CurrentLineHighlight>,
  675    collapse_matches: bool,
  676    autoindent_mode: Option<AutoindentMode>,
  677    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  678    input_enabled: bool,
  679    use_modal_editing: bool,
  680    read_only: bool,
  681    leader_peer_id: Option<PeerId>,
  682    remote_id: Option<ViewId>,
  683    hover_state: HoverState,
  684    gutter_hovered: bool,
  685    hovered_link_state: Option<HoveredLinkState>,
  686    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  687    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  688    active_inline_completion: Option<InlineCompletionState>,
  689    // enable_inline_completions is a switch that Vim can use to disable
  690    // inline completions based on its mode.
  691    enable_inline_completions: bool,
  692    show_inline_completions_override: Option<bool>,
  693    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  694    inlay_hint_cache: InlayHintCache,
  695    next_inlay_id: usize,
  696    _subscriptions: Vec<Subscription>,
  697    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  698    gutter_dimensions: GutterDimensions,
  699    style: Option<EditorStyle>,
  700    text_style_refinement: Option<TextStyleRefinement>,
  701    next_editor_action_id: EditorActionId,
  702    editor_actions:
  703        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  704    use_autoclose: bool,
  705    use_auto_surround: bool,
  706    auto_replace_emoji_shortcode: bool,
  707    show_git_blame_gutter: bool,
  708    show_git_blame_inline: bool,
  709    show_git_blame_inline_delay_task: Option<Task<()>>,
  710    git_blame_inline_enabled: bool,
  711    serialize_dirty_buffers: bool,
  712    show_selection_menu: Option<bool>,
  713    blame: Option<Entity<GitBlame>>,
  714    blame_subscription: Option<Subscription>,
  715    custom_context_menu: Option<
  716        Box<
  717            dyn 'static
  718                + Fn(
  719                    &mut Self,
  720                    DisplayPoint,
  721                    &mut Window,
  722                    &mut Context<Self>,
  723                ) -> Option<Entity<ui::ContextMenu>>,
  724        >,
  725    >,
  726    last_bounds: Option<Bounds<Pixels>>,
  727    expect_bounds_change: Option<Bounds<Pixels>>,
  728    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  729    tasks_update_task: Option<Task<()>>,
  730    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  731    breadcrumb_header: Option<String>,
  732    focused_block: Option<FocusedBlock>,
  733    next_scroll_position: NextScrollCursorCenterTopBottom,
  734    addons: HashMap<TypeId, Box<dyn Addon>>,
  735    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  736    selection_mark_mode: bool,
  737    toggle_fold_multiple_buffers: Task<()>,
  738    _scroll_cursor_center_top_bottom_task: Task<()>,
  739}
  740
  741#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  742enum NextScrollCursorCenterTopBottom {
  743    #[default]
  744    Center,
  745    Top,
  746    Bottom,
  747}
  748
  749impl NextScrollCursorCenterTopBottom {
  750    fn next(&self) -> Self {
  751        match self {
  752            Self::Center => Self::Top,
  753            Self::Top => Self::Bottom,
  754            Self::Bottom => Self::Center,
  755        }
  756    }
  757}
  758
  759#[derive(Clone)]
  760pub struct EditorSnapshot {
  761    pub mode: EditorMode,
  762    show_gutter: bool,
  763    show_line_numbers: Option<bool>,
  764    show_git_diff_gutter: Option<bool>,
  765    show_code_actions: Option<bool>,
  766    show_runnables: Option<bool>,
  767    git_blame_gutter_max_author_length: Option<usize>,
  768    pub display_snapshot: DisplaySnapshot,
  769    pub placeholder_text: Option<Arc<str>>,
  770    is_focused: bool,
  771    scroll_anchor: ScrollAnchor,
  772    ongoing_scroll: OngoingScroll,
  773    current_line_highlight: CurrentLineHighlight,
  774    gutter_hovered: bool,
  775}
  776
  777const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  778
  779#[derive(Default, Debug, Clone, Copy)]
  780pub struct GutterDimensions {
  781    pub left_padding: Pixels,
  782    pub right_padding: Pixels,
  783    pub width: Pixels,
  784    pub margin: Pixels,
  785    pub git_blame_entries_width: Option<Pixels>,
  786}
  787
  788impl GutterDimensions {
  789    /// The full width of the space taken up by the gutter.
  790    pub fn full_width(&self) -> Pixels {
  791        self.margin + self.width
  792    }
  793
  794    /// The width of the space reserved for the fold indicators,
  795    /// use alongside 'justify_end' and `gutter_width` to
  796    /// right align content with the line numbers
  797    pub fn fold_area_width(&self) -> Pixels {
  798        self.margin + self.right_padding
  799    }
  800}
  801
  802#[derive(Debug)]
  803pub struct RemoteSelection {
  804    pub replica_id: ReplicaId,
  805    pub selection: Selection<Anchor>,
  806    pub cursor_shape: CursorShape,
  807    pub peer_id: PeerId,
  808    pub line_mode: bool,
  809    pub participant_index: Option<ParticipantIndex>,
  810    pub user_name: Option<SharedString>,
  811}
  812
  813#[derive(Clone, Debug)]
  814struct SelectionHistoryEntry {
  815    selections: Arc<[Selection<Anchor>]>,
  816    select_next_state: Option<SelectNextState>,
  817    select_prev_state: Option<SelectNextState>,
  818    add_selections_state: Option<AddSelectionsState>,
  819}
  820
  821enum SelectionHistoryMode {
  822    Normal,
  823    Undoing,
  824    Redoing,
  825}
  826
  827#[derive(Clone, PartialEq, Eq, Hash)]
  828struct HoveredCursor {
  829    replica_id: u16,
  830    selection_id: usize,
  831}
  832
  833impl Default for SelectionHistoryMode {
  834    fn default() -> Self {
  835        Self::Normal
  836    }
  837}
  838
  839#[derive(Default)]
  840struct SelectionHistory {
  841    #[allow(clippy::type_complexity)]
  842    selections_by_transaction:
  843        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  844    mode: SelectionHistoryMode,
  845    undo_stack: VecDeque<SelectionHistoryEntry>,
  846    redo_stack: VecDeque<SelectionHistoryEntry>,
  847}
  848
  849impl SelectionHistory {
  850    fn insert_transaction(
  851        &mut self,
  852        transaction_id: TransactionId,
  853        selections: Arc<[Selection<Anchor>]>,
  854    ) {
  855        self.selections_by_transaction
  856            .insert(transaction_id, (selections, None));
  857    }
  858
  859    #[allow(clippy::type_complexity)]
  860    fn transaction(
  861        &self,
  862        transaction_id: TransactionId,
  863    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  864        self.selections_by_transaction.get(&transaction_id)
  865    }
  866
  867    #[allow(clippy::type_complexity)]
  868    fn transaction_mut(
  869        &mut self,
  870        transaction_id: TransactionId,
  871    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  872        self.selections_by_transaction.get_mut(&transaction_id)
  873    }
  874
  875    fn push(&mut self, entry: SelectionHistoryEntry) {
  876        if !entry.selections.is_empty() {
  877            match self.mode {
  878                SelectionHistoryMode::Normal => {
  879                    self.push_undo(entry);
  880                    self.redo_stack.clear();
  881                }
  882                SelectionHistoryMode::Undoing => self.push_redo(entry),
  883                SelectionHistoryMode::Redoing => self.push_undo(entry),
  884            }
  885        }
  886    }
  887
  888    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  889        if self
  890            .undo_stack
  891            .back()
  892            .map_or(true, |e| e.selections != entry.selections)
  893        {
  894            self.undo_stack.push_back(entry);
  895            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  896                self.undo_stack.pop_front();
  897            }
  898        }
  899    }
  900
  901    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  902        if self
  903            .redo_stack
  904            .back()
  905            .map_or(true, |e| e.selections != entry.selections)
  906        {
  907            self.redo_stack.push_back(entry);
  908            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  909                self.redo_stack.pop_front();
  910            }
  911        }
  912    }
  913}
  914
  915struct RowHighlight {
  916    index: usize,
  917    range: Range<Anchor>,
  918    color: Hsla,
  919    should_autoscroll: bool,
  920}
  921
  922#[derive(Clone, Debug)]
  923struct AddSelectionsState {
  924    above: bool,
  925    stack: Vec<usize>,
  926}
  927
  928#[derive(Clone)]
  929struct SelectNextState {
  930    query: AhoCorasick,
  931    wordwise: bool,
  932    done: bool,
  933}
  934
  935impl std::fmt::Debug for SelectNextState {
  936    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  937        f.debug_struct(std::any::type_name::<Self>())
  938            .field("wordwise", &self.wordwise)
  939            .field("done", &self.done)
  940            .finish()
  941    }
  942}
  943
  944#[derive(Debug)]
  945struct AutocloseRegion {
  946    selection_id: usize,
  947    range: Range<Anchor>,
  948    pair: BracketPair,
  949}
  950
  951#[derive(Debug)]
  952struct SnippetState {
  953    ranges: Vec<Vec<Range<Anchor>>>,
  954    active_index: usize,
  955    choices: Vec<Option<Vec<String>>>,
  956}
  957
  958#[doc(hidden)]
  959pub struct RenameState {
  960    pub range: Range<Anchor>,
  961    pub old_name: Arc<str>,
  962    pub editor: Entity<Editor>,
  963    block_id: CustomBlockId,
  964}
  965
  966struct InvalidationStack<T>(Vec<T>);
  967
  968struct RegisteredInlineCompletionProvider {
  969    provider: Arc<dyn InlineCompletionProviderHandle>,
  970    _subscription: Subscription,
  971}
  972
  973#[derive(Debug)]
  974struct ActiveDiagnosticGroup {
  975    primary_range: Range<Anchor>,
  976    primary_message: String,
  977    group_id: usize,
  978    blocks: HashMap<CustomBlockId, Diagnostic>,
  979    is_valid: bool,
  980}
  981
  982#[derive(Serialize, Deserialize, Clone, Debug)]
  983pub struct ClipboardSelection {
  984    pub len: usize,
  985    pub is_entire_line: bool,
  986    pub first_line_indent: u32,
  987}
  988
  989#[derive(Debug)]
  990pub(crate) struct NavigationData {
  991    cursor_anchor: Anchor,
  992    cursor_position: Point,
  993    scroll_anchor: ScrollAnchor,
  994    scroll_top_row: u32,
  995}
  996
  997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  998pub enum GotoDefinitionKind {
  999    Symbol,
 1000    Declaration,
 1001    Type,
 1002    Implementation,
 1003}
 1004
 1005#[derive(Debug, Clone)]
 1006enum InlayHintRefreshReason {
 1007    Toggle(bool),
 1008    SettingsChange(InlayHintSettings),
 1009    NewLinesShown,
 1010    BufferEdited(HashSet<Arc<Language>>),
 1011    RefreshRequested,
 1012    ExcerptsRemoved(Vec<ExcerptId>),
 1013}
 1014
 1015impl InlayHintRefreshReason {
 1016    fn description(&self) -> &'static str {
 1017        match self {
 1018            Self::Toggle(_) => "toggle",
 1019            Self::SettingsChange(_) => "settings change",
 1020            Self::NewLinesShown => "new lines shown",
 1021            Self::BufferEdited(_) => "buffer edited",
 1022            Self::RefreshRequested => "refresh requested",
 1023            Self::ExcerptsRemoved(_) => "excerpts removed",
 1024        }
 1025    }
 1026}
 1027
 1028pub enum FormatTarget {
 1029    Buffers,
 1030    Ranges(Vec<Range<MultiBufferPoint>>),
 1031}
 1032
 1033pub(crate) struct FocusedBlock {
 1034    id: BlockId,
 1035    focus_handle: WeakFocusHandle,
 1036}
 1037
 1038#[derive(Clone)]
 1039enum JumpData {
 1040    MultiBufferRow {
 1041        row: MultiBufferRow,
 1042        line_offset_from_top: u32,
 1043    },
 1044    MultiBufferPoint {
 1045        excerpt_id: ExcerptId,
 1046        position: Point,
 1047        anchor: text::Anchor,
 1048        line_offset_from_top: u32,
 1049    },
 1050}
 1051
 1052pub enum MultibufferSelectionMode {
 1053    First,
 1054    All,
 1055}
 1056
 1057impl Editor {
 1058    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1059        let buffer = cx.new(|cx| Buffer::local("", cx));
 1060        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1061        Self::new(
 1062            EditorMode::SingleLine { auto_width: false },
 1063            buffer,
 1064            None,
 1065            false,
 1066            window,
 1067            cx,
 1068        )
 1069    }
 1070
 1071    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1072        let buffer = cx.new(|cx| Buffer::local("", cx));
 1073        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1075    }
 1076
 1077    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1078        let buffer = cx.new(|cx| Buffer::local("", cx));
 1079        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1080        Self::new(
 1081            EditorMode::SingleLine { auto_width: true },
 1082            buffer,
 1083            None,
 1084            false,
 1085            window,
 1086            cx,
 1087        )
 1088    }
 1089
 1090    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1091        let buffer = cx.new(|cx| Buffer::local("", cx));
 1092        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1093        Self::new(
 1094            EditorMode::AutoHeight { max_lines },
 1095            buffer,
 1096            None,
 1097            false,
 1098            window,
 1099            cx,
 1100        )
 1101    }
 1102
 1103    pub fn for_buffer(
 1104        buffer: Entity<Buffer>,
 1105        project: Option<Entity<Project>>,
 1106        window: &mut Window,
 1107        cx: &mut Context<Self>,
 1108    ) -> Self {
 1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1110        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1111    }
 1112
 1113    pub fn for_multibuffer(
 1114        buffer: Entity<MultiBuffer>,
 1115        project: Option<Entity<Project>>,
 1116        show_excerpt_controls: bool,
 1117        window: &mut Window,
 1118        cx: &mut Context<Self>,
 1119    ) -> Self {
 1120        Self::new(
 1121            EditorMode::Full,
 1122            buffer,
 1123            project,
 1124            show_excerpt_controls,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1131        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1132        let mut clone = Self::new(
 1133            self.mode,
 1134            self.buffer.clone(),
 1135            self.project.clone(),
 1136            show_excerpt_controls,
 1137            window,
 1138            cx,
 1139        );
 1140        self.display_map.update(cx, |display_map, cx| {
 1141            let snapshot = display_map.snapshot(cx);
 1142            clone.display_map.update(cx, |display_map, cx| {
 1143                display_map.set_state(&snapshot, cx);
 1144            });
 1145        });
 1146        clone.selections.clone_state(&self.selections);
 1147        clone.scroll_manager.clone_state(&self.scroll_manager);
 1148        clone.searchable = self.searchable;
 1149        clone
 1150    }
 1151
 1152    pub fn new(
 1153        mode: EditorMode,
 1154        buffer: Entity<MultiBuffer>,
 1155        project: Option<Entity<Project>>,
 1156        show_excerpt_controls: bool,
 1157        window: &mut Window,
 1158        cx: &mut Context<Self>,
 1159    ) -> Self {
 1160        let style = window.text_style();
 1161        let font_size = style.font_size.to_pixels(window.rem_size());
 1162        let editor = cx.entity().downgrade();
 1163        let fold_placeholder = FoldPlaceholder {
 1164            constrain_width: true,
 1165            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1166                let editor = editor.clone();
 1167                div()
 1168                    .id(fold_id)
 1169                    .bg(cx.theme().colors().ghost_element_background)
 1170                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1171                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1172                    .rounded_sm()
 1173                    .size_full()
 1174                    .cursor_pointer()
 1175                    .child("")
 1176                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1177                    .on_click(move |_, _window, cx| {
 1178                        editor
 1179                            .update(cx, |editor, cx| {
 1180                                editor.unfold_ranges(
 1181                                    &[fold_range.start..fold_range.end],
 1182                                    true,
 1183                                    false,
 1184                                    cx,
 1185                                );
 1186                                cx.stop_propagation();
 1187                            })
 1188                            .ok();
 1189                    })
 1190                    .into_any()
 1191            }),
 1192            merge_adjacent: true,
 1193            ..Default::default()
 1194        };
 1195        let display_map = cx.new(|cx| {
 1196            DisplayMap::new(
 1197                buffer.clone(),
 1198                style.font(),
 1199                font_size,
 1200                None,
 1201                show_excerpt_controls,
 1202                FILE_HEADER_HEIGHT,
 1203                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1204                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1205                fold_placeholder,
 1206                cx,
 1207            )
 1208        });
 1209
 1210        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1211
 1212        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1213
 1214        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1215            .then(|| language_settings::SoftWrap::None);
 1216
 1217        let mut project_subscriptions = Vec::new();
 1218        if mode == EditorMode::Full {
 1219            if let Some(project) = project.as_ref() {
 1220                if buffer.read(cx).is_singleton() {
 1221                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1222                        cx.emit(EditorEvent::TitleChanged);
 1223                    }));
 1224                }
 1225                project_subscriptions.push(cx.subscribe_in(
 1226                    project,
 1227                    window,
 1228                    |editor, _, event, window, cx| {
 1229                        if let project::Event::RefreshInlayHints = event {
 1230                            editor
 1231                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1232                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1233                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1234                                let focus_handle = editor.focus_handle(cx);
 1235                                if focus_handle.is_focused(window) {
 1236                                    let snapshot = buffer.read(cx).snapshot();
 1237                                    for (range, snippet) in snippet_edits {
 1238                                        let editor_range =
 1239                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1240                                        editor
 1241                                            .insert_snippet(
 1242                                                &[editor_range],
 1243                                                snippet.clone(),
 1244                                                window,
 1245                                                cx,
 1246                                            )
 1247                                            .ok();
 1248                                    }
 1249                                }
 1250                            }
 1251                        }
 1252                    },
 1253                ));
 1254                if let Some(task_inventory) = project
 1255                    .read(cx)
 1256                    .task_store()
 1257                    .read(cx)
 1258                    .task_inventory()
 1259                    .cloned()
 1260                {
 1261                    project_subscriptions.push(cx.observe_in(
 1262                        &task_inventory,
 1263                        window,
 1264                        |editor, _, window, cx| {
 1265                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1266                        },
 1267                    ));
 1268                }
 1269            }
 1270        }
 1271
 1272        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1273
 1274        let inlay_hint_settings =
 1275            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1276        let focus_handle = cx.focus_handle();
 1277        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1278            .detach();
 1279        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1280            .detach();
 1281        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1282            .detach();
 1283        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1284            .detach();
 1285
 1286        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1287            Some(false)
 1288        } else {
 1289            None
 1290        };
 1291
 1292        let mut code_action_providers = Vec::new();
 1293        if let Some(project) = project.clone() {
 1294            get_unstaged_changes_for_buffers(
 1295                &project,
 1296                buffer.read(cx).all_buffers(),
 1297                buffer.clone(),
 1298                cx,
 1299            );
 1300            code_action_providers.push(Rc::new(project) as Rc<_>);
 1301        }
 1302
 1303        let mut this = Self {
 1304            focus_handle,
 1305            show_cursor_when_unfocused: false,
 1306            last_focused_descendant: None,
 1307            buffer: buffer.clone(),
 1308            display_map: display_map.clone(),
 1309            selections,
 1310            scroll_manager: ScrollManager::new(cx),
 1311            columnar_selection_tail: None,
 1312            add_selections_state: None,
 1313            select_next_state: None,
 1314            select_prev_state: None,
 1315            selection_history: Default::default(),
 1316            autoclose_regions: Default::default(),
 1317            snippet_stack: Default::default(),
 1318            select_larger_syntax_node_stack: Vec::new(),
 1319            ime_transaction: Default::default(),
 1320            active_diagnostics: None,
 1321            soft_wrap_mode_override,
 1322            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1323            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1324            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1325            project,
 1326            blink_manager: blink_manager.clone(),
 1327            show_local_selections: true,
 1328            show_scrollbars: true,
 1329            mode,
 1330            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1331            show_gutter: mode == EditorMode::Full,
 1332            show_line_numbers: None,
 1333            use_relative_line_numbers: None,
 1334            show_git_diff_gutter: None,
 1335            show_code_actions: None,
 1336            show_runnables: None,
 1337            show_wrap_guides: None,
 1338            show_indent_guides,
 1339            placeholder_text: None,
 1340            highlight_order: 0,
 1341            highlighted_rows: HashMap::default(),
 1342            background_highlights: Default::default(),
 1343            gutter_highlights: TreeMap::default(),
 1344            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1345            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1346            nav_history: None,
 1347            context_menu: RefCell::new(None),
 1348            mouse_context_menu: None,
 1349            completion_tasks: Default::default(),
 1350            signature_help_state: SignatureHelpState::default(),
 1351            auto_signature_help: None,
 1352            find_all_references_task_sources: Vec::new(),
 1353            next_completion_id: 0,
 1354            next_inlay_id: 0,
 1355            code_action_providers,
 1356            available_code_actions: Default::default(),
 1357            code_actions_task: Default::default(),
 1358            document_highlights_task: Default::default(),
 1359            linked_editing_range_task: Default::default(),
 1360            pending_rename: Default::default(),
 1361            searchable: true,
 1362            cursor_shape: EditorSettings::get_global(cx)
 1363                .cursor_shape
 1364                .unwrap_or_default(),
 1365            current_line_highlight: None,
 1366            autoindent_mode: Some(AutoindentMode::EachLine),
 1367            collapse_matches: false,
 1368            workspace: None,
 1369            input_enabled: true,
 1370            use_modal_editing: mode == EditorMode::Full,
 1371            read_only: false,
 1372            use_autoclose: true,
 1373            use_auto_surround: true,
 1374            auto_replace_emoji_shortcode: false,
 1375            leader_peer_id: None,
 1376            remote_id: None,
 1377            hover_state: Default::default(),
 1378            hovered_link_state: Default::default(),
 1379            inline_completion_provider: None,
 1380            active_inline_completion: None,
 1381            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1382
 1383            gutter_hovered: false,
 1384            pixel_position_of_newest_cursor: None,
 1385            last_bounds: None,
 1386            expect_bounds_change: None,
 1387            gutter_dimensions: GutterDimensions::default(),
 1388            style: None,
 1389            show_cursor_names: false,
 1390            hovered_cursors: Default::default(),
 1391            next_editor_action_id: EditorActionId::default(),
 1392            editor_actions: Rc::default(),
 1393            show_inline_completions_override: None,
 1394            enable_inline_completions: true,
 1395            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1396            custom_context_menu: None,
 1397            show_git_blame_gutter: false,
 1398            show_git_blame_inline: false,
 1399            show_selection_menu: None,
 1400            show_git_blame_inline_delay_task: None,
 1401            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1402            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1403                .session
 1404                .restore_unsaved_buffers,
 1405            blame: None,
 1406            blame_subscription: None,
 1407            tasks: Default::default(),
 1408            _subscriptions: vec![
 1409                cx.observe(&buffer, Self::on_buffer_changed),
 1410                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1411                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1412                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1413                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1414                cx.observe_window_activation(window, |editor, window, cx| {
 1415                    let active = window.is_window_active();
 1416                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1417                        if active {
 1418                            blink_manager.enable(cx);
 1419                        } else {
 1420                            blink_manager.disable(cx);
 1421                        }
 1422                    });
 1423                }),
 1424            ],
 1425            tasks_update_task: None,
 1426            linked_edit_ranges: Default::default(),
 1427            previous_search_ranges: None,
 1428            breadcrumb_header: None,
 1429            focused_block: None,
 1430            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1431            addons: HashMap::default(),
 1432            registered_buffers: HashMap::default(),
 1433            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1434            selection_mark_mode: false,
 1435            toggle_fold_multiple_buffers: Task::ready(()),
 1436            text_style_refinement: None,
 1437        };
 1438        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1439        this._subscriptions.extend(project_subscriptions);
 1440
 1441        this.end_selection(window, cx);
 1442        this.scroll_manager.show_scrollbar(window, cx);
 1443
 1444        if mode == EditorMode::Full {
 1445            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1446            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1447
 1448            if this.git_blame_inline_enabled {
 1449                this.git_blame_inline_enabled = true;
 1450                this.start_git_blame_inline(false, window, cx);
 1451            }
 1452
 1453            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1454                if let Some(project) = this.project.as_ref() {
 1455                    let lsp_store = project.read(cx).lsp_store();
 1456                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1457                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1458                    });
 1459                    this.registered_buffers
 1460                        .insert(buffer.read(cx).remote_id(), handle);
 1461                }
 1462            }
 1463        }
 1464
 1465        this.report_editor_event("Editor Opened", None, cx);
 1466        this
 1467    }
 1468
 1469    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1470        self.mouse_context_menu
 1471            .as_ref()
 1472            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1473    }
 1474
 1475    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1476        let mut key_context = KeyContext::new_with_defaults();
 1477        key_context.add("Editor");
 1478        let mode = match self.mode {
 1479            EditorMode::SingleLine { .. } => "single_line",
 1480            EditorMode::AutoHeight { .. } => "auto_height",
 1481            EditorMode::Full => "full",
 1482        };
 1483
 1484        if EditorSettings::jupyter_enabled(cx) {
 1485            key_context.add("jupyter");
 1486        }
 1487
 1488        key_context.set("mode", mode);
 1489        if self.pending_rename.is_some() {
 1490            key_context.add("renaming");
 1491        }
 1492        match self.context_menu.borrow().as_ref() {
 1493            Some(CodeContextMenu::Completions(_)) => {
 1494                key_context.add("menu");
 1495                key_context.add("showing_completions")
 1496            }
 1497            Some(CodeContextMenu::CodeActions(_)) => {
 1498                key_context.add("menu");
 1499                key_context.add("showing_code_actions")
 1500            }
 1501            None => {}
 1502        }
 1503
 1504        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1505        if !self.focus_handle(cx).contains_focused(window, cx)
 1506            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1507        {
 1508            for addon in self.addons.values() {
 1509                addon.extend_key_context(&mut key_context, cx)
 1510            }
 1511        }
 1512
 1513        if let Some(extension) = self
 1514            .buffer
 1515            .read(cx)
 1516            .as_singleton()
 1517            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1518        {
 1519            key_context.set("extension", extension.to_string());
 1520        }
 1521
 1522        if self.has_active_inline_completion() {
 1523            key_context.add("copilot_suggestion");
 1524            key_context.add("inline_completion");
 1525        }
 1526
 1527        if self.selection_mark_mode {
 1528            key_context.add("selection_mode");
 1529        }
 1530
 1531        key_context
 1532    }
 1533
 1534    pub fn new_file(
 1535        workspace: &mut Workspace,
 1536        _: &workspace::NewFile,
 1537        window: &mut Window,
 1538        cx: &mut Context<Workspace>,
 1539    ) {
 1540        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1541            "Failed to create buffer",
 1542            window,
 1543            cx,
 1544            |e, _, _| match e.error_code() {
 1545                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1546                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1547                e.error_tag("required").unwrap_or("the latest version")
 1548            )),
 1549                _ => None,
 1550            },
 1551        );
 1552    }
 1553
 1554    pub fn new_in_workspace(
 1555        workspace: &mut Workspace,
 1556        window: &mut Window,
 1557        cx: &mut Context<Workspace>,
 1558    ) -> Task<Result<Entity<Editor>>> {
 1559        let project = workspace.project().clone();
 1560        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1561
 1562        cx.spawn_in(window, |workspace, mut cx| async move {
 1563            let buffer = create.await?;
 1564            workspace.update_in(&mut cx, |workspace, window, cx| {
 1565                let editor =
 1566                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1567                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1568                editor
 1569            })
 1570        })
 1571    }
 1572
 1573    fn new_file_vertical(
 1574        workspace: &mut Workspace,
 1575        _: &workspace::NewFileSplitVertical,
 1576        window: &mut Window,
 1577        cx: &mut Context<Workspace>,
 1578    ) {
 1579        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1580    }
 1581
 1582    fn new_file_horizontal(
 1583        workspace: &mut Workspace,
 1584        _: &workspace::NewFileSplitHorizontal,
 1585        window: &mut Window,
 1586        cx: &mut Context<Workspace>,
 1587    ) {
 1588        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1589    }
 1590
 1591    fn new_file_in_direction(
 1592        workspace: &mut Workspace,
 1593        direction: SplitDirection,
 1594        window: &mut Window,
 1595        cx: &mut Context<Workspace>,
 1596    ) {
 1597        let project = workspace.project().clone();
 1598        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1599
 1600        cx.spawn_in(window, |workspace, mut cx| async move {
 1601            let buffer = create.await?;
 1602            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1603                workspace.split_item(
 1604                    direction,
 1605                    Box::new(
 1606                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1607                    ),
 1608                    window,
 1609                    cx,
 1610                )
 1611            })?;
 1612            anyhow::Ok(())
 1613        })
 1614        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1615            match e.error_code() {
 1616                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1617                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1618                e.error_tag("required").unwrap_or("the latest version")
 1619            )),
 1620                _ => None,
 1621            }
 1622        });
 1623    }
 1624
 1625    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1626        self.leader_peer_id
 1627    }
 1628
 1629    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1630        &self.buffer
 1631    }
 1632
 1633    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1634        self.workspace.as_ref()?.0.upgrade()
 1635    }
 1636
 1637    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1638        self.buffer().read(cx).title(cx)
 1639    }
 1640
 1641    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1642        let git_blame_gutter_max_author_length = self
 1643            .render_git_blame_gutter(cx)
 1644            .then(|| {
 1645                if let Some(blame) = self.blame.as_ref() {
 1646                    let max_author_length =
 1647                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1648                    Some(max_author_length)
 1649                } else {
 1650                    None
 1651                }
 1652            })
 1653            .flatten();
 1654
 1655        EditorSnapshot {
 1656            mode: self.mode,
 1657            show_gutter: self.show_gutter,
 1658            show_line_numbers: self.show_line_numbers,
 1659            show_git_diff_gutter: self.show_git_diff_gutter,
 1660            show_code_actions: self.show_code_actions,
 1661            show_runnables: self.show_runnables,
 1662            git_blame_gutter_max_author_length,
 1663            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1664            scroll_anchor: self.scroll_manager.anchor(),
 1665            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1666            placeholder_text: self.placeholder_text.clone(),
 1667            is_focused: self.focus_handle.is_focused(window),
 1668            current_line_highlight: self
 1669                .current_line_highlight
 1670                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1671            gutter_hovered: self.gutter_hovered,
 1672        }
 1673    }
 1674
 1675    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1676        self.buffer.read(cx).language_at(point, cx)
 1677    }
 1678
 1679    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1680        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1681    }
 1682
 1683    pub fn active_excerpt(
 1684        &self,
 1685        cx: &App,
 1686    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1687        self.buffer
 1688            .read(cx)
 1689            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1690    }
 1691
 1692    pub fn mode(&self) -> EditorMode {
 1693        self.mode
 1694    }
 1695
 1696    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1697        self.collaboration_hub.as_deref()
 1698    }
 1699
 1700    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1701        self.collaboration_hub = Some(hub);
 1702    }
 1703
 1704    pub fn set_custom_context_menu(
 1705        &mut self,
 1706        f: impl 'static
 1707            + Fn(
 1708                &mut Self,
 1709                DisplayPoint,
 1710                &mut Window,
 1711                &mut Context<Self>,
 1712            ) -> Option<Entity<ui::ContextMenu>>,
 1713    ) {
 1714        self.custom_context_menu = Some(Box::new(f))
 1715    }
 1716
 1717    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1718        self.completion_provider = provider;
 1719    }
 1720
 1721    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1722        self.semantics_provider.clone()
 1723    }
 1724
 1725    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1726        self.semantics_provider = provider;
 1727    }
 1728
 1729    pub fn set_inline_completion_provider<T>(
 1730        &mut self,
 1731        provider: Option<Entity<T>>,
 1732        window: &mut Window,
 1733        cx: &mut Context<Self>,
 1734    ) where
 1735        T: InlineCompletionProvider,
 1736    {
 1737        self.inline_completion_provider =
 1738            provider.map(|provider| RegisteredInlineCompletionProvider {
 1739                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1740                    if this.focus_handle.is_focused(window) {
 1741                        this.update_visible_inline_completion(window, cx);
 1742                    }
 1743                }),
 1744                provider: Arc::new(provider),
 1745            });
 1746        self.refresh_inline_completion(false, false, window, cx);
 1747    }
 1748
 1749    pub fn placeholder_text(&self) -> Option<&str> {
 1750        self.placeholder_text.as_deref()
 1751    }
 1752
 1753    pub fn set_placeholder_text(
 1754        &mut self,
 1755        placeholder_text: impl Into<Arc<str>>,
 1756        cx: &mut Context<Self>,
 1757    ) {
 1758        let placeholder_text = Some(placeholder_text.into());
 1759        if self.placeholder_text != placeholder_text {
 1760            self.placeholder_text = placeholder_text;
 1761            cx.notify();
 1762        }
 1763    }
 1764
 1765    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1766        self.cursor_shape = cursor_shape;
 1767
 1768        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1769        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1770
 1771        cx.notify();
 1772    }
 1773
 1774    pub fn set_current_line_highlight(
 1775        &mut self,
 1776        current_line_highlight: Option<CurrentLineHighlight>,
 1777    ) {
 1778        self.current_line_highlight = current_line_highlight;
 1779    }
 1780
 1781    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1782        self.collapse_matches = collapse_matches;
 1783    }
 1784
 1785    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1786        let buffers = self.buffer.read(cx).all_buffers();
 1787        let Some(lsp_store) = self.lsp_store(cx) else {
 1788            return;
 1789        };
 1790        lsp_store.update(cx, |lsp_store, cx| {
 1791            for buffer in buffers {
 1792                self.registered_buffers
 1793                    .entry(buffer.read(cx).remote_id())
 1794                    .or_insert_with(|| {
 1795                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1796                    });
 1797            }
 1798        })
 1799    }
 1800
 1801    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1802        if self.collapse_matches {
 1803            return range.start..range.start;
 1804        }
 1805        range.clone()
 1806    }
 1807
 1808    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1809        if self.display_map.read(cx).clip_at_line_ends != clip {
 1810            self.display_map
 1811                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1812        }
 1813    }
 1814
 1815    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1816        self.input_enabled = input_enabled;
 1817    }
 1818
 1819    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1820        self.enable_inline_completions = enabled;
 1821        if !self.enable_inline_completions {
 1822            self.take_active_inline_completion(cx);
 1823            cx.notify();
 1824        }
 1825    }
 1826
 1827    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1828        self.menu_inline_completions_policy = value;
 1829    }
 1830
 1831    pub fn set_autoindent(&mut self, autoindent: bool) {
 1832        if autoindent {
 1833            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1834        } else {
 1835            self.autoindent_mode = None;
 1836        }
 1837    }
 1838
 1839    pub fn read_only(&self, cx: &App) -> bool {
 1840        self.read_only || self.buffer.read(cx).read_only()
 1841    }
 1842
 1843    pub fn set_read_only(&mut self, read_only: bool) {
 1844        self.read_only = read_only;
 1845    }
 1846
 1847    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1848        self.use_autoclose = autoclose;
 1849    }
 1850
 1851    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1852        self.use_auto_surround = auto_surround;
 1853    }
 1854
 1855    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1856        self.auto_replace_emoji_shortcode = auto_replace;
 1857    }
 1858
 1859    pub fn toggle_inline_completions(
 1860        &mut self,
 1861        _: &ToggleInlineCompletions,
 1862        window: &mut Window,
 1863        cx: &mut Context<Self>,
 1864    ) {
 1865        if self.show_inline_completions_override.is_some() {
 1866            self.set_show_inline_completions(None, window, cx);
 1867        } else {
 1868            let cursor = self.selections.newest_anchor().head();
 1869            if let Some((buffer, cursor_buffer_position)) =
 1870                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1871            {
 1872                let show_inline_completions =
 1873                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1874                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1875            }
 1876        }
 1877    }
 1878
 1879    pub fn set_show_inline_completions(
 1880        &mut self,
 1881        show_inline_completions: Option<bool>,
 1882        window: &mut Window,
 1883        cx: &mut Context<Self>,
 1884    ) {
 1885        self.show_inline_completions_override = show_inline_completions;
 1886        self.refresh_inline_completion(false, true, window, cx);
 1887    }
 1888
 1889    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1890        let cursor = self.selections.newest_anchor().head();
 1891        if let Some((buffer, buffer_position)) =
 1892            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1893        {
 1894            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1895        } else {
 1896            false
 1897        }
 1898    }
 1899
 1900    fn should_show_inline_completions(
 1901        &self,
 1902        buffer: &Entity<Buffer>,
 1903        buffer_position: language::Anchor,
 1904        cx: &App,
 1905    ) -> bool {
 1906        if !self.snippet_stack.is_empty() {
 1907            return false;
 1908        }
 1909
 1910        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1911            return false;
 1912        }
 1913
 1914        if let Some(provider) = self.inline_completion_provider() {
 1915            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1916                show_inline_completions
 1917            } else {
 1918                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1919            }
 1920        } else {
 1921            false
 1922        }
 1923    }
 1924
 1925    fn inline_completions_disabled_in_scope(
 1926        &self,
 1927        buffer: &Entity<Buffer>,
 1928        buffer_position: language::Anchor,
 1929        cx: &App,
 1930    ) -> bool {
 1931        let snapshot = buffer.read(cx).snapshot();
 1932        let settings = snapshot.settings_at(buffer_position, cx);
 1933
 1934        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1935            return false;
 1936        };
 1937
 1938        scope.override_name().map_or(false, |scope_name| {
 1939            settings
 1940                .inline_completions_disabled_in
 1941                .iter()
 1942                .any(|s| s == scope_name)
 1943        })
 1944    }
 1945
 1946    pub fn set_use_modal_editing(&mut self, to: bool) {
 1947        self.use_modal_editing = to;
 1948    }
 1949
 1950    pub fn use_modal_editing(&self) -> bool {
 1951        self.use_modal_editing
 1952    }
 1953
 1954    fn selections_did_change(
 1955        &mut self,
 1956        local: bool,
 1957        old_cursor_position: &Anchor,
 1958        show_completions: bool,
 1959        window: &mut Window,
 1960        cx: &mut Context<Self>,
 1961    ) {
 1962        window.invalidate_character_coordinates();
 1963
 1964        // Copy selections to primary selection buffer
 1965        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1966        if local {
 1967            let selections = self.selections.all::<usize>(cx);
 1968            let buffer_handle = self.buffer.read(cx).read(cx);
 1969
 1970            let mut text = String::new();
 1971            for (index, selection) in selections.iter().enumerate() {
 1972                let text_for_selection = buffer_handle
 1973                    .text_for_range(selection.start..selection.end)
 1974                    .collect::<String>();
 1975
 1976                text.push_str(&text_for_selection);
 1977                if index != selections.len() - 1 {
 1978                    text.push('\n');
 1979                }
 1980            }
 1981
 1982            if !text.is_empty() {
 1983                cx.write_to_primary(ClipboardItem::new_string(text));
 1984            }
 1985        }
 1986
 1987        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1988            self.buffer.update(cx, |buffer, cx| {
 1989                buffer.set_active_selections(
 1990                    &self.selections.disjoint_anchors(),
 1991                    self.selections.line_mode,
 1992                    self.cursor_shape,
 1993                    cx,
 1994                )
 1995            });
 1996        }
 1997        let display_map = self
 1998            .display_map
 1999            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2000        let buffer = &display_map.buffer_snapshot;
 2001        self.add_selections_state = None;
 2002        self.select_next_state = None;
 2003        self.select_prev_state = None;
 2004        self.select_larger_syntax_node_stack.clear();
 2005        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2006        self.snippet_stack
 2007            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2008        self.take_rename(false, window, cx);
 2009
 2010        let new_cursor_position = self.selections.newest_anchor().head();
 2011
 2012        self.push_to_nav_history(
 2013            *old_cursor_position,
 2014            Some(new_cursor_position.to_point(buffer)),
 2015            cx,
 2016        );
 2017
 2018        if local {
 2019            let new_cursor_position = self.selections.newest_anchor().head();
 2020            let mut context_menu = self.context_menu.borrow_mut();
 2021            let completion_menu = match context_menu.as_ref() {
 2022                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2023                _ => {
 2024                    *context_menu = None;
 2025                    None
 2026                }
 2027            };
 2028
 2029            if let Some(completion_menu) = completion_menu {
 2030                let cursor_position = new_cursor_position.to_offset(buffer);
 2031                let (word_range, kind) =
 2032                    buffer.surrounding_word(completion_menu.initial_position, true);
 2033                if kind == Some(CharKind::Word)
 2034                    && word_range.to_inclusive().contains(&cursor_position)
 2035                {
 2036                    let mut completion_menu = completion_menu.clone();
 2037                    drop(context_menu);
 2038
 2039                    let query = Self::completion_query(buffer, cursor_position);
 2040                    cx.spawn(move |this, mut cx| async move {
 2041                        completion_menu
 2042                            .filter(query.as_deref(), cx.background_executor().clone())
 2043                            .await;
 2044
 2045                        this.update(&mut cx, |this, cx| {
 2046                            let mut context_menu = this.context_menu.borrow_mut();
 2047                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2048                            else {
 2049                                return;
 2050                            };
 2051
 2052                            if menu.id > completion_menu.id {
 2053                                return;
 2054                            }
 2055
 2056                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2057                            drop(context_menu);
 2058                            cx.notify();
 2059                        })
 2060                    })
 2061                    .detach();
 2062
 2063                    if show_completions {
 2064                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2065                    }
 2066                } else {
 2067                    drop(context_menu);
 2068                    self.hide_context_menu(window, cx);
 2069                }
 2070            } else {
 2071                drop(context_menu);
 2072            }
 2073
 2074            hide_hover(self, cx);
 2075
 2076            if old_cursor_position.to_display_point(&display_map).row()
 2077                != new_cursor_position.to_display_point(&display_map).row()
 2078            {
 2079                self.available_code_actions.take();
 2080            }
 2081            self.refresh_code_actions(window, cx);
 2082            self.refresh_document_highlights(cx);
 2083            refresh_matching_bracket_highlights(self, window, cx);
 2084            self.update_visible_inline_completion(window, cx);
 2085            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2086            if self.git_blame_inline_enabled {
 2087                self.start_inline_blame_timer(window, cx);
 2088            }
 2089        }
 2090
 2091        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2092        cx.emit(EditorEvent::SelectionsChanged { local });
 2093
 2094        if self.selections.disjoint_anchors().len() == 1 {
 2095            cx.emit(SearchEvent::ActiveMatchChanged)
 2096        }
 2097        cx.notify();
 2098    }
 2099
 2100    pub fn change_selections<R>(
 2101        &mut self,
 2102        autoscroll: Option<Autoscroll>,
 2103        window: &mut Window,
 2104        cx: &mut Context<Self>,
 2105        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2106    ) -> R {
 2107        self.change_selections_inner(autoscroll, true, window, cx, change)
 2108    }
 2109
 2110    pub fn change_selections_inner<R>(
 2111        &mut self,
 2112        autoscroll: Option<Autoscroll>,
 2113        request_completions: bool,
 2114        window: &mut Window,
 2115        cx: &mut Context<Self>,
 2116        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2117    ) -> R {
 2118        let old_cursor_position = self.selections.newest_anchor().head();
 2119        self.push_to_selection_history();
 2120
 2121        let (changed, result) = self.selections.change_with(cx, change);
 2122
 2123        if changed {
 2124            if let Some(autoscroll) = autoscroll {
 2125                self.request_autoscroll(autoscroll, cx);
 2126            }
 2127            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2128
 2129            if self.should_open_signature_help_automatically(
 2130                &old_cursor_position,
 2131                self.signature_help_state.backspace_pressed(),
 2132                cx,
 2133            ) {
 2134                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2135            }
 2136            self.signature_help_state.set_backspace_pressed(false);
 2137        }
 2138
 2139        result
 2140    }
 2141
 2142    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2143    where
 2144        I: IntoIterator<Item = (Range<S>, T)>,
 2145        S: ToOffset,
 2146        T: Into<Arc<str>>,
 2147    {
 2148        if self.read_only(cx) {
 2149            return;
 2150        }
 2151
 2152        self.buffer
 2153            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2154    }
 2155
 2156    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2157    where
 2158        I: IntoIterator<Item = (Range<S>, T)>,
 2159        S: ToOffset,
 2160        T: Into<Arc<str>>,
 2161    {
 2162        if self.read_only(cx) {
 2163            return;
 2164        }
 2165
 2166        self.buffer.update(cx, |buffer, cx| {
 2167            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2168        });
 2169    }
 2170
 2171    pub fn edit_with_block_indent<I, S, T>(
 2172        &mut self,
 2173        edits: I,
 2174        original_indent_columns: Vec<u32>,
 2175        cx: &mut Context<Self>,
 2176    ) where
 2177        I: IntoIterator<Item = (Range<S>, T)>,
 2178        S: ToOffset,
 2179        T: Into<Arc<str>>,
 2180    {
 2181        if self.read_only(cx) {
 2182            return;
 2183        }
 2184
 2185        self.buffer.update(cx, |buffer, cx| {
 2186            buffer.edit(
 2187                edits,
 2188                Some(AutoindentMode::Block {
 2189                    original_indent_columns,
 2190                }),
 2191                cx,
 2192            )
 2193        });
 2194    }
 2195
 2196    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2197        self.hide_context_menu(window, cx);
 2198
 2199        match phase {
 2200            SelectPhase::Begin {
 2201                position,
 2202                add,
 2203                click_count,
 2204            } => self.begin_selection(position, add, click_count, window, cx),
 2205            SelectPhase::BeginColumnar {
 2206                position,
 2207                goal_column,
 2208                reset,
 2209            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2210            SelectPhase::Extend {
 2211                position,
 2212                click_count,
 2213            } => self.extend_selection(position, click_count, window, cx),
 2214            SelectPhase::Update {
 2215                position,
 2216                goal_column,
 2217                scroll_delta,
 2218            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2219            SelectPhase::End => self.end_selection(window, cx),
 2220        }
 2221    }
 2222
 2223    fn extend_selection(
 2224        &mut self,
 2225        position: DisplayPoint,
 2226        click_count: usize,
 2227        window: &mut Window,
 2228        cx: &mut Context<Self>,
 2229    ) {
 2230        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2231        let tail = self.selections.newest::<usize>(cx).tail();
 2232        self.begin_selection(position, false, click_count, window, cx);
 2233
 2234        let position = position.to_offset(&display_map, Bias::Left);
 2235        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2236
 2237        let mut pending_selection = self
 2238            .selections
 2239            .pending_anchor()
 2240            .expect("extend_selection not called with pending selection");
 2241        if position >= tail {
 2242            pending_selection.start = tail_anchor;
 2243        } else {
 2244            pending_selection.end = tail_anchor;
 2245            pending_selection.reversed = true;
 2246        }
 2247
 2248        let mut pending_mode = self.selections.pending_mode().unwrap();
 2249        match &mut pending_mode {
 2250            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2251            _ => {}
 2252        }
 2253
 2254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2255            s.set_pending(pending_selection, pending_mode)
 2256        });
 2257    }
 2258
 2259    fn begin_selection(
 2260        &mut self,
 2261        position: DisplayPoint,
 2262        add: bool,
 2263        click_count: usize,
 2264        window: &mut Window,
 2265        cx: &mut Context<Self>,
 2266    ) {
 2267        if !self.focus_handle.is_focused(window) {
 2268            self.last_focused_descendant = None;
 2269            window.focus(&self.focus_handle);
 2270        }
 2271
 2272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2273        let buffer = &display_map.buffer_snapshot;
 2274        let newest_selection = self.selections.newest_anchor().clone();
 2275        let position = display_map.clip_point(position, Bias::Left);
 2276
 2277        let start;
 2278        let end;
 2279        let mode;
 2280        let mut auto_scroll;
 2281        match click_count {
 2282            1 => {
 2283                start = buffer.anchor_before(position.to_point(&display_map));
 2284                end = start;
 2285                mode = SelectMode::Character;
 2286                auto_scroll = true;
 2287            }
 2288            2 => {
 2289                let range = movement::surrounding_word(&display_map, position);
 2290                start = buffer.anchor_before(range.start.to_point(&display_map));
 2291                end = buffer.anchor_before(range.end.to_point(&display_map));
 2292                mode = SelectMode::Word(start..end);
 2293                auto_scroll = true;
 2294            }
 2295            3 => {
 2296                let position = display_map
 2297                    .clip_point(position, Bias::Left)
 2298                    .to_point(&display_map);
 2299                let line_start = display_map.prev_line_boundary(position).0;
 2300                let next_line_start = buffer.clip_point(
 2301                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2302                    Bias::Left,
 2303                );
 2304                start = buffer.anchor_before(line_start);
 2305                end = buffer.anchor_before(next_line_start);
 2306                mode = SelectMode::Line(start..end);
 2307                auto_scroll = true;
 2308            }
 2309            _ => {
 2310                start = buffer.anchor_before(0);
 2311                end = buffer.anchor_before(buffer.len());
 2312                mode = SelectMode::All;
 2313                auto_scroll = false;
 2314            }
 2315        }
 2316        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2317
 2318        let point_to_delete: Option<usize> = {
 2319            let selected_points: Vec<Selection<Point>> =
 2320                self.selections.disjoint_in_range(start..end, cx);
 2321
 2322            if !add || click_count > 1 {
 2323                None
 2324            } else if !selected_points.is_empty() {
 2325                Some(selected_points[0].id)
 2326            } else {
 2327                let clicked_point_already_selected =
 2328                    self.selections.disjoint.iter().find(|selection| {
 2329                        selection.start.to_point(buffer) == start.to_point(buffer)
 2330                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2331                    });
 2332
 2333                clicked_point_already_selected.map(|selection| selection.id)
 2334            }
 2335        };
 2336
 2337        let selections_count = self.selections.count();
 2338
 2339        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2340            if let Some(point_to_delete) = point_to_delete {
 2341                s.delete(point_to_delete);
 2342
 2343                if selections_count == 1 {
 2344                    s.set_pending_anchor_range(start..end, mode);
 2345                }
 2346            } else {
 2347                if !add {
 2348                    s.clear_disjoint();
 2349                } else if click_count > 1 {
 2350                    s.delete(newest_selection.id)
 2351                }
 2352
 2353                s.set_pending_anchor_range(start..end, mode);
 2354            }
 2355        });
 2356    }
 2357
 2358    fn begin_columnar_selection(
 2359        &mut self,
 2360        position: DisplayPoint,
 2361        goal_column: u32,
 2362        reset: bool,
 2363        window: &mut Window,
 2364        cx: &mut Context<Self>,
 2365    ) {
 2366        if !self.focus_handle.is_focused(window) {
 2367            self.last_focused_descendant = None;
 2368            window.focus(&self.focus_handle);
 2369        }
 2370
 2371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2372
 2373        if reset {
 2374            let pointer_position = display_map
 2375                .buffer_snapshot
 2376                .anchor_before(position.to_point(&display_map));
 2377
 2378            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2379                s.clear_disjoint();
 2380                s.set_pending_anchor_range(
 2381                    pointer_position..pointer_position,
 2382                    SelectMode::Character,
 2383                );
 2384            });
 2385        }
 2386
 2387        let tail = self.selections.newest::<Point>(cx).tail();
 2388        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2389
 2390        if !reset {
 2391            self.select_columns(
 2392                tail.to_display_point(&display_map),
 2393                position,
 2394                goal_column,
 2395                &display_map,
 2396                window,
 2397                cx,
 2398            );
 2399        }
 2400    }
 2401
 2402    fn update_selection(
 2403        &mut self,
 2404        position: DisplayPoint,
 2405        goal_column: u32,
 2406        scroll_delta: gpui::Point<f32>,
 2407        window: &mut Window,
 2408        cx: &mut Context<Self>,
 2409    ) {
 2410        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2411
 2412        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2413            let tail = tail.to_display_point(&display_map);
 2414            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2415        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2416            let buffer = self.buffer.read(cx).snapshot(cx);
 2417            let head;
 2418            let tail;
 2419            let mode = self.selections.pending_mode().unwrap();
 2420            match &mode {
 2421                SelectMode::Character => {
 2422                    head = position.to_point(&display_map);
 2423                    tail = pending.tail().to_point(&buffer);
 2424                }
 2425                SelectMode::Word(original_range) => {
 2426                    let original_display_range = original_range.start.to_display_point(&display_map)
 2427                        ..original_range.end.to_display_point(&display_map);
 2428                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2429                        ..original_display_range.end.to_point(&display_map);
 2430                    if movement::is_inside_word(&display_map, position)
 2431                        || original_display_range.contains(&position)
 2432                    {
 2433                        let word_range = movement::surrounding_word(&display_map, position);
 2434                        if word_range.start < original_display_range.start {
 2435                            head = word_range.start.to_point(&display_map);
 2436                        } else {
 2437                            head = word_range.end.to_point(&display_map);
 2438                        }
 2439                    } else {
 2440                        head = position.to_point(&display_map);
 2441                    }
 2442
 2443                    if head <= original_buffer_range.start {
 2444                        tail = original_buffer_range.end;
 2445                    } else {
 2446                        tail = original_buffer_range.start;
 2447                    }
 2448                }
 2449                SelectMode::Line(original_range) => {
 2450                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2451
 2452                    let position = display_map
 2453                        .clip_point(position, Bias::Left)
 2454                        .to_point(&display_map);
 2455                    let line_start = display_map.prev_line_boundary(position).0;
 2456                    let next_line_start = buffer.clip_point(
 2457                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2458                        Bias::Left,
 2459                    );
 2460
 2461                    if line_start < original_range.start {
 2462                        head = line_start
 2463                    } else {
 2464                        head = next_line_start
 2465                    }
 2466
 2467                    if head <= original_range.start {
 2468                        tail = original_range.end;
 2469                    } else {
 2470                        tail = original_range.start;
 2471                    }
 2472                }
 2473                SelectMode::All => {
 2474                    return;
 2475                }
 2476            };
 2477
 2478            if head < tail {
 2479                pending.start = buffer.anchor_before(head);
 2480                pending.end = buffer.anchor_before(tail);
 2481                pending.reversed = true;
 2482            } else {
 2483                pending.start = buffer.anchor_before(tail);
 2484                pending.end = buffer.anchor_before(head);
 2485                pending.reversed = false;
 2486            }
 2487
 2488            self.change_selections(None, window, cx, |s| {
 2489                s.set_pending(pending, mode);
 2490            });
 2491        } else {
 2492            log::error!("update_selection dispatched with no pending selection");
 2493            return;
 2494        }
 2495
 2496        self.apply_scroll_delta(scroll_delta, window, cx);
 2497        cx.notify();
 2498    }
 2499
 2500    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2501        self.columnar_selection_tail.take();
 2502        if self.selections.pending_anchor().is_some() {
 2503            let selections = self.selections.all::<usize>(cx);
 2504            self.change_selections(None, window, cx, |s| {
 2505                s.select(selections);
 2506                s.clear_pending();
 2507            });
 2508        }
 2509    }
 2510
 2511    fn select_columns(
 2512        &mut self,
 2513        tail: DisplayPoint,
 2514        head: DisplayPoint,
 2515        goal_column: u32,
 2516        display_map: &DisplaySnapshot,
 2517        window: &mut Window,
 2518        cx: &mut Context<Self>,
 2519    ) {
 2520        let start_row = cmp::min(tail.row(), head.row());
 2521        let end_row = cmp::max(tail.row(), head.row());
 2522        let start_column = cmp::min(tail.column(), goal_column);
 2523        let end_column = cmp::max(tail.column(), goal_column);
 2524        let reversed = start_column < tail.column();
 2525
 2526        let selection_ranges = (start_row.0..=end_row.0)
 2527            .map(DisplayRow)
 2528            .filter_map(|row| {
 2529                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2530                    let start = display_map
 2531                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2532                        .to_point(display_map);
 2533                    let end = display_map
 2534                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2535                        .to_point(display_map);
 2536                    if reversed {
 2537                        Some(end..start)
 2538                    } else {
 2539                        Some(start..end)
 2540                    }
 2541                } else {
 2542                    None
 2543                }
 2544            })
 2545            .collect::<Vec<_>>();
 2546
 2547        self.change_selections(None, window, cx, |s| {
 2548            s.select_ranges(selection_ranges);
 2549        });
 2550        cx.notify();
 2551    }
 2552
 2553    pub fn has_pending_nonempty_selection(&self) -> bool {
 2554        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2555            Some(Selection { start, end, .. }) => start != end,
 2556            None => false,
 2557        };
 2558
 2559        pending_nonempty_selection
 2560            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2561    }
 2562
 2563    pub fn has_pending_selection(&self) -> bool {
 2564        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2565    }
 2566
 2567    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2568        self.selection_mark_mode = false;
 2569
 2570        if self.clear_expanded_diff_hunks(cx) {
 2571            cx.notify();
 2572            return;
 2573        }
 2574        if self.dismiss_menus_and_popups(true, window, cx) {
 2575            return;
 2576        }
 2577
 2578        if self.mode == EditorMode::Full
 2579            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2580        {
 2581            return;
 2582        }
 2583
 2584        cx.propagate();
 2585    }
 2586
 2587    pub fn dismiss_menus_and_popups(
 2588        &mut self,
 2589        should_report_inline_completion_event: bool,
 2590        window: &mut Window,
 2591        cx: &mut Context<Self>,
 2592    ) -> bool {
 2593        if self.take_rename(false, window, cx).is_some() {
 2594            return true;
 2595        }
 2596
 2597        if hide_hover(self, cx) {
 2598            return true;
 2599        }
 2600
 2601        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2602            return true;
 2603        }
 2604
 2605        if self.hide_context_menu(window, cx).is_some() {
 2606            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2607                self.update_visible_inline_completion(window, cx);
 2608            }
 2609            return true;
 2610        }
 2611
 2612        if self.mouse_context_menu.take().is_some() {
 2613            return true;
 2614        }
 2615
 2616        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2617            return true;
 2618        }
 2619
 2620        if self.snippet_stack.pop().is_some() {
 2621            return true;
 2622        }
 2623
 2624        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2625            self.dismiss_diagnostics(cx);
 2626            return true;
 2627        }
 2628
 2629        false
 2630    }
 2631
 2632    fn linked_editing_ranges_for(
 2633        &self,
 2634        selection: Range<text::Anchor>,
 2635        cx: &App,
 2636    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2637        if self.linked_edit_ranges.is_empty() {
 2638            return None;
 2639        }
 2640        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2641            selection.end.buffer_id.and_then(|end_buffer_id| {
 2642                if selection.start.buffer_id != Some(end_buffer_id) {
 2643                    return None;
 2644                }
 2645                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2646                let snapshot = buffer.read(cx).snapshot();
 2647                self.linked_edit_ranges
 2648                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2649                    .map(|ranges| (ranges, snapshot, buffer))
 2650            })?;
 2651        use text::ToOffset as TO;
 2652        // find offset from the start of current range to current cursor position
 2653        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2654
 2655        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2656        let start_difference = start_offset - start_byte_offset;
 2657        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2658        let end_difference = end_offset - start_byte_offset;
 2659        // Current range has associated linked ranges.
 2660        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2661        for range in linked_ranges.iter() {
 2662            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2663            let end_offset = start_offset + end_difference;
 2664            let start_offset = start_offset + start_difference;
 2665            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2666                continue;
 2667            }
 2668            if self.selections.disjoint_anchor_ranges().any(|s| {
 2669                if s.start.buffer_id != selection.start.buffer_id
 2670                    || s.end.buffer_id != selection.end.buffer_id
 2671                {
 2672                    return false;
 2673                }
 2674                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2675                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2676            }) {
 2677                continue;
 2678            }
 2679            let start = buffer_snapshot.anchor_after(start_offset);
 2680            let end = buffer_snapshot.anchor_after(end_offset);
 2681            linked_edits
 2682                .entry(buffer.clone())
 2683                .or_default()
 2684                .push(start..end);
 2685        }
 2686        Some(linked_edits)
 2687    }
 2688
 2689    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2690        let text: Arc<str> = text.into();
 2691
 2692        if self.read_only(cx) {
 2693            return;
 2694        }
 2695
 2696        let selections = self.selections.all_adjusted(cx);
 2697        let mut bracket_inserted = false;
 2698        let mut edits = Vec::new();
 2699        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2700        let mut new_selections = Vec::with_capacity(selections.len());
 2701        let mut new_autoclose_regions = Vec::new();
 2702        let snapshot = self.buffer.read(cx).read(cx);
 2703
 2704        for (selection, autoclose_region) in
 2705            self.selections_with_autoclose_regions(selections, &snapshot)
 2706        {
 2707            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2708                // Determine if the inserted text matches the opening or closing
 2709                // bracket of any of this language's bracket pairs.
 2710                let mut bracket_pair = None;
 2711                let mut is_bracket_pair_start = false;
 2712                let mut is_bracket_pair_end = false;
 2713                if !text.is_empty() {
 2714                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2715                    //  and they are removing the character that triggered IME popup.
 2716                    for (pair, enabled) in scope.brackets() {
 2717                        if !pair.close && !pair.surround {
 2718                            continue;
 2719                        }
 2720
 2721                        if enabled && pair.start.ends_with(text.as_ref()) {
 2722                            let prefix_len = pair.start.len() - text.len();
 2723                            let preceding_text_matches_prefix = prefix_len == 0
 2724                                || (selection.start.column >= (prefix_len as u32)
 2725                                    && snapshot.contains_str_at(
 2726                                        Point::new(
 2727                                            selection.start.row,
 2728                                            selection.start.column - (prefix_len as u32),
 2729                                        ),
 2730                                        &pair.start[..prefix_len],
 2731                                    ));
 2732                            if preceding_text_matches_prefix {
 2733                                bracket_pair = Some(pair.clone());
 2734                                is_bracket_pair_start = true;
 2735                                break;
 2736                            }
 2737                        }
 2738                        if pair.end.as_str() == text.as_ref() {
 2739                            bracket_pair = Some(pair.clone());
 2740                            is_bracket_pair_end = true;
 2741                            break;
 2742                        }
 2743                    }
 2744                }
 2745
 2746                if let Some(bracket_pair) = bracket_pair {
 2747                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2748                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2749                    let auto_surround =
 2750                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2751                    if selection.is_empty() {
 2752                        if is_bracket_pair_start {
 2753                            // If the inserted text is a suffix of an opening bracket and the
 2754                            // selection is preceded by the rest of the opening bracket, then
 2755                            // insert the closing bracket.
 2756                            let following_text_allows_autoclose = snapshot
 2757                                .chars_at(selection.start)
 2758                                .next()
 2759                                .map_or(true, |c| scope.should_autoclose_before(c));
 2760
 2761                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2762                                && bracket_pair.start.len() == 1
 2763                            {
 2764                                let target = bracket_pair.start.chars().next().unwrap();
 2765                                let current_line_count = snapshot
 2766                                    .reversed_chars_at(selection.start)
 2767                                    .take_while(|&c| c != '\n')
 2768                                    .filter(|&c| c == target)
 2769                                    .count();
 2770                                current_line_count % 2 == 1
 2771                            } else {
 2772                                false
 2773                            };
 2774
 2775                            if autoclose
 2776                                && bracket_pair.close
 2777                                && following_text_allows_autoclose
 2778                                && !is_closing_quote
 2779                            {
 2780                                let anchor = snapshot.anchor_before(selection.end);
 2781                                new_selections.push((selection.map(|_| anchor), text.len()));
 2782                                new_autoclose_regions.push((
 2783                                    anchor,
 2784                                    text.len(),
 2785                                    selection.id,
 2786                                    bracket_pair.clone(),
 2787                                ));
 2788                                edits.push((
 2789                                    selection.range(),
 2790                                    format!("{}{}", text, bracket_pair.end).into(),
 2791                                ));
 2792                                bracket_inserted = true;
 2793                                continue;
 2794                            }
 2795                        }
 2796
 2797                        if let Some(region) = autoclose_region {
 2798                            // If the selection is followed by an auto-inserted closing bracket,
 2799                            // then don't insert that closing bracket again; just move the selection
 2800                            // past the closing bracket.
 2801                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2802                                && text.as_ref() == region.pair.end.as_str();
 2803                            if should_skip {
 2804                                let anchor = snapshot.anchor_after(selection.end);
 2805                                new_selections
 2806                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2807                                continue;
 2808                            }
 2809                        }
 2810
 2811                        let always_treat_brackets_as_autoclosed = snapshot
 2812                            .settings_at(selection.start, cx)
 2813                            .always_treat_brackets_as_autoclosed;
 2814                        if always_treat_brackets_as_autoclosed
 2815                            && is_bracket_pair_end
 2816                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2817                        {
 2818                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2819                            // and the inserted text is a closing bracket and the selection is followed
 2820                            // by the closing bracket then move the selection past the closing bracket.
 2821                            let anchor = snapshot.anchor_after(selection.end);
 2822                            new_selections.push((selection.map(|_| anchor), text.len()));
 2823                            continue;
 2824                        }
 2825                    }
 2826                    // If an opening bracket is 1 character long and is typed while
 2827                    // text is selected, then surround that text with the bracket pair.
 2828                    else if auto_surround
 2829                        && bracket_pair.surround
 2830                        && is_bracket_pair_start
 2831                        && bracket_pair.start.chars().count() == 1
 2832                    {
 2833                        edits.push((selection.start..selection.start, text.clone()));
 2834                        edits.push((
 2835                            selection.end..selection.end,
 2836                            bracket_pair.end.as_str().into(),
 2837                        ));
 2838                        bracket_inserted = true;
 2839                        new_selections.push((
 2840                            Selection {
 2841                                id: selection.id,
 2842                                start: snapshot.anchor_after(selection.start),
 2843                                end: snapshot.anchor_before(selection.end),
 2844                                reversed: selection.reversed,
 2845                                goal: selection.goal,
 2846                            },
 2847                            0,
 2848                        ));
 2849                        continue;
 2850                    }
 2851                }
 2852            }
 2853
 2854            if self.auto_replace_emoji_shortcode
 2855                && selection.is_empty()
 2856                && text.as_ref().ends_with(':')
 2857            {
 2858                if let Some(possible_emoji_short_code) =
 2859                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2860                {
 2861                    if !possible_emoji_short_code.is_empty() {
 2862                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2863                            let emoji_shortcode_start = Point::new(
 2864                                selection.start.row,
 2865                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2866                            );
 2867
 2868                            // Remove shortcode from buffer
 2869                            edits.push((
 2870                                emoji_shortcode_start..selection.start,
 2871                                "".to_string().into(),
 2872                            ));
 2873                            new_selections.push((
 2874                                Selection {
 2875                                    id: selection.id,
 2876                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2877                                    end: snapshot.anchor_before(selection.start),
 2878                                    reversed: selection.reversed,
 2879                                    goal: selection.goal,
 2880                                },
 2881                                0,
 2882                            ));
 2883
 2884                            // Insert emoji
 2885                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2886                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2887                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2888
 2889                            continue;
 2890                        }
 2891                    }
 2892                }
 2893            }
 2894
 2895            // If not handling any auto-close operation, then just replace the selected
 2896            // text with the given input and move the selection to the end of the
 2897            // newly inserted text.
 2898            let anchor = snapshot.anchor_after(selection.end);
 2899            if !self.linked_edit_ranges.is_empty() {
 2900                let start_anchor = snapshot.anchor_before(selection.start);
 2901
 2902                let is_word_char = text.chars().next().map_or(true, |char| {
 2903                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2904                    classifier.is_word(char)
 2905                });
 2906
 2907                if is_word_char {
 2908                    if let Some(ranges) = self
 2909                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2910                    {
 2911                        for (buffer, edits) in ranges {
 2912                            linked_edits
 2913                                .entry(buffer.clone())
 2914                                .or_default()
 2915                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2916                        }
 2917                    }
 2918                }
 2919            }
 2920
 2921            new_selections.push((selection.map(|_| anchor), 0));
 2922            edits.push((selection.start..selection.end, text.clone()));
 2923        }
 2924
 2925        drop(snapshot);
 2926
 2927        self.transact(window, cx, |this, window, cx| {
 2928            this.buffer.update(cx, |buffer, cx| {
 2929                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2930            });
 2931            for (buffer, edits) in linked_edits {
 2932                buffer.update(cx, |buffer, cx| {
 2933                    let snapshot = buffer.snapshot();
 2934                    let edits = edits
 2935                        .into_iter()
 2936                        .map(|(range, text)| {
 2937                            use text::ToPoint as TP;
 2938                            let end_point = TP::to_point(&range.end, &snapshot);
 2939                            let start_point = TP::to_point(&range.start, &snapshot);
 2940                            (start_point..end_point, text)
 2941                        })
 2942                        .sorted_by_key(|(range, _)| range.start)
 2943                        .collect::<Vec<_>>();
 2944                    buffer.edit(edits, None, cx);
 2945                })
 2946            }
 2947            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2948            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2949            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2950            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2951                .zip(new_selection_deltas)
 2952                .map(|(selection, delta)| Selection {
 2953                    id: selection.id,
 2954                    start: selection.start + delta,
 2955                    end: selection.end + delta,
 2956                    reversed: selection.reversed,
 2957                    goal: SelectionGoal::None,
 2958                })
 2959                .collect::<Vec<_>>();
 2960
 2961            let mut i = 0;
 2962            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2963                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2964                let start = map.buffer_snapshot.anchor_before(position);
 2965                let end = map.buffer_snapshot.anchor_after(position);
 2966                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2967                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2968                        Ordering::Less => i += 1,
 2969                        Ordering::Greater => break,
 2970                        Ordering::Equal => {
 2971                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2972                                Ordering::Less => i += 1,
 2973                                Ordering::Equal => break,
 2974                                Ordering::Greater => break,
 2975                            }
 2976                        }
 2977                    }
 2978                }
 2979                this.autoclose_regions.insert(
 2980                    i,
 2981                    AutocloseRegion {
 2982                        selection_id,
 2983                        range: start..end,
 2984                        pair,
 2985                    },
 2986                );
 2987            }
 2988
 2989            let had_active_inline_completion = this.has_active_inline_completion();
 2990            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2991                s.select(new_selections)
 2992            });
 2993
 2994            if !bracket_inserted {
 2995                if let Some(on_type_format_task) =
 2996                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2997                {
 2998                    on_type_format_task.detach_and_log_err(cx);
 2999                }
 3000            }
 3001
 3002            let editor_settings = EditorSettings::get_global(cx);
 3003            if bracket_inserted
 3004                && (editor_settings.auto_signature_help
 3005                    || editor_settings.show_signature_help_after_edits)
 3006            {
 3007                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3008            }
 3009
 3010            let trigger_in_words =
 3011                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3012            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3013            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3014            this.refresh_inline_completion(true, false, window, cx);
 3015        });
 3016    }
 3017
 3018    fn find_possible_emoji_shortcode_at_position(
 3019        snapshot: &MultiBufferSnapshot,
 3020        position: Point,
 3021    ) -> Option<String> {
 3022        let mut chars = Vec::new();
 3023        let mut found_colon = false;
 3024        for char in snapshot.reversed_chars_at(position).take(100) {
 3025            // Found a possible emoji shortcode in the middle of the buffer
 3026            if found_colon {
 3027                if char.is_whitespace() {
 3028                    chars.reverse();
 3029                    return Some(chars.iter().collect());
 3030                }
 3031                // If the previous character is not a whitespace, we are in the middle of a word
 3032                // and we only want to complete the shortcode if the word is made up of other emojis
 3033                let mut containing_word = String::new();
 3034                for ch in snapshot
 3035                    .reversed_chars_at(position)
 3036                    .skip(chars.len() + 1)
 3037                    .take(100)
 3038                {
 3039                    if ch.is_whitespace() {
 3040                        break;
 3041                    }
 3042                    containing_word.push(ch);
 3043                }
 3044                let containing_word = containing_word.chars().rev().collect::<String>();
 3045                if util::word_consists_of_emojis(containing_word.as_str()) {
 3046                    chars.reverse();
 3047                    return Some(chars.iter().collect());
 3048                }
 3049            }
 3050
 3051            if char.is_whitespace() || !char.is_ascii() {
 3052                return None;
 3053            }
 3054            if char == ':' {
 3055                found_colon = true;
 3056            } else {
 3057                chars.push(char);
 3058            }
 3059        }
 3060        // Found a possible emoji shortcode at the beginning of the buffer
 3061        chars.reverse();
 3062        Some(chars.iter().collect())
 3063    }
 3064
 3065    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3066        self.transact(window, cx, |this, window, cx| {
 3067            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3068                let selections = this.selections.all::<usize>(cx);
 3069                let multi_buffer = this.buffer.read(cx);
 3070                let buffer = multi_buffer.snapshot(cx);
 3071                selections
 3072                    .iter()
 3073                    .map(|selection| {
 3074                        let start_point = selection.start.to_point(&buffer);
 3075                        let mut indent =
 3076                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3077                        indent.len = cmp::min(indent.len, start_point.column);
 3078                        let start = selection.start;
 3079                        let end = selection.end;
 3080                        let selection_is_empty = start == end;
 3081                        let language_scope = buffer.language_scope_at(start);
 3082                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3083                            &language_scope
 3084                        {
 3085                            let leading_whitespace_len = buffer
 3086                                .reversed_chars_at(start)
 3087                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3088                                .map(|c| c.len_utf8())
 3089                                .sum::<usize>();
 3090
 3091                            let trailing_whitespace_len = buffer
 3092                                .chars_at(end)
 3093                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3094                                .map(|c| c.len_utf8())
 3095                                .sum::<usize>();
 3096
 3097                            let insert_extra_newline =
 3098                                language.brackets().any(|(pair, enabled)| {
 3099                                    let pair_start = pair.start.trim_end();
 3100                                    let pair_end = pair.end.trim_start();
 3101
 3102                                    enabled
 3103                                        && pair.newline
 3104                                        && buffer.contains_str_at(
 3105                                            end + trailing_whitespace_len,
 3106                                            pair_end,
 3107                                        )
 3108                                        && buffer.contains_str_at(
 3109                                            (start - leading_whitespace_len)
 3110                                                .saturating_sub(pair_start.len()),
 3111                                            pair_start,
 3112                                        )
 3113                                });
 3114
 3115                            // Comment extension on newline is allowed only for cursor selections
 3116                            let comment_delimiter = maybe!({
 3117                                if !selection_is_empty {
 3118                                    return None;
 3119                                }
 3120
 3121                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3122                                    return None;
 3123                                }
 3124
 3125                                let delimiters = language.line_comment_prefixes();
 3126                                let max_len_of_delimiter =
 3127                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3128                                let (snapshot, range) =
 3129                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3130
 3131                                let mut index_of_first_non_whitespace = 0;
 3132                                let comment_candidate = snapshot
 3133                                    .chars_for_range(range)
 3134                                    .skip_while(|c| {
 3135                                        let should_skip = c.is_whitespace();
 3136                                        if should_skip {
 3137                                            index_of_first_non_whitespace += 1;
 3138                                        }
 3139                                        should_skip
 3140                                    })
 3141                                    .take(max_len_of_delimiter)
 3142                                    .collect::<String>();
 3143                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3144                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3145                                })?;
 3146                                let cursor_is_placed_after_comment_marker =
 3147                                    index_of_first_non_whitespace + comment_prefix.len()
 3148                                        <= start_point.column as usize;
 3149                                if cursor_is_placed_after_comment_marker {
 3150                                    Some(comment_prefix.clone())
 3151                                } else {
 3152                                    None
 3153                                }
 3154                            });
 3155                            (comment_delimiter, insert_extra_newline)
 3156                        } else {
 3157                            (None, false)
 3158                        };
 3159
 3160                        let capacity_for_delimiter = comment_delimiter
 3161                            .as_deref()
 3162                            .map(str::len)
 3163                            .unwrap_or_default();
 3164                        let mut new_text =
 3165                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3166                        new_text.push('\n');
 3167                        new_text.extend(indent.chars());
 3168                        if let Some(delimiter) = &comment_delimiter {
 3169                            new_text.push_str(delimiter);
 3170                        }
 3171                        if insert_extra_newline {
 3172                            new_text = new_text.repeat(2);
 3173                        }
 3174
 3175                        let anchor = buffer.anchor_after(end);
 3176                        let new_selection = selection.map(|_| anchor);
 3177                        (
 3178                            (start..end, new_text),
 3179                            (insert_extra_newline, new_selection),
 3180                        )
 3181                    })
 3182                    .unzip()
 3183            };
 3184
 3185            this.edit_with_autoindent(edits, cx);
 3186            let buffer = this.buffer.read(cx).snapshot(cx);
 3187            let new_selections = selection_fixup_info
 3188                .into_iter()
 3189                .map(|(extra_newline_inserted, new_selection)| {
 3190                    let mut cursor = new_selection.end.to_point(&buffer);
 3191                    if extra_newline_inserted {
 3192                        cursor.row -= 1;
 3193                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3194                    }
 3195                    new_selection.map(|_| cursor)
 3196                })
 3197                .collect();
 3198
 3199            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3200                s.select(new_selections)
 3201            });
 3202            this.refresh_inline_completion(true, false, window, cx);
 3203        });
 3204    }
 3205
 3206    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3207        let buffer = self.buffer.read(cx);
 3208        let snapshot = buffer.snapshot(cx);
 3209
 3210        let mut edits = Vec::new();
 3211        let mut rows = Vec::new();
 3212
 3213        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3214            let cursor = selection.head();
 3215            let row = cursor.row;
 3216
 3217            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3218
 3219            let newline = "\n".to_string();
 3220            edits.push((start_of_line..start_of_line, newline));
 3221
 3222            rows.push(row + rows_inserted as u32);
 3223        }
 3224
 3225        self.transact(window, cx, |editor, window, cx| {
 3226            editor.edit(edits, cx);
 3227
 3228            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3229                let mut index = 0;
 3230                s.move_cursors_with(|map, _, _| {
 3231                    let row = rows[index];
 3232                    index += 1;
 3233
 3234                    let point = Point::new(row, 0);
 3235                    let boundary = map.next_line_boundary(point).1;
 3236                    let clipped = map.clip_point(boundary, Bias::Left);
 3237
 3238                    (clipped, SelectionGoal::None)
 3239                });
 3240            });
 3241
 3242            let mut indent_edits = Vec::new();
 3243            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3244            for row in rows {
 3245                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3246                for (row, indent) in indents {
 3247                    if indent.len == 0 {
 3248                        continue;
 3249                    }
 3250
 3251                    let text = match indent.kind {
 3252                        IndentKind::Space => " ".repeat(indent.len as usize),
 3253                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3254                    };
 3255                    let point = Point::new(row.0, 0);
 3256                    indent_edits.push((point..point, text));
 3257                }
 3258            }
 3259            editor.edit(indent_edits, cx);
 3260        });
 3261    }
 3262
 3263    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3264        let buffer = self.buffer.read(cx);
 3265        let snapshot = buffer.snapshot(cx);
 3266
 3267        let mut edits = Vec::new();
 3268        let mut rows = Vec::new();
 3269        let mut rows_inserted = 0;
 3270
 3271        for selection in self.selections.all_adjusted(cx) {
 3272            let cursor = selection.head();
 3273            let row = cursor.row;
 3274
 3275            let point = Point::new(row + 1, 0);
 3276            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3277
 3278            let newline = "\n".to_string();
 3279            edits.push((start_of_line..start_of_line, newline));
 3280
 3281            rows_inserted += 1;
 3282            rows.push(row + rows_inserted);
 3283        }
 3284
 3285        self.transact(window, cx, |editor, window, cx| {
 3286            editor.edit(edits, cx);
 3287
 3288            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3289                let mut index = 0;
 3290                s.move_cursors_with(|map, _, _| {
 3291                    let row = rows[index];
 3292                    index += 1;
 3293
 3294                    let point = Point::new(row, 0);
 3295                    let boundary = map.next_line_boundary(point).1;
 3296                    let clipped = map.clip_point(boundary, Bias::Left);
 3297
 3298                    (clipped, SelectionGoal::None)
 3299                });
 3300            });
 3301
 3302            let mut indent_edits = Vec::new();
 3303            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3304            for row in rows {
 3305                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3306                for (row, indent) in indents {
 3307                    if indent.len == 0 {
 3308                        continue;
 3309                    }
 3310
 3311                    let text = match indent.kind {
 3312                        IndentKind::Space => " ".repeat(indent.len as usize),
 3313                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3314                    };
 3315                    let point = Point::new(row.0, 0);
 3316                    indent_edits.push((point..point, text));
 3317                }
 3318            }
 3319            editor.edit(indent_edits, cx);
 3320        });
 3321    }
 3322
 3323    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3324        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3325            original_indent_columns: Vec::new(),
 3326        });
 3327        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3328    }
 3329
 3330    fn insert_with_autoindent_mode(
 3331        &mut self,
 3332        text: &str,
 3333        autoindent_mode: Option<AutoindentMode>,
 3334        window: &mut Window,
 3335        cx: &mut Context<Self>,
 3336    ) {
 3337        if self.read_only(cx) {
 3338            return;
 3339        }
 3340
 3341        let text: Arc<str> = text.into();
 3342        self.transact(window, cx, |this, window, cx| {
 3343            let old_selections = this.selections.all_adjusted(cx);
 3344            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3345                let anchors = {
 3346                    let snapshot = buffer.read(cx);
 3347                    old_selections
 3348                        .iter()
 3349                        .map(|s| {
 3350                            let anchor = snapshot.anchor_after(s.head());
 3351                            s.map(|_| anchor)
 3352                        })
 3353                        .collect::<Vec<_>>()
 3354                };
 3355                buffer.edit(
 3356                    old_selections
 3357                        .iter()
 3358                        .map(|s| (s.start..s.end, text.clone())),
 3359                    autoindent_mode,
 3360                    cx,
 3361                );
 3362                anchors
 3363            });
 3364
 3365            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3366                s.select_anchors(selection_anchors);
 3367            });
 3368
 3369            cx.notify();
 3370        });
 3371    }
 3372
 3373    fn trigger_completion_on_input(
 3374        &mut self,
 3375        text: &str,
 3376        trigger_in_words: bool,
 3377        window: &mut Window,
 3378        cx: &mut Context<Self>,
 3379    ) {
 3380        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3381            self.show_completions(
 3382                &ShowCompletions {
 3383                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3384                },
 3385                window,
 3386                cx,
 3387            );
 3388        } else {
 3389            self.hide_context_menu(window, cx);
 3390        }
 3391    }
 3392
 3393    fn is_completion_trigger(
 3394        &self,
 3395        text: &str,
 3396        trigger_in_words: bool,
 3397        cx: &mut Context<Self>,
 3398    ) -> bool {
 3399        let position = self.selections.newest_anchor().head();
 3400        let multibuffer = self.buffer.read(cx);
 3401        let Some(buffer) = position
 3402            .buffer_id
 3403            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3404        else {
 3405            return false;
 3406        };
 3407
 3408        if let Some(completion_provider) = &self.completion_provider {
 3409            completion_provider.is_completion_trigger(
 3410                &buffer,
 3411                position.text_anchor,
 3412                text,
 3413                trigger_in_words,
 3414                cx,
 3415            )
 3416        } else {
 3417            false
 3418        }
 3419    }
 3420
 3421    /// If any empty selections is touching the start of its innermost containing autoclose
 3422    /// region, expand it to select the brackets.
 3423    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3424        let selections = self.selections.all::<usize>(cx);
 3425        let buffer = self.buffer.read(cx).read(cx);
 3426        let new_selections = self
 3427            .selections_with_autoclose_regions(selections, &buffer)
 3428            .map(|(mut selection, region)| {
 3429                if !selection.is_empty() {
 3430                    return selection;
 3431                }
 3432
 3433                if let Some(region) = region {
 3434                    let mut range = region.range.to_offset(&buffer);
 3435                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3436                        range.start -= region.pair.start.len();
 3437                        if buffer.contains_str_at(range.start, &region.pair.start)
 3438                            && buffer.contains_str_at(range.end, &region.pair.end)
 3439                        {
 3440                            range.end += region.pair.end.len();
 3441                            selection.start = range.start;
 3442                            selection.end = range.end;
 3443
 3444                            return selection;
 3445                        }
 3446                    }
 3447                }
 3448
 3449                let always_treat_brackets_as_autoclosed = buffer
 3450                    .settings_at(selection.start, cx)
 3451                    .always_treat_brackets_as_autoclosed;
 3452
 3453                if !always_treat_brackets_as_autoclosed {
 3454                    return selection;
 3455                }
 3456
 3457                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3458                    for (pair, enabled) in scope.brackets() {
 3459                        if !enabled || !pair.close {
 3460                            continue;
 3461                        }
 3462
 3463                        if buffer.contains_str_at(selection.start, &pair.end) {
 3464                            let pair_start_len = pair.start.len();
 3465                            if buffer.contains_str_at(
 3466                                selection.start.saturating_sub(pair_start_len),
 3467                                &pair.start,
 3468                            ) {
 3469                                selection.start -= pair_start_len;
 3470                                selection.end += pair.end.len();
 3471
 3472                                return selection;
 3473                            }
 3474                        }
 3475                    }
 3476                }
 3477
 3478                selection
 3479            })
 3480            .collect();
 3481
 3482        drop(buffer);
 3483        self.change_selections(None, window, cx, |selections| {
 3484            selections.select(new_selections)
 3485        });
 3486    }
 3487
 3488    /// Iterate the given selections, and for each one, find the smallest surrounding
 3489    /// autoclose region. This uses the ordering of the selections and the autoclose
 3490    /// regions to avoid repeated comparisons.
 3491    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3492        &'a self,
 3493        selections: impl IntoIterator<Item = Selection<D>>,
 3494        buffer: &'a MultiBufferSnapshot,
 3495    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3496        let mut i = 0;
 3497        let mut regions = self.autoclose_regions.as_slice();
 3498        selections.into_iter().map(move |selection| {
 3499            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3500
 3501            let mut enclosing = None;
 3502            while let Some(pair_state) = regions.get(i) {
 3503                if pair_state.range.end.to_offset(buffer) < range.start {
 3504                    regions = &regions[i + 1..];
 3505                    i = 0;
 3506                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3507                    break;
 3508                } else {
 3509                    if pair_state.selection_id == selection.id {
 3510                        enclosing = Some(pair_state);
 3511                    }
 3512                    i += 1;
 3513                }
 3514            }
 3515
 3516            (selection, enclosing)
 3517        })
 3518    }
 3519
 3520    /// Remove any autoclose regions that no longer contain their selection.
 3521    fn invalidate_autoclose_regions(
 3522        &mut self,
 3523        mut selections: &[Selection<Anchor>],
 3524        buffer: &MultiBufferSnapshot,
 3525    ) {
 3526        self.autoclose_regions.retain(|state| {
 3527            let mut i = 0;
 3528            while let Some(selection) = selections.get(i) {
 3529                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3530                    selections = &selections[1..];
 3531                    continue;
 3532                }
 3533                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3534                    break;
 3535                }
 3536                if selection.id == state.selection_id {
 3537                    return true;
 3538                } else {
 3539                    i += 1;
 3540                }
 3541            }
 3542            false
 3543        });
 3544    }
 3545
 3546    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3547        let offset = position.to_offset(buffer);
 3548        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3549        if offset > word_range.start && kind == Some(CharKind::Word) {
 3550            Some(
 3551                buffer
 3552                    .text_for_range(word_range.start..offset)
 3553                    .collect::<String>(),
 3554            )
 3555        } else {
 3556            None
 3557        }
 3558    }
 3559
 3560    pub fn toggle_inlay_hints(
 3561        &mut self,
 3562        _: &ToggleInlayHints,
 3563        _: &mut Window,
 3564        cx: &mut Context<Self>,
 3565    ) {
 3566        self.refresh_inlay_hints(
 3567            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3568            cx,
 3569        );
 3570    }
 3571
 3572    pub fn inlay_hints_enabled(&self) -> bool {
 3573        self.inlay_hint_cache.enabled
 3574    }
 3575
 3576    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3577        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3578            return;
 3579        }
 3580
 3581        let reason_description = reason.description();
 3582        let ignore_debounce = matches!(
 3583            reason,
 3584            InlayHintRefreshReason::SettingsChange(_)
 3585                | InlayHintRefreshReason::Toggle(_)
 3586                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3587        );
 3588        let (invalidate_cache, required_languages) = match reason {
 3589            InlayHintRefreshReason::Toggle(enabled) => {
 3590                self.inlay_hint_cache.enabled = enabled;
 3591                if enabled {
 3592                    (InvalidationStrategy::RefreshRequested, None)
 3593                } else {
 3594                    self.inlay_hint_cache.clear();
 3595                    self.splice_inlays(
 3596                        self.visible_inlay_hints(cx)
 3597                            .iter()
 3598                            .map(|inlay| inlay.id)
 3599                            .collect(),
 3600                        Vec::new(),
 3601                        cx,
 3602                    );
 3603                    return;
 3604                }
 3605            }
 3606            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3607                match self.inlay_hint_cache.update_settings(
 3608                    &self.buffer,
 3609                    new_settings,
 3610                    self.visible_inlay_hints(cx),
 3611                    cx,
 3612                ) {
 3613                    ControlFlow::Break(Some(InlaySplice {
 3614                        to_remove,
 3615                        to_insert,
 3616                    })) => {
 3617                        self.splice_inlays(to_remove, to_insert, cx);
 3618                        return;
 3619                    }
 3620                    ControlFlow::Break(None) => return,
 3621                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3622                }
 3623            }
 3624            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3625                if let Some(InlaySplice {
 3626                    to_remove,
 3627                    to_insert,
 3628                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3629                {
 3630                    self.splice_inlays(to_remove, to_insert, cx);
 3631                }
 3632                return;
 3633            }
 3634            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3635            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3636                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3637            }
 3638            InlayHintRefreshReason::RefreshRequested => {
 3639                (InvalidationStrategy::RefreshRequested, None)
 3640            }
 3641        };
 3642
 3643        if let Some(InlaySplice {
 3644            to_remove,
 3645            to_insert,
 3646        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3647            reason_description,
 3648            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3649            invalidate_cache,
 3650            ignore_debounce,
 3651            cx,
 3652        ) {
 3653            self.splice_inlays(to_remove, to_insert, cx);
 3654        }
 3655    }
 3656
 3657    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3658        self.display_map
 3659            .read(cx)
 3660            .current_inlays()
 3661            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3662            .cloned()
 3663            .collect()
 3664    }
 3665
 3666    pub fn excerpts_for_inlay_hints_query(
 3667        &self,
 3668        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3669        cx: &mut Context<Editor>,
 3670    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3671        let Some(project) = self.project.as_ref() else {
 3672            return HashMap::default();
 3673        };
 3674        let project = project.read(cx);
 3675        let multi_buffer = self.buffer().read(cx);
 3676        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3677        let multi_buffer_visible_start = self
 3678            .scroll_manager
 3679            .anchor()
 3680            .anchor
 3681            .to_point(&multi_buffer_snapshot);
 3682        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3683            multi_buffer_visible_start
 3684                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3685            Bias::Left,
 3686        );
 3687        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3688        multi_buffer_snapshot
 3689            .range_to_buffer_ranges(multi_buffer_visible_range)
 3690            .into_iter()
 3691            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3692            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3693                let buffer_file = project::File::from_dyn(buffer.file())?;
 3694                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3695                let worktree_entry = buffer_worktree
 3696                    .read(cx)
 3697                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3698                if worktree_entry.is_ignored {
 3699                    return None;
 3700                }
 3701
 3702                let language = buffer.language()?;
 3703                if let Some(restrict_to_languages) = restrict_to_languages {
 3704                    if !restrict_to_languages.contains(language) {
 3705                        return None;
 3706                    }
 3707                }
 3708                Some((
 3709                    excerpt_id,
 3710                    (
 3711                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3712                        buffer.version().clone(),
 3713                        excerpt_visible_range,
 3714                    ),
 3715                ))
 3716            })
 3717            .collect()
 3718    }
 3719
 3720    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3721        TextLayoutDetails {
 3722            text_system: window.text_system().clone(),
 3723            editor_style: self.style.clone().unwrap(),
 3724            rem_size: window.rem_size(),
 3725            scroll_anchor: self.scroll_manager.anchor(),
 3726            visible_rows: self.visible_line_count(),
 3727            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3728        }
 3729    }
 3730
 3731    pub fn splice_inlays(
 3732        &self,
 3733        to_remove: Vec<InlayId>,
 3734        to_insert: Vec<Inlay>,
 3735        cx: &mut Context<Self>,
 3736    ) {
 3737        self.display_map.update(cx, |display_map, cx| {
 3738            display_map.splice_inlays(to_remove, to_insert, cx)
 3739        });
 3740        cx.notify();
 3741    }
 3742
 3743    fn trigger_on_type_formatting(
 3744        &self,
 3745        input: String,
 3746        window: &mut Window,
 3747        cx: &mut Context<Self>,
 3748    ) -> Option<Task<Result<()>>> {
 3749        if input.len() != 1 {
 3750            return None;
 3751        }
 3752
 3753        let project = self.project.as_ref()?;
 3754        let position = self.selections.newest_anchor().head();
 3755        let (buffer, buffer_position) = self
 3756            .buffer
 3757            .read(cx)
 3758            .text_anchor_for_position(position, cx)?;
 3759
 3760        let settings = language_settings::language_settings(
 3761            buffer
 3762                .read(cx)
 3763                .language_at(buffer_position)
 3764                .map(|l| l.name()),
 3765            buffer.read(cx).file(),
 3766            cx,
 3767        );
 3768        if !settings.use_on_type_format {
 3769            return None;
 3770        }
 3771
 3772        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3773        // hence we do LSP request & edit on host side only — add formats to host's history.
 3774        let push_to_lsp_host_history = true;
 3775        // If this is not the host, append its history with new edits.
 3776        let push_to_client_history = project.read(cx).is_via_collab();
 3777
 3778        let on_type_formatting = project.update(cx, |project, cx| {
 3779            project.on_type_format(
 3780                buffer.clone(),
 3781                buffer_position,
 3782                input,
 3783                push_to_lsp_host_history,
 3784                cx,
 3785            )
 3786        });
 3787        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3788            if let Some(transaction) = on_type_formatting.await? {
 3789                if push_to_client_history {
 3790                    buffer
 3791                        .update(&mut cx, |buffer, _| {
 3792                            buffer.push_transaction(transaction, Instant::now());
 3793                        })
 3794                        .ok();
 3795                }
 3796                editor.update(&mut cx, |editor, cx| {
 3797                    editor.refresh_document_highlights(cx);
 3798                })?;
 3799            }
 3800            Ok(())
 3801        }))
 3802    }
 3803
 3804    pub fn show_completions(
 3805        &mut self,
 3806        options: &ShowCompletions,
 3807        window: &mut Window,
 3808        cx: &mut Context<Self>,
 3809    ) {
 3810        if self.pending_rename.is_some() {
 3811            return;
 3812        }
 3813
 3814        let Some(provider) = self.completion_provider.as_ref() else {
 3815            return;
 3816        };
 3817
 3818        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3819            return;
 3820        }
 3821
 3822        let position = self.selections.newest_anchor().head();
 3823        if position.diff_base_anchor.is_some() {
 3824            return;
 3825        }
 3826        let (buffer, buffer_position) =
 3827            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3828                output
 3829            } else {
 3830                return;
 3831            };
 3832        let show_completion_documentation = buffer
 3833            .read(cx)
 3834            .snapshot()
 3835            .settings_at(buffer_position, cx)
 3836            .show_completion_documentation;
 3837
 3838        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3839
 3840        let trigger_kind = match &options.trigger {
 3841            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3842                CompletionTriggerKind::TRIGGER_CHARACTER
 3843            }
 3844            _ => CompletionTriggerKind::INVOKED,
 3845        };
 3846        let completion_context = CompletionContext {
 3847            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3848                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3849                    Some(String::from(trigger))
 3850                } else {
 3851                    None
 3852                }
 3853            }),
 3854            trigger_kind,
 3855        };
 3856        let completions =
 3857            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3858        let sort_completions = provider.sort_completions();
 3859
 3860        let id = post_inc(&mut self.next_completion_id);
 3861        let task = cx.spawn_in(window, |editor, mut cx| {
 3862            async move {
 3863                editor.update(&mut cx, |this, _| {
 3864                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3865                })?;
 3866                let completions = completions.await.log_err();
 3867                let menu = if let Some(completions) = completions {
 3868                    let mut menu = CompletionsMenu::new(
 3869                        id,
 3870                        sort_completions,
 3871                        show_completion_documentation,
 3872                        position,
 3873                        buffer.clone(),
 3874                        completions.into(),
 3875                    );
 3876
 3877                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3878                        .await;
 3879
 3880                    menu.visible().then_some(menu)
 3881                } else {
 3882                    None
 3883                };
 3884
 3885                editor.update_in(&mut cx, |editor, window, cx| {
 3886                    match editor.context_menu.borrow().as_ref() {
 3887                        None => {}
 3888                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3889                            if prev_menu.id > id {
 3890                                return;
 3891                            }
 3892                        }
 3893                        _ => return,
 3894                    }
 3895
 3896                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3897                        let mut menu = menu.unwrap();
 3898                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3899
 3900                        if editor.show_inline_completions_in_menu(cx) {
 3901                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3902                                menu.show_inline_completion_hint(hint);
 3903                            }
 3904                        } else {
 3905                            editor.discard_inline_completion(false, cx);
 3906                        }
 3907
 3908                        *editor.context_menu.borrow_mut() =
 3909                            Some(CodeContextMenu::Completions(menu));
 3910
 3911                        cx.notify();
 3912                    } else if editor.completion_tasks.len() <= 1 {
 3913                        // If there are no more completion tasks and the last menu was
 3914                        // empty, we should hide it.
 3915                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3916                        // If it was already hidden and we don't show inline
 3917                        // completions in the menu, we should also show the
 3918                        // inline-completion when available.
 3919                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3920                            editor.update_visible_inline_completion(window, cx);
 3921                        }
 3922                    }
 3923                })?;
 3924
 3925                Ok::<_, anyhow::Error>(())
 3926            }
 3927            .log_err()
 3928        });
 3929
 3930        self.completion_tasks.push((id, task));
 3931    }
 3932
 3933    pub fn confirm_completion(
 3934        &mut self,
 3935        action: &ConfirmCompletion,
 3936        window: &mut Window,
 3937        cx: &mut Context<Self>,
 3938    ) -> Option<Task<Result<()>>> {
 3939        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3940    }
 3941
 3942    pub fn compose_completion(
 3943        &mut self,
 3944        action: &ComposeCompletion,
 3945        window: &mut Window,
 3946        cx: &mut Context<Self>,
 3947    ) -> Option<Task<Result<()>>> {
 3948        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3949    }
 3950
 3951    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3952        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3953            return;
 3954        };
 3955
 3956        let project = project.read(cx);
 3957
 3958        ZedPredictModal::toggle(
 3959            workspace,
 3960            project.user_store().clone(),
 3961            project.client().clone(),
 3962            project.fs().clone(),
 3963            window,
 3964            cx,
 3965        );
 3966    }
 3967
 3968    fn do_completion(
 3969        &mut self,
 3970        item_ix: Option<usize>,
 3971        intent: CompletionIntent,
 3972        window: &mut Window,
 3973        cx: &mut Context<Editor>,
 3974    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3975        use language::ToOffset as _;
 3976
 3977        {
 3978            let context_menu = self.context_menu.borrow();
 3979            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3980                let entries = menu.entries.borrow();
 3981                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3982                match entry {
 3983                    Some(CompletionEntry::InlineCompletionHint(
 3984                        InlineCompletionMenuHint::Loading,
 3985                    )) => return Some(Task::ready(Ok(()))),
 3986                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3987                        drop(entries);
 3988                        drop(context_menu);
 3989                        self.context_menu_next(&Default::default(), window, cx);
 3990                        return Some(Task::ready(Ok(())));
 3991                    }
 3992                    Some(CompletionEntry::InlineCompletionHint(
 3993                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3994                    )) => {
 3995                        drop(entries);
 3996                        drop(context_menu);
 3997                        self.toggle_zed_predict_onboarding(window, cx);
 3998                        return Some(Task::ready(Ok(())));
 3999                    }
 4000                    _ => {}
 4001                }
 4002            }
 4003        }
 4004
 4005        let completions_menu =
 4006            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4007                menu
 4008            } else {
 4009                return None;
 4010            };
 4011
 4012        let entries = completions_menu.entries.borrow();
 4013        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4014        let mat = match mat {
 4015            CompletionEntry::InlineCompletionHint(_) => {
 4016                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4017                cx.stop_propagation();
 4018                return Some(Task::ready(Ok(())));
 4019            }
 4020            CompletionEntry::Match(mat) => {
 4021                if self.show_inline_completions_in_menu(cx) {
 4022                    self.discard_inline_completion(true, cx);
 4023                }
 4024                mat
 4025            }
 4026        };
 4027        let candidate_id = mat.candidate_id;
 4028        drop(entries);
 4029
 4030        let buffer_handle = completions_menu.buffer;
 4031        let completion = completions_menu
 4032            .completions
 4033            .borrow()
 4034            .get(candidate_id)?
 4035            .clone();
 4036        cx.stop_propagation();
 4037
 4038        let snippet;
 4039        let text;
 4040
 4041        if completion.is_snippet() {
 4042            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4043            text = snippet.as_ref().unwrap().text.clone();
 4044        } else {
 4045            snippet = None;
 4046            text = completion.new_text.clone();
 4047        };
 4048        let selections = self.selections.all::<usize>(cx);
 4049        let buffer = buffer_handle.read(cx);
 4050        let old_range = completion.old_range.to_offset(buffer);
 4051        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4052
 4053        let newest_selection = self.selections.newest_anchor();
 4054        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4055            return None;
 4056        }
 4057
 4058        let lookbehind = newest_selection
 4059            .start
 4060            .text_anchor
 4061            .to_offset(buffer)
 4062            .saturating_sub(old_range.start);
 4063        let lookahead = old_range
 4064            .end
 4065            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4066        let mut common_prefix_len = old_text
 4067            .bytes()
 4068            .zip(text.bytes())
 4069            .take_while(|(a, b)| a == b)
 4070            .count();
 4071
 4072        let snapshot = self.buffer.read(cx).snapshot(cx);
 4073        let mut range_to_replace: Option<Range<isize>> = None;
 4074        let mut ranges = Vec::new();
 4075        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4076        for selection in &selections {
 4077            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4078                let start = selection.start.saturating_sub(lookbehind);
 4079                let end = selection.end + lookahead;
 4080                if selection.id == newest_selection.id {
 4081                    range_to_replace = Some(
 4082                        ((start + common_prefix_len) as isize - selection.start as isize)
 4083                            ..(end as isize - selection.start as isize),
 4084                    );
 4085                }
 4086                ranges.push(start + common_prefix_len..end);
 4087            } else {
 4088                common_prefix_len = 0;
 4089                ranges.clear();
 4090                ranges.extend(selections.iter().map(|s| {
 4091                    if s.id == newest_selection.id {
 4092                        range_to_replace = Some(
 4093                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4094                                - selection.start as isize
 4095                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4096                                    - selection.start as isize,
 4097                        );
 4098                        old_range.clone()
 4099                    } else {
 4100                        s.start..s.end
 4101                    }
 4102                }));
 4103                break;
 4104            }
 4105            if !self.linked_edit_ranges.is_empty() {
 4106                let start_anchor = snapshot.anchor_before(selection.head());
 4107                let end_anchor = snapshot.anchor_after(selection.tail());
 4108                if let Some(ranges) = self
 4109                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4110                {
 4111                    for (buffer, edits) in ranges {
 4112                        linked_edits.entry(buffer.clone()).or_default().extend(
 4113                            edits
 4114                                .into_iter()
 4115                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4116                        );
 4117                    }
 4118                }
 4119            }
 4120        }
 4121        let text = &text[common_prefix_len..];
 4122
 4123        cx.emit(EditorEvent::InputHandled {
 4124            utf16_range_to_replace: range_to_replace,
 4125            text: text.into(),
 4126        });
 4127
 4128        self.transact(window, cx, |this, window, cx| {
 4129            if let Some(mut snippet) = snippet {
 4130                snippet.text = text.to_string();
 4131                for tabstop in snippet
 4132                    .tabstops
 4133                    .iter_mut()
 4134                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4135                {
 4136                    tabstop.start -= common_prefix_len as isize;
 4137                    tabstop.end -= common_prefix_len as isize;
 4138                }
 4139
 4140                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4141            } else {
 4142                this.buffer.update(cx, |buffer, cx| {
 4143                    buffer.edit(
 4144                        ranges.iter().map(|range| (range.clone(), text)),
 4145                        this.autoindent_mode.clone(),
 4146                        cx,
 4147                    );
 4148                });
 4149            }
 4150            for (buffer, edits) in linked_edits {
 4151                buffer.update(cx, |buffer, cx| {
 4152                    let snapshot = buffer.snapshot();
 4153                    let edits = edits
 4154                        .into_iter()
 4155                        .map(|(range, text)| {
 4156                            use text::ToPoint as TP;
 4157                            let end_point = TP::to_point(&range.end, &snapshot);
 4158                            let start_point = TP::to_point(&range.start, &snapshot);
 4159                            (start_point..end_point, text)
 4160                        })
 4161                        .sorted_by_key(|(range, _)| range.start)
 4162                        .collect::<Vec<_>>();
 4163                    buffer.edit(edits, None, cx);
 4164                })
 4165            }
 4166
 4167            this.refresh_inline_completion(true, false, window, cx);
 4168        });
 4169
 4170        let show_new_completions_on_confirm = completion
 4171            .confirm
 4172            .as_ref()
 4173            .map_or(false, |confirm| confirm(intent, window, cx));
 4174        if show_new_completions_on_confirm {
 4175            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4176        }
 4177
 4178        let provider = self.completion_provider.as_ref()?;
 4179        drop(completion);
 4180        let apply_edits = provider.apply_additional_edits_for_completion(
 4181            buffer_handle,
 4182            completions_menu.completions.clone(),
 4183            candidate_id,
 4184            true,
 4185            cx,
 4186        );
 4187
 4188        let editor_settings = EditorSettings::get_global(cx);
 4189        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4190            // After the code completion is finished, users often want to know what signatures are needed.
 4191            // so we should automatically call signature_help
 4192            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4193        }
 4194
 4195        Some(cx.foreground_executor().spawn(async move {
 4196            apply_edits.await?;
 4197            Ok(())
 4198        }))
 4199    }
 4200
 4201    pub fn toggle_code_actions(
 4202        &mut self,
 4203        action: &ToggleCodeActions,
 4204        window: &mut Window,
 4205        cx: &mut Context<Self>,
 4206    ) {
 4207        let mut context_menu = self.context_menu.borrow_mut();
 4208        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4209            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4210                // Toggle if we're selecting the same one
 4211                *context_menu = None;
 4212                cx.notify();
 4213                return;
 4214            } else {
 4215                // Otherwise, clear it and start a new one
 4216                *context_menu = None;
 4217                cx.notify();
 4218            }
 4219        }
 4220        drop(context_menu);
 4221        let snapshot = self.snapshot(window, cx);
 4222        let deployed_from_indicator = action.deployed_from_indicator;
 4223        let mut task = self.code_actions_task.take();
 4224        let action = action.clone();
 4225        cx.spawn_in(window, |editor, mut cx| async move {
 4226            while let Some(prev_task) = task {
 4227                prev_task.await.log_err();
 4228                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4229            }
 4230
 4231            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4232                if editor.focus_handle.is_focused(window) {
 4233                    let multibuffer_point = action
 4234                        .deployed_from_indicator
 4235                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4236                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4237                    let (buffer, buffer_row) = snapshot
 4238                        .buffer_snapshot
 4239                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4240                        .and_then(|(buffer_snapshot, range)| {
 4241                            editor
 4242                                .buffer
 4243                                .read(cx)
 4244                                .buffer(buffer_snapshot.remote_id())
 4245                                .map(|buffer| (buffer, range.start.row))
 4246                        })?;
 4247                    let (_, code_actions) = editor
 4248                        .available_code_actions
 4249                        .clone()
 4250                        .and_then(|(location, code_actions)| {
 4251                            let snapshot = location.buffer.read(cx).snapshot();
 4252                            let point_range = location.range.to_point(&snapshot);
 4253                            let point_range = point_range.start.row..=point_range.end.row;
 4254                            if point_range.contains(&buffer_row) {
 4255                                Some((location, code_actions))
 4256                            } else {
 4257                                None
 4258                            }
 4259                        })
 4260                        .unzip();
 4261                    let buffer_id = buffer.read(cx).remote_id();
 4262                    let tasks = editor
 4263                        .tasks
 4264                        .get(&(buffer_id, buffer_row))
 4265                        .map(|t| Arc::new(t.to_owned()));
 4266                    if tasks.is_none() && code_actions.is_none() {
 4267                        return None;
 4268                    }
 4269
 4270                    editor.completion_tasks.clear();
 4271                    editor.discard_inline_completion(false, cx);
 4272                    let task_context =
 4273                        tasks
 4274                            .as_ref()
 4275                            .zip(editor.project.clone())
 4276                            .map(|(tasks, project)| {
 4277                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4278                            });
 4279
 4280                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4281                        let task_context = match task_context {
 4282                            Some(task_context) => task_context.await,
 4283                            None => None,
 4284                        };
 4285                        let resolved_tasks =
 4286                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4287                                Rc::new(ResolvedTasks {
 4288                                    templates: tasks.resolve(&task_context).collect(),
 4289                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4290                                        multibuffer_point.row,
 4291                                        tasks.column,
 4292                                    )),
 4293                                })
 4294                            });
 4295                        let spawn_straight_away = resolved_tasks
 4296                            .as_ref()
 4297                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4298                            && code_actions
 4299                                .as_ref()
 4300                                .map_or(true, |actions| actions.is_empty());
 4301                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4302                            *editor.context_menu.borrow_mut() =
 4303                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4304                                    buffer,
 4305                                    actions: CodeActionContents {
 4306                                        tasks: resolved_tasks,
 4307                                        actions: code_actions,
 4308                                    },
 4309                                    selected_item: Default::default(),
 4310                                    scroll_handle: UniformListScrollHandle::default(),
 4311                                    deployed_from_indicator,
 4312                                }));
 4313                            if spawn_straight_away {
 4314                                if let Some(task) = editor.confirm_code_action(
 4315                                    &ConfirmCodeAction { item_ix: Some(0) },
 4316                                    window,
 4317                                    cx,
 4318                                ) {
 4319                                    cx.notify();
 4320                                    return task;
 4321                                }
 4322                            }
 4323                            cx.notify();
 4324                            Task::ready(Ok(()))
 4325                        }) {
 4326                            task.await
 4327                        } else {
 4328                            Ok(())
 4329                        }
 4330                    }))
 4331                } else {
 4332                    Some(Task::ready(Ok(())))
 4333                }
 4334            })?;
 4335            if let Some(task) = spawned_test_task {
 4336                task.await?;
 4337            }
 4338
 4339            Ok::<_, anyhow::Error>(())
 4340        })
 4341        .detach_and_log_err(cx);
 4342    }
 4343
 4344    pub fn confirm_code_action(
 4345        &mut self,
 4346        action: &ConfirmCodeAction,
 4347        window: &mut Window,
 4348        cx: &mut Context<Self>,
 4349    ) -> Option<Task<Result<()>>> {
 4350        let actions_menu =
 4351            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4352                menu
 4353            } else {
 4354                return None;
 4355            };
 4356        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4357        let action = actions_menu.actions.get(action_ix)?;
 4358        let title = action.label();
 4359        let buffer = actions_menu.buffer;
 4360        let workspace = self.workspace()?;
 4361
 4362        match action {
 4363            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4364                workspace.update(cx, |workspace, cx| {
 4365                    workspace::tasks::schedule_resolved_task(
 4366                        workspace,
 4367                        task_source_kind,
 4368                        resolved_task,
 4369                        false,
 4370                        cx,
 4371                    );
 4372
 4373                    Some(Task::ready(Ok(())))
 4374                })
 4375            }
 4376            CodeActionsItem::CodeAction {
 4377                excerpt_id,
 4378                action,
 4379                provider,
 4380            } => {
 4381                let apply_code_action =
 4382                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4383                let workspace = workspace.downgrade();
 4384                Some(cx.spawn_in(window, |editor, cx| async move {
 4385                    let project_transaction = apply_code_action.await?;
 4386                    Self::open_project_transaction(
 4387                        &editor,
 4388                        workspace,
 4389                        project_transaction,
 4390                        title,
 4391                        cx,
 4392                    )
 4393                    .await
 4394                }))
 4395            }
 4396        }
 4397    }
 4398
 4399    pub async fn open_project_transaction(
 4400        this: &WeakEntity<Editor>,
 4401        workspace: WeakEntity<Workspace>,
 4402        transaction: ProjectTransaction,
 4403        title: String,
 4404        mut cx: AsyncWindowContext,
 4405    ) -> Result<()> {
 4406        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4407        cx.update(|_, cx| {
 4408            entries.sort_unstable_by_key(|(buffer, _)| {
 4409                buffer.read(cx).file().map(|f| f.path().clone())
 4410            });
 4411        })?;
 4412
 4413        // If the project transaction's edits are all contained within this editor, then
 4414        // avoid opening a new editor to display them.
 4415
 4416        if let Some((buffer, transaction)) = entries.first() {
 4417            if entries.len() == 1 {
 4418                let excerpt = this.update(&mut cx, |editor, cx| {
 4419                    editor
 4420                        .buffer()
 4421                        .read(cx)
 4422                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4423                })?;
 4424                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4425                    if excerpted_buffer == *buffer {
 4426                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4427                            let excerpt_range = excerpt_range.to_offset(buffer);
 4428                            buffer
 4429                                .edited_ranges_for_transaction::<usize>(transaction)
 4430                                .all(|range| {
 4431                                    excerpt_range.start <= range.start
 4432                                        && excerpt_range.end >= range.end
 4433                                })
 4434                        })?;
 4435
 4436                        if all_edits_within_excerpt {
 4437                            return Ok(());
 4438                        }
 4439                    }
 4440                }
 4441            }
 4442        } else {
 4443            return Ok(());
 4444        }
 4445
 4446        let mut ranges_to_highlight = Vec::new();
 4447        let excerpt_buffer = cx.new(|cx| {
 4448            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4449            for (buffer_handle, transaction) in &entries {
 4450                let buffer = buffer_handle.read(cx);
 4451                ranges_to_highlight.extend(
 4452                    multibuffer.push_excerpts_with_context_lines(
 4453                        buffer_handle.clone(),
 4454                        buffer
 4455                            .edited_ranges_for_transaction::<usize>(transaction)
 4456                            .collect(),
 4457                        DEFAULT_MULTIBUFFER_CONTEXT,
 4458                        cx,
 4459                    ),
 4460                );
 4461            }
 4462            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4463            multibuffer
 4464        })?;
 4465
 4466        workspace.update_in(&mut cx, |workspace, window, cx| {
 4467            let project = workspace.project().clone();
 4468            let editor = cx
 4469                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4470            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4471            editor.update(cx, |editor, cx| {
 4472                editor.highlight_background::<Self>(
 4473                    &ranges_to_highlight,
 4474                    |theme| theme.editor_highlighted_line_background,
 4475                    cx,
 4476                );
 4477            });
 4478        })?;
 4479
 4480        Ok(())
 4481    }
 4482
 4483    pub fn clear_code_action_providers(&mut self) {
 4484        self.code_action_providers.clear();
 4485        self.available_code_actions.take();
 4486    }
 4487
 4488    pub fn add_code_action_provider(
 4489        &mut self,
 4490        provider: Rc<dyn CodeActionProvider>,
 4491        window: &mut Window,
 4492        cx: &mut Context<Self>,
 4493    ) {
 4494        if self
 4495            .code_action_providers
 4496            .iter()
 4497            .any(|existing_provider| existing_provider.id() == provider.id())
 4498        {
 4499            return;
 4500        }
 4501
 4502        self.code_action_providers.push(provider);
 4503        self.refresh_code_actions(window, cx);
 4504    }
 4505
 4506    pub fn remove_code_action_provider(
 4507        &mut self,
 4508        id: Arc<str>,
 4509        window: &mut Window,
 4510        cx: &mut Context<Self>,
 4511    ) {
 4512        self.code_action_providers
 4513            .retain(|provider| provider.id() != id);
 4514        self.refresh_code_actions(window, cx);
 4515    }
 4516
 4517    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4518        let buffer = self.buffer.read(cx);
 4519        let newest_selection = self.selections.newest_anchor().clone();
 4520        if newest_selection.head().diff_base_anchor.is_some() {
 4521            return None;
 4522        }
 4523        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4524        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4525        if start_buffer != end_buffer {
 4526            return None;
 4527        }
 4528
 4529        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4530            cx.background_executor()
 4531                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4532                .await;
 4533
 4534            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4535                let providers = this.code_action_providers.clone();
 4536                let tasks = this
 4537                    .code_action_providers
 4538                    .iter()
 4539                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4540                    .collect::<Vec<_>>();
 4541                (providers, tasks)
 4542            })?;
 4543
 4544            let mut actions = Vec::new();
 4545            for (provider, provider_actions) in
 4546                providers.into_iter().zip(future::join_all(tasks).await)
 4547            {
 4548                if let Some(provider_actions) = provider_actions.log_err() {
 4549                    actions.extend(provider_actions.into_iter().map(|action| {
 4550                        AvailableCodeAction {
 4551                            excerpt_id: newest_selection.start.excerpt_id,
 4552                            action,
 4553                            provider: provider.clone(),
 4554                        }
 4555                    }));
 4556                }
 4557            }
 4558
 4559            this.update(&mut cx, |this, cx| {
 4560                this.available_code_actions = if actions.is_empty() {
 4561                    None
 4562                } else {
 4563                    Some((
 4564                        Location {
 4565                            buffer: start_buffer,
 4566                            range: start..end,
 4567                        },
 4568                        actions.into(),
 4569                    ))
 4570                };
 4571                cx.notify();
 4572            })
 4573        }));
 4574        None
 4575    }
 4576
 4577    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4578        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4579            self.show_git_blame_inline = false;
 4580
 4581            self.show_git_blame_inline_delay_task =
 4582                Some(cx.spawn_in(window, |this, mut cx| async move {
 4583                    cx.background_executor().timer(delay).await;
 4584
 4585                    this.update(&mut cx, |this, cx| {
 4586                        this.show_git_blame_inline = true;
 4587                        cx.notify();
 4588                    })
 4589                    .log_err();
 4590                }));
 4591        }
 4592    }
 4593
 4594    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4595        if self.pending_rename.is_some() {
 4596            return None;
 4597        }
 4598
 4599        let provider = self.semantics_provider.clone()?;
 4600        let buffer = self.buffer.read(cx);
 4601        let newest_selection = self.selections.newest_anchor().clone();
 4602        let cursor_position = newest_selection.head();
 4603        let (cursor_buffer, cursor_buffer_position) =
 4604            buffer.text_anchor_for_position(cursor_position, cx)?;
 4605        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4606        if cursor_buffer != tail_buffer {
 4607            return None;
 4608        }
 4609        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4610        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4611            cx.background_executor()
 4612                .timer(Duration::from_millis(debounce))
 4613                .await;
 4614
 4615            let highlights = if let Some(highlights) = cx
 4616                .update(|cx| {
 4617                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4618                })
 4619                .ok()
 4620                .flatten()
 4621            {
 4622                highlights.await.log_err()
 4623            } else {
 4624                None
 4625            };
 4626
 4627            if let Some(highlights) = highlights {
 4628                this.update(&mut cx, |this, cx| {
 4629                    if this.pending_rename.is_some() {
 4630                        return;
 4631                    }
 4632
 4633                    let buffer_id = cursor_position.buffer_id;
 4634                    let buffer = this.buffer.read(cx);
 4635                    if !buffer
 4636                        .text_anchor_for_position(cursor_position, cx)
 4637                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4638                    {
 4639                        return;
 4640                    }
 4641
 4642                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4643                    let mut write_ranges = Vec::new();
 4644                    let mut read_ranges = Vec::new();
 4645                    for highlight in highlights {
 4646                        for (excerpt_id, excerpt_range) in
 4647                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4648                        {
 4649                            let start = highlight
 4650                                .range
 4651                                .start
 4652                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4653                            let end = highlight
 4654                                .range
 4655                                .end
 4656                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4657                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4658                                continue;
 4659                            }
 4660
 4661                            let range = Anchor {
 4662                                buffer_id,
 4663                                excerpt_id,
 4664                                text_anchor: start,
 4665                                diff_base_anchor: None,
 4666                            }..Anchor {
 4667                                buffer_id,
 4668                                excerpt_id,
 4669                                text_anchor: end,
 4670                                diff_base_anchor: None,
 4671                            };
 4672                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4673                                write_ranges.push(range);
 4674                            } else {
 4675                                read_ranges.push(range);
 4676                            }
 4677                        }
 4678                    }
 4679
 4680                    this.highlight_background::<DocumentHighlightRead>(
 4681                        &read_ranges,
 4682                        |theme| theme.editor_document_highlight_read_background,
 4683                        cx,
 4684                    );
 4685                    this.highlight_background::<DocumentHighlightWrite>(
 4686                        &write_ranges,
 4687                        |theme| theme.editor_document_highlight_write_background,
 4688                        cx,
 4689                    );
 4690                    cx.notify();
 4691                })
 4692                .log_err();
 4693            }
 4694        }));
 4695        None
 4696    }
 4697
 4698    pub fn refresh_inline_completion(
 4699        &mut self,
 4700        debounce: bool,
 4701        user_requested: bool,
 4702        window: &mut Window,
 4703        cx: &mut Context<Self>,
 4704    ) -> Option<()> {
 4705        let provider = self.inline_completion_provider()?;
 4706        let cursor = self.selections.newest_anchor().head();
 4707        let (buffer, cursor_buffer_position) =
 4708            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4709
 4710        if !user_requested
 4711            && (!self.enable_inline_completions
 4712                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4713                || !self.is_focused(window)
 4714                || buffer.read(cx).is_empty())
 4715        {
 4716            self.discard_inline_completion(false, cx);
 4717            return None;
 4718        }
 4719
 4720        self.update_visible_inline_completion(window, cx);
 4721        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4722        Some(())
 4723    }
 4724
 4725    fn cycle_inline_completion(
 4726        &mut self,
 4727        direction: Direction,
 4728        window: &mut Window,
 4729        cx: &mut Context<Self>,
 4730    ) -> Option<()> {
 4731        let provider = self.inline_completion_provider()?;
 4732        let cursor = self.selections.newest_anchor().head();
 4733        let (buffer, cursor_buffer_position) =
 4734            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4735        if !self.enable_inline_completions
 4736            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4737        {
 4738            return None;
 4739        }
 4740
 4741        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4742        self.update_visible_inline_completion(window, cx);
 4743
 4744        Some(())
 4745    }
 4746
 4747    pub fn show_inline_completion(
 4748        &mut self,
 4749        _: &ShowInlineCompletion,
 4750        window: &mut Window,
 4751        cx: &mut Context<Self>,
 4752    ) {
 4753        if !self.has_active_inline_completion() {
 4754            self.refresh_inline_completion(false, true, window, cx);
 4755            return;
 4756        }
 4757
 4758        self.update_visible_inline_completion(window, cx);
 4759    }
 4760
 4761    pub fn display_cursor_names(
 4762        &mut self,
 4763        _: &DisplayCursorNames,
 4764        window: &mut Window,
 4765        cx: &mut Context<Self>,
 4766    ) {
 4767        self.show_cursor_names(window, cx);
 4768    }
 4769
 4770    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4771        self.show_cursor_names = true;
 4772        cx.notify();
 4773        cx.spawn_in(window, |this, mut cx| async move {
 4774            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4775            this.update(&mut cx, |this, cx| {
 4776                this.show_cursor_names = false;
 4777                cx.notify()
 4778            })
 4779            .ok()
 4780        })
 4781        .detach();
 4782    }
 4783
 4784    pub fn next_inline_completion(
 4785        &mut self,
 4786        _: &NextInlineCompletion,
 4787        window: &mut Window,
 4788        cx: &mut Context<Self>,
 4789    ) {
 4790        if self.has_active_inline_completion() {
 4791            self.cycle_inline_completion(Direction::Next, window, cx);
 4792        } else {
 4793            let is_copilot_disabled = self
 4794                .refresh_inline_completion(false, true, window, cx)
 4795                .is_none();
 4796            if is_copilot_disabled {
 4797                cx.propagate();
 4798            }
 4799        }
 4800    }
 4801
 4802    pub fn previous_inline_completion(
 4803        &mut self,
 4804        _: &PreviousInlineCompletion,
 4805        window: &mut Window,
 4806        cx: &mut Context<Self>,
 4807    ) {
 4808        if self.has_active_inline_completion() {
 4809            self.cycle_inline_completion(Direction::Prev, window, cx);
 4810        } else {
 4811            let is_copilot_disabled = self
 4812                .refresh_inline_completion(false, true, window, cx)
 4813                .is_none();
 4814            if is_copilot_disabled {
 4815                cx.propagate();
 4816            }
 4817        }
 4818    }
 4819
 4820    pub fn accept_inline_completion(
 4821        &mut self,
 4822        _: &AcceptInlineCompletion,
 4823        window: &mut Window,
 4824        cx: &mut Context<Self>,
 4825    ) {
 4826        let buffer = self.buffer.read(cx);
 4827        let snapshot = buffer.snapshot(cx);
 4828        let selection = self.selections.newest_adjusted(cx);
 4829        let cursor = selection.head();
 4830        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4831        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4832        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4833        {
 4834            if cursor.column < suggested_indent.len
 4835                && cursor.column <= current_indent.len
 4836                && current_indent.len <= suggested_indent.len
 4837            {
 4838                self.tab(&Default::default(), window, cx);
 4839                return;
 4840            }
 4841        }
 4842
 4843        if self.show_inline_completions_in_menu(cx) {
 4844            self.hide_context_menu(window, cx);
 4845        }
 4846
 4847        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4848            return;
 4849        };
 4850
 4851        self.report_inline_completion_event(true, cx);
 4852
 4853        match &active_inline_completion.completion {
 4854            InlineCompletion::Move(position) => {
 4855                let position = *position;
 4856                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4857                    selections.select_anchor_ranges([position..position]);
 4858                });
 4859            }
 4860            InlineCompletion::Edit { edits, .. } => {
 4861                if let Some(provider) = self.inline_completion_provider() {
 4862                    provider.accept(cx);
 4863                }
 4864
 4865                let snapshot = self.buffer.read(cx).snapshot(cx);
 4866                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4867
 4868                self.buffer.update(cx, |buffer, cx| {
 4869                    buffer.edit(edits.iter().cloned(), None, cx)
 4870                });
 4871
 4872                self.change_selections(None, window, cx, |s| {
 4873                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4874                });
 4875
 4876                self.update_visible_inline_completion(window, cx);
 4877                if self.active_inline_completion.is_none() {
 4878                    self.refresh_inline_completion(true, true, window, cx);
 4879                }
 4880
 4881                cx.notify();
 4882            }
 4883        }
 4884    }
 4885
 4886    pub fn accept_partial_inline_completion(
 4887        &mut self,
 4888        _: &AcceptPartialInlineCompletion,
 4889        window: &mut Window,
 4890        cx: &mut Context<Self>,
 4891    ) {
 4892        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4893            return;
 4894        };
 4895        if self.selections.count() != 1 {
 4896            return;
 4897        }
 4898
 4899        self.report_inline_completion_event(true, cx);
 4900
 4901        match &active_inline_completion.completion {
 4902            InlineCompletion::Move(position) => {
 4903                let position = *position;
 4904                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4905                    selections.select_anchor_ranges([position..position]);
 4906                });
 4907            }
 4908            InlineCompletion::Edit { edits, .. } => {
 4909                // Find an insertion that starts at the cursor position.
 4910                let snapshot = self.buffer.read(cx).snapshot(cx);
 4911                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4912                let insertion = edits.iter().find_map(|(range, text)| {
 4913                    let range = range.to_offset(&snapshot);
 4914                    if range.is_empty() && range.start == cursor_offset {
 4915                        Some(text)
 4916                    } else {
 4917                        None
 4918                    }
 4919                });
 4920
 4921                if let Some(text) = insertion {
 4922                    let mut partial_completion = text
 4923                        .chars()
 4924                        .by_ref()
 4925                        .take_while(|c| c.is_alphabetic())
 4926                        .collect::<String>();
 4927                    if partial_completion.is_empty() {
 4928                        partial_completion = text
 4929                            .chars()
 4930                            .by_ref()
 4931                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4932                            .collect::<String>();
 4933                    }
 4934
 4935                    cx.emit(EditorEvent::InputHandled {
 4936                        utf16_range_to_replace: None,
 4937                        text: partial_completion.clone().into(),
 4938                    });
 4939
 4940                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4941
 4942                    self.refresh_inline_completion(true, true, window, cx);
 4943                    cx.notify();
 4944                } else {
 4945                    self.accept_inline_completion(&Default::default(), window, cx);
 4946                }
 4947            }
 4948        }
 4949    }
 4950
 4951    fn discard_inline_completion(
 4952        &mut self,
 4953        should_report_inline_completion_event: bool,
 4954        cx: &mut Context<Self>,
 4955    ) -> bool {
 4956        if should_report_inline_completion_event {
 4957            self.report_inline_completion_event(false, cx);
 4958        }
 4959
 4960        if let Some(provider) = self.inline_completion_provider() {
 4961            provider.discard(cx);
 4962        }
 4963
 4964        self.take_active_inline_completion(cx).is_some()
 4965    }
 4966
 4967    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4968        let Some(provider) = self.inline_completion_provider() else {
 4969            return;
 4970        };
 4971
 4972        let Some((_, buffer, _)) = self
 4973            .buffer
 4974            .read(cx)
 4975            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4976        else {
 4977            return;
 4978        };
 4979
 4980        let extension = buffer
 4981            .read(cx)
 4982            .file()
 4983            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4984
 4985        let event_type = match accepted {
 4986            true => "Inline Completion Accepted",
 4987            false => "Inline Completion Discarded",
 4988        };
 4989        telemetry::event!(
 4990            event_type,
 4991            provider = provider.name(),
 4992            suggestion_accepted = accepted,
 4993            file_extension = extension,
 4994        );
 4995    }
 4996
 4997    pub fn has_active_inline_completion(&self) -> bool {
 4998        self.active_inline_completion.is_some()
 4999    }
 5000
 5001    fn take_active_inline_completion(
 5002        &mut self,
 5003        cx: &mut Context<Self>,
 5004    ) -> Option<InlineCompletion> {
 5005        let active_inline_completion = self.active_inline_completion.take()?;
 5006        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5007        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5008        Some(active_inline_completion.completion)
 5009    }
 5010
 5011    fn update_visible_inline_completion(
 5012        &mut self,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) -> Option<()> {
 5016        let selection = self.selections.newest_anchor();
 5017        let cursor = selection.head();
 5018        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5019        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5020        let excerpt_id = cursor.excerpt_id;
 5021
 5022        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5023            && (self.context_menu.borrow().is_some()
 5024                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5025        if completions_menu_has_precedence
 5026            || !offset_selection.is_empty()
 5027            || !self.enable_inline_completions
 5028            || self
 5029                .active_inline_completion
 5030                .as_ref()
 5031                .map_or(false, |completion| {
 5032                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5033                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5034                    !invalidation_range.contains(&offset_selection.head())
 5035                })
 5036        {
 5037            self.discard_inline_completion(false, cx);
 5038            return None;
 5039        }
 5040
 5041        self.take_active_inline_completion(cx);
 5042        let provider = self.inline_completion_provider()?;
 5043
 5044        let (buffer, cursor_buffer_position) =
 5045            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5046
 5047        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5048        let edits = inline_completion
 5049            .edits
 5050            .into_iter()
 5051            .flat_map(|(range, new_text)| {
 5052                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5053                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5054                Some((start..end, new_text))
 5055            })
 5056            .collect::<Vec<_>>();
 5057        if edits.is_empty() {
 5058            return None;
 5059        }
 5060
 5061        let first_edit_start = edits.first().unwrap().0.start;
 5062        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5063        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5064
 5065        let last_edit_end = edits.last().unwrap().0.end;
 5066        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5067        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5068
 5069        let cursor_row = cursor.to_point(&multibuffer).row;
 5070
 5071        let mut inlay_ids = Vec::new();
 5072        let invalidation_row_range;
 5073        let completion = if cursor_row < edit_start_row {
 5074            invalidation_row_range = cursor_row..edit_end_row;
 5075            InlineCompletion::Move(first_edit_start)
 5076        } else if cursor_row > edit_end_row {
 5077            invalidation_row_range = edit_start_row..cursor_row;
 5078            InlineCompletion::Move(first_edit_start)
 5079        } else {
 5080            if edits
 5081                .iter()
 5082                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5083            {
 5084                let mut inlays = Vec::new();
 5085                for (range, new_text) in &edits {
 5086                    let inlay = Inlay::inline_completion(
 5087                        post_inc(&mut self.next_inlay_id),
 5088                        range.start,
 5089                        new_text.as_str(),
 5090                    );
 5091                    inlay_ids.push(inlay.id);
 5092                    inlays.push(inlay);
 5093                }
 5094
 5095                self.splice_inlays(vec![], inlays, cx);
 5096            } else {
 5097                let background_color = cx.theme().status().deleted_background;
 5098                self.highlight_text::<InlineCompletionHighlight>(
 5099                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5100                    HighlightStyle {
 5101                        background_color: Some(background_color),
 5102                        ..Default::default()
 5103                    },
 5104                    cx,
 5105                );
 5106            }
 5107
 5108            invalidation_row_range = edit_start_row..edit_end_row;
 5109
 5110            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5111                if provider.show_tab_accept_marker()
 5112                    && first_edit_start_point.row == last_edit_end_point.row
 5113                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 5114                {
 5115                    EditDisplayMode::TabAccept
 5116                } else {
 5117                    EditDisplayMode::Inline
 5118                }
 5119            } else {
 5120                EditDisplayMode::DiffPopover
 5121            };
 5122
 5123            let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5124
 5125            InlineCompletion::Edit {
 5126                edits,
 5127                edit_preview: inline_completion.edit_preview,
 5128                display_mode,
 5129                snapshot,
 5130            }
 5131        };
 5132
 5133        let invalidation_range = multibuffer
 5134            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5135            ..multibuffer.anchor_after(Point::new(
 5136                invalidation_row_range.end,
 5137                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5138            ));
 5139
 5140        self.active_inline_completion = Some(InlineCompletionState {
 5141            inlay_ids,
 5142            completion,
 5143            invalidation_range,
 5144        });
 5145
 5146        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5147            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5148                match self.context_menu.borrow_mut().as_mut() {
 5149                    Some(CodeContextMenu::Completions(menu)) => {
 5150                        menu.show_inline_completion_hint(hint);
 5151                    }
 5152                    _ => {}
 5153                }
 5154            }
 5155        }
 5156
 5157        cx.notify();
 5158
 5159        Some(())
 5160    }
 5161
 5162    fn inline_completion_menu_hint(
 5163        &self,
 5164        window: &mut Window,
 5165        cx: &mut Context<Self>,
 5166    ) -> Option<InlineCompletionMenuHint> {
 5167        let provider = self.inline_completion_provider()?;
 5168        if self.has_active_inline_completion() {
 5169            let editor_snapshot = self.snapshot(window, cx);
 5170
 5171            let text = match &self.active_inline_completion.as_ref()?.completion {
 5172                InlineCompletion::Edit {
 5173                    edits,
 5174                    edit_preview,
 5175                    display_mode: _,
 5176                    snapshot,
 5177                } => edit_preview
 5178                    .as_ref()
 5179                    .and_then(|edit_preview| {
 5180                        inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
 5181                    })
 5182                    .map(InlineCompletionText::Edit),
 5183                InlineCompletion::Move(target) => {
 5184                    let target_point =
 5185                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5186                    let target_line = target_point.row + 1;
 5187                    Some(InlineCompletionText::Move(
 5188                        format!("Jump to edit in line {}", target_line).into(),
 5189                    ))
 5190                }
 5191            };
 5192
 5193            Some(InlineCompletionMenuHint::Loaded { text: text? })
 5194        } else if provider.is_refreshing(cx) {
 5195            Some(InlineCompletionMenuHint::Loading)
 5196        } else if provider.needs_terms_acceptance(cx) {
 5197            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5198        } else {
 5199            Some(InlineCompletionMenuHint::None)
 5200        }
 5201    }
 5202
 5203    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5204        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5205    }
 5206
 5207    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5208        let by_provider = matches!(
 5209            self.menu_inline_completions_policy,
 5210            MenuInlineCompletionsPolicy::ByProvider
 5211        );
 5212
 5213        by_provider
 5214            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5215            && self
 5216                .inline_completion_provider()
 5217                .map_or(false, |provider| provider.show_completions_in_menu())
 5218    }
 5219
 5220    fn render_code_actions_indicator(
 5221        &self,
 5222        _style: &EditorStyle,
 5223        row: DisplayRow,
 5224        is_active: bool,
 5225        cx: &mut Context<Self>,
 5226    ) -> Option<IconButton> {
 5227        if self.available_code_actions.is_some() {
 5228            Some(
 5229                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5230                    .shape(ui::IconButtonShape::Square)
 5231                    .icon_size(IconSize::XSmall)
 5232                    .icon_color(Color::Muted)
 5233                    .toggle_state(is_active)
 5234                    .tooltip({
 5235                        let focus_handle = self.focus_handle.clone();
 5236                        move |window, cx| {
 5237                            Tooltip::for_action_in(
 5238                                "Toggle Code Actions",
 5239                                &ToggleCodeActions {
 5240                                    deployed_from_indicator: None,
 5241                                },
 5242                                &focus_handle,
 5243                                window,
 5244                                cx,
 5245                            )
 5246                        }
 5247                    })
 5248                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5249                        window.focus(&editor.focus_handle(cx));
 5250                        editor.toggle_code_actions(
 5251                            &ToggleCodeActions {
 5252                                deployed_from_indicator: Some(row),
 5253                            },
 5254                            window,
 5255                            cx,
 5256                        );
 5257                    })),
 5258            )
 5259        } else {
 5260            None
 5261        }
 5262    }
 5263
 5264    fn clear_tasks(&mut self) {
 5265        self.tasks.clear()
 5266    }
 5267
 5268    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5269        if self.tasks.insert(key, value).is_some() {
 5270            // This case should hopefully be rare, but just in case...
 5271            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5272        }
 5273    }
 5274
 5275    fn build_tasks_context(
 5276        project: &Entity<Project>,
 5277        buffer: &Entity<Buffer>,
 5278        buffer_row: u32,
 5279        tasks: &Arc<RunnableTasks>,
 5280        cx: &mut Context<Self>,
 5281    ) -> Task<Option<task::TaskContext>> {
 5282        let position = Point::new(buffer_row, tasks.column);
 5283        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5284        let location = Location {
 5285            buffer: buffer.clone(),
 5286            range: range_start..range_start,
 5287        };
 5288        // Fill in the environmental variables from the tree-sitter captures
 5289        let mut captured_task_variables = TaskVariables::default();
 5290        for (capture_name, value) in tasks.extra_variables.clone() {
 5291            captured_task_variables.insert(
 5292                task::VariableName::Custom(capture_name.into()),
 5293                value.clone(),
 5294            );
 5295        }
 5296        project.update(cx, |project, cx| {
 5297            project.task_store().update(cx, |task_store, cx| {
 5298                task_store.task_context_for_location(captured_task_variables, location, cx)
 5299            })
 5300        })
 5301    }
 5302
 5303    pub fn spawn_nearest_task(
 5304        &mut self,
 5305        action: &SpawnNearestTask,
 5306        window: &mut Window,
 5307        cx: &mut Context<Self>,
 5308    ) {
 5309        let Some((workspace, _)) = self.workspace.clone() else {
 5310            return;
 5311        };
 5312        let Some(project) = self.project.clone() else {
 5313            return;
 5314        };
 5315
 5316        // Try to find a closest, enclosing node using tree-sitter that has a
 5317        // task
 5318        let Some((buffer, buffer_row, tasks)) = self
 5319            .find_enclosing_node_task(cx)
 5320            // Or find the task that's closest in row-distance.
 5321            .or_else(|| self.find_closest_task(cx))
 5322        else {
 5323            return;
 5324        };
 5325
 5326        let reveal_strategy = action.reveal;
 5327        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5328        cx.spawn_in(window, |_, mut cx| async move {
 5329            let context = task_context.await?;
 5330            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5331
 5332            let resolved = resolved_task.resolved.as_mut()?;
 5333            resolved.reveal = reveal_strategy;
 5334
 5335            workspace
 5336                .update(&mut cx, |workspace, cx| {
 5337                    workspace::tasks::schedule_resolved_task(
 5338                        workspace,
 5339                        task_source_kind,
 5340                        resolved_task,
 5341                        false,
 5342                        cx,
 5343                    );
 5344                })
 5345                .ok()
 5346        })
 5347        .detach();
 5348    }
 5349
 5350    fn find_closest_task(
 5351        &mut self,
 5352        cx: &mut Context<Self>,
 5353    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5354        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5355
 5356        let ((buffer_id, row), tasks) = self
 5357            .tasks
 5358            .iter()
 5359            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5360
 5361        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5362        let tasks = Arc::new(tasks.to_owned());
 5363        Some((buffer, *row, tasks))
 5364    }
 5365
 5366    fn find_enclosing_node_task(
 5367        &mut self,
 5368        cx: &mut Context<Self>,
 5369    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5370        let snapshot = self.buffer.read(cx).snapshot(cx);
 5371        let offset = self.selections.newest::<usize>(cx).head();
 5372        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5373        let buffer_id = excerpt.buffer().remote_id();
 5374
 5375        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5376        let mut cursor = layer.node().walk();
 5377
 5378        while cursor.goto_first_child_for_byte(offset).is_some() {
 5379            if cursor.node().end_byte() == offset {
 5380                cursor.goto_next_sibling();
 5381            }
 5382        }
 5383
 5384        // Ascend to the smallest ancestor that contains the range and has a task.
 5385        loop {
 5386            let node = cursor.node();
 5387            let node_range = node.byte_range();
 5388            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5389
 5390            // Check if this node contains our offset
 5391            if node_range.start <= offset && node_range.end >= offset {
 5392                // If it contains offset, check for task
 5393                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5394                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5395                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5396                }
 5397            }
 5398
 5399            if !cursor.goto_parent() {
 5400                break;
 5401            }
 5402        }
 5403        None
 5404    }
 5405
 5406    fn render_run_indicator(
 5407        &self,
 5408        _style: &EditorStyle,
 5409        is_active: bool,
 5410        row: DisplayRow,
 5411        cx: &mut Context<Self>,
 5412    ) -> IconButton {
 5413        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5414            .shape(ui::IconButtonShape::Square)
 5415            .icon_size(IconSize::XSmall)
 5416            .icon_color(Color::Muted)
 5417            .toggle_state(is_active)
 5418            .on_click(cx.listener(move |editor, _e, window, cx| {
 5419                window.focus(&editor.focus_handle(cx));
 5420                editor.toggle_code_actions(
 5421                    &ToggleCodeActions {
 5422                        deployed_from_indicator: Some(row),
 5423                    },
 5424                    window,
 5425                    cx,
 5426                );
 5427            }))
 5428    }
 5429
 5430    #[cfg(any(test, feature = "test-support"))]
 5431    pub fn context_menu_visible(&self) -> bool {
 5432        self.context_menu
 5433            .borrow()
 5434            .as_ref()
 5435            .map_or(false, |menu| menu.visible())
 5436    }
 5437
 5438    #[cfg(feature = "test-support")]
 5439    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5440        self.context_menu
 5441            .borrow()
 5442            .as_ref()
 5443            .map_or(false, |menu| match menu {
 5444                CodeContextMenu::Completions(menu) => {
 5445                    menu.entries.borrow().first().map_or(false, |entry| {
 5446                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5447                    })
 5448                }
 5449                CodeContextMenu::CodeActions(_) => false,
 5450            })
 5451    }
 5452
 5453    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5454        self.context_menu
 5455            .borrow()
 5456            .as_ref()
 5457            .map(|menu| menu.origin(cursor_position))
 5458    }
 5459
 5460    fn render_context_menu(
 5461        &self,
 5462        style: &EditorStyle,
 5463        max_height_in_lines: u32,
 5464        y_flipped: bool,
 5465        window: &mut Window,
 5466        cx: &mut Context<Editor>,
 5467    ) -> Option<AnyElement> {
 5468        self.context_menu.borrow().as_ref().and_then(|menu| {
 5469            if menu.visible() {
 5470                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5471            } else {
 5472                None
 5473            }
 5474        })
 5475    }
 5476
 5477    fn render_context_menu_aside(
 5478        &self,
 5479        style: &EditorStyle,
 5480        max_size: Size<Pixels>,
 5481        cx: &mut Context<Editor>,
 5482    ) -> Option<AnyElement> {
 5483        self.context_menu.borrow().as_ref().and_then(|menu| {
 5484            if menu.visible() {
 5485                menu.render_aside(
 5486                    style,
 5487                    max_size,
 5488                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5489                    cx,
 5490                )
 5491            } else {
 5492                None
 5493            }
 5494        })
 5495    }
 5496
 5497    fn hide_context_menu(
 5498        &mut self,
 5499        window: &mut Window,
 5500        cx: &mut Context<Self>,
 5501    ) -> Option<CodeContextMenu> {
 5502        cx.notify();
 5503        self.completion_tasks.clear();
 5504        let context_menu = self.context_menu.borrow_mut().take();
 5505        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5506            self.update_visible_inline_completion(window, cx);
 5507        }
 5508        context_menu
 5509    }
 5510
 5511    fn show_snippet_choices(
 5512        &mut self,
 5513        choices: &Vec<String>,
 5514        selection: Range<Anchor>,
 5515        cx: &mut Context<Self>,
 5516    ) {
 5517        if selection.start.buffer_id.is_none() {
 5518            return;
 5519        }
 5520        let buffer_id = selection.start.buffer_id.unwrap();
 5521        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5522        let id = post_inc(&mut self.next_completion_id);
 5523
 5524        if let Some(buffer) = buffer {
 5525            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5526                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5527            ));
 5528        }
 5529    }
 5530
 5531    pub fn insert_snippet(
 5532        &mut self,
 5533        insertion_ranges: &[Range<usize>],
 5534        snippet: Snippet,
 5535        window: &mut Window,
 5536        cx: &mut Context<Self>,
 5537    ) -> Result<()> {
 5538        struct Tabstop<T> {
 5539            is_end_tabstop: bool,
 5540            ranges: Vec<Range<T>>,
 5541            choices: Option<Vec<String>>,
 5542        }
 5543
 5544        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5545            let snippet_text: Arc<str> = snippet.text.clone().into();
 5546            buffer.edit(
 5547                insertion_ranges
 5548                    .iter()
 5549                    .cloned()
 5550                    .map(|range| (range, snippet_text.clone())),
 5551                Some(AutoindentMode::EachLine),
 5552                cx,
 5553            );
 5554
 5555            let snapshot = &*buffer.read(cx);
 5556            let snippet = &snippet;
 5557            snippet
 5558                .tabstops
 5559                .iter()
 5560                .map(|tabstop| {
 5561                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5562                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5563                    });
 5564                    let mut tabstop_ranges = tabstop
 5565                        .ranges
 5566                        .iter()
 5567                        .flat_map(|tabstop_range| {
 5568                            let mut delta = 0_isize;
 5569                            insertion_ranges.iter().map(move |insertion_range| {
 5570                                let insertion_start = insertion_range.start as isize + delta;
 5571                                delta +=
 5572                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5573
 5574                                let start = ((insertion_start + tabstop_range.start) as usize)
 5575                                    .min(snapshot.len());
 5576                                let end = ((insertion_start + tabstop_range.end) as usize)
 5577                                    .min(snapshot.len());
 5578                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5579                            })
 5580                        })
 5581                        .collect::<Vec<_>>();
 5582                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5583
 5584                    Tabstop {
 5585                        is_end_tabstop,
 5586                        ranges: tabstop_ranges,
 5587                        choices: tabstop.choices.clone(),
 5588                    }
 5589                })
 5590                .collect::<Vec<_>>()
 5591        });
 5592        if let Some(tabstop) = tabstops.first() {
 5593            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5594                s.select_ranges(tabstop.ranges.iter().cloned());
 5595            });
 5596
 5597            if let Some(choices) = &tabstop.choices {
 5598                if let Some(selection) = tabstop.ranges.first() {
 5599                    self.show_snippet_choices(choices, selection.clone(), cx)
 5600                }
 5601            }
 5602
 5603            // If we're already at the last tabstop and it's at the end of the snippet,
 5604            // we're done, we don't need to keep the state around.
 5605            if !tabstop.is_end_tabstop {
 5606                let choices = tabstops
 5607                    .iter()
 5608                    .map(|tabstop| tabstop.choices.clone())
 5609                    .collect();
 5610
 5611                let ranges = tabstops
 5612                    .into_iter()
 5613                    .map(|tabstop| tabstop.ranges)
 5614                    .collect::<Vec<_>>();
 5615
 5616                self.snippet_stack.push(SnippetState {
 5617                    active_index: 0,
 5618                    ranges,
 5619                    choices,
 5620                });
 5621            }
 5622
 5623            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5624            if self.autoclose_regions.is_empty() {
 5625                let snapshot = self.buffer.read(cx).snapshot(cx);
 5626                for selection in &mut self.selections.all::<Point>(cx) {
 5627                    let selection_head = selection.head();
 5628                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5629                        continue;
 5630                    };
 5631
 5632                    let mut bracket_pair = None;
 5633                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5634                    let prev_chars = snapshot
 5635                        .reversed_chars_at(selection_head)
 5636                        .collect::<String>();
 5637                    for (pair, enabled) in scope.brackets() {
 5638                        if enabled
 5639                            && pair.close
 5640                            && prev_chars.starts_with(pair.start.as_str())
 5641                            && next_chars.starts_with(pair.end.as_str())
 5642                        {
 5643                            bracket_pair = Some(pair.clone());
 5644                            break;
 5645                        }
 5646                    }
 5647                    if let Some(pair) = bracket_pair {
 5648                        let start = snapshot.anchor_after(selection_head);
 5649                        let end = snapshot.anchor_after(selection_head);
 5650                        self.autoclose_regions.push(AutocloseRegion {
 5651                            selection_id: selection.id,
 5652                            range: start..end,
 5653                            pair,
 5654                        });
 5655                    }
 5656                }
 5657            }
 5658        }
 5659        Ok(())
 5660    }
 5661
 5662    pub fn move_to_next_snippet_tabstop(
 5663        &mut self,
 5664        window: &mut Window,
 5665        cx: &mut Context<Self>,
 5666    ) -> bool {
 5667        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5668    }
 5669
 5670    pub fn move_to_prev_snippet_tabstop(
 5671        &mut self,
 5672        window: &mut Window,
 5673        cx: &mut Context<Self>,
 5674    ) -> bool {
 5675        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5676    }
 5677
 5678    pub fn move_to_snippet_tabstop(
 5679        &mut self,
 5680        bias: Bias,
 5681        window: &mut Window,
 5682        cx: &mut Context<Self>,
 5683    ) -> bool {
 5684        if let Some(mut snippet) = self.snippet_stack.pop() {
 5685            match bias {
 5686                Bias::Left => {
 5687                    if snippet.active_index > 0 {
 5688                        snippet.active_index -= 1;
 5689                    } else {
 5690                        self.snippet_stack.push(snippet);
 5691                        return false;
 5692                    }
 5693                }
 5694                Bias::Right => {
 5695                    if snippet.active_index + 1 < snippet.ranges.len() {
 5696                        snippet.active_index += 1;
 5697                    } else {
 5698                        self.snippet_stack.push(snippet);
 5699                        return false;
 5700                    }
 5701                }
 5702            }
 5703            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5704                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5705                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5706                });
 5707
 5708                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5709                    if let Some(selection) = current_ranges.first() {
 5710                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5711                    }
 5712                }
 5713
 5714                // If snippet state is not at the last tabstop, push it back on the stack
 5715                if snippet.active_index + 1 < snippet.ranges.len() {
 5716                    self.snippet_stack.push(snippet);
 5717                }
 5718                return true;
 5719            }
 5720        }
 5721
 5722        false
 5723    }
 5724
 5725    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5726        self.transact(window, cx, |this, window, cx| {
 5727            this.select_all(&SelectAll, window, cx);
 5728            this.insert("", window, cx);
 5729        });
 5730    }
 5731
 5732    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5733        self.transact(window, cx, |this, window, cx| {
 5734            this.select_autoclose_pair(window, cx);
 5735            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5736            if !this.linked_edit_ranges.is_empty() {
 5737                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5738                let snapshot = this.buffer.read(cx).snapshot(cx);
 5739
 5740                for selection in selections.iter() {
 5741                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5742                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5743                    if selection_start.buffer_id != selection_end.buffer_id {
 5744                        continue;
 5745                    }
 5746                    if let Some(ranges) =
 5747                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5748                    {
 5749                        for (buffer, entries) in ranges {
 5750                            linked_ranges.entry(buffer).or_default().extend(entries);
 5751                        }
 5752                    }
 5753                }
 5754            }
 5755
 5756            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5757            if !this.selections.line_mode {
 5758                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5759                for selection in &mut selections {
 5760                    if selection.is_empty() {
 5761                        let old_head = selection.head();
 5762                        let mut new_head =
 5763                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5764                                .to_point(&display_map);
 5765                        if let Some((buffer, line_buffer_range)) = display_map
 5766                            .buffer_snapshot
 5767                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5768                        {
 5769                            let indent_size =
 5770                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5771                            let indent_len = match indent_size.kind {
 5772                                IndentKind::Space => {
 5773                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5774                                }
 5775                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5776                            };
 5777                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5778                                let indent_len = indent_len.get();
 5779                                new_head = cmp::min(
 5780                                    new_head,
 5781                                    MultiBufferPoint::new(
 5782                                        old_head.row,
 5783                                        ((old_head.column - 1) / indent_len) * indent_len,
 5784                                    ),
 5785                                );
 5786                            }
 5787                        }
 5788
 5789                        selection.set_head(new_head, SelectionGoal::None);
 5790                    }
 5791                }
 5792            }
 5793
 5794            this.signature_help_state.set_backspace_pressed(true);
 5795            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5796                s.select(selections)
 5797            });
 5798            this.insert("", window, cx);
 5799            let empty_str: Arc<str> = Arc::from("");
 5800            for (buffer, edits) in linked_ranges {
 5801                let snapshot = buffer.read(cx).snapshot();
 5802                use text::ToPoint as TP;
 5803
 5804                let edits = edits
 5805                    .into_iter()
 5806                    .map(|range| {
 5807                        let end_point = TP::to_point(&range.end, &snapshot);
 5808                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5809
 5810                        if end_point == start_point {
 5811                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5812                                .saturating_sub(1);
 5813                            start_point =
 5814                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5815                        };
 5816
 5817                        (start_point..end_point, empty_str.clone())
 5818                    })
 5819                    .sorted_by_key(|(range, _)| range.start)
 5820                    .collect::<Vec<_>>();
 5821                buffer.update(cx, |this, cx| {
 5822                    this.edit(edits, None, cx);
 5823                })
 5824            }
 5825            this.refresh_inline_completion(true, false, window, cx);
 5826            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5827        });
 5828    }
 5829
 5830    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5831        self.transact(window, cx, |this, window, cx| {
 5832            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5833                let line_mode = s.line_mode;
 5834                s.move_with(|map, selection| {
 5835                    if selection.is_empty() && !line_mode {
 5836                        let cursor = movement::right(map, selection.head());
 5837                        selection.end = cursor;
 5838                        selection.reversed = true;
 5839                        selection.goal = SelectionGoal::None;
 5840                    }
 5841                })
 5842            });
 5843            this.insert("", window, cx);
 5844            this.refresh_inline_completion(true, false, window, cx);
 5845        });
 5846    }
 5847
 5848    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5849        if self.move_to_prev_snippet_tabstop(window, cx) {
 5850            return;
 5851        }
 5852
 5853        self.outdent(&Outdent, window, cx);
 5854    }
 5855
 5856    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5857        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5858            return;
 5859        }
 5860
 5861        let mut selections = self.selections.all_adjusted(cx);
 5862        let buffer = self.buffer.read(cx);
 5863        let snapshot = buffer.snapshot(cx);
 5864        let rows_iter = selections.iter().map(|s| s.head().row);
 5865        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5866
 5867        let mut edits = Vec::new();
 5868        let mut prev_edited_row = 0;
 5869        let mut row_delta = 0;
 5870        for selection in &mut selections {
 5871            if selection.start.row != prev_edited_row {
 5872                row_delta = 0;
 5873            }
 5874            prev_edited_row = selection.end.row;
 5875
 5876            // If the selection is non-empty, then increase the indentation of the selected lines.
 5877            if !selection.is_empty() {
 5878                row_delta =
 5879                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5880                continue;
 5881            }
 5882
 5883            // If the selection is empty and the cursor is in the leading whitespace before the
 5884            // suggested indentation, then auto-indent the line.
 5885            let cursor = selection.head();
 5886            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5887            if let Some(suggested_indent) =
 5888                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5889            {
 5890                if cursor.column < suggested_indent.len
 5891                    && cursor.column <= current_indent.len
 5892                    && current_indent.len <= suggested_indent.len
 5893                {
 5894                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5895                    selection.end = selection.start;
 5896                    if row_delta == 0 {
 5897                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5898                            cursor.row,
 5899                            current_indent,
 5900                            suggested_indent,
 5901                        ));
 5902                        row_delta = suggested_indent.len - current_indent.len;
 5903                    }
 5904                    continue;
 5905                }
 5906            }
 5907
 5908            // Otherwise, insert a hard or soft tab.
 5909            let settings = buffer.settings_at(cursor, cx);
 5910            let tab_size = if settings.hard_tabs {
 5911                IndentSize::tab()
 5912            } else {
 5913                let tab_size = settings.tab_size.get();
 5914                let char_column = snapshot
 5915                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5916                    .flat_map(str::chars)
 5917                    .count()
 5918                    + row_delta as usize;
 5919                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5920                IndentSize::spaces(chars_to_next_tab_stop)
 5921            };
 5922            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5923            selection.end = selection.start;
 5924            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5925            row_delta += tab_size.len;
 5926        }
 5927
 5928        self.transact(window, cx, |this, window, cx| {
 5929            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5930            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5931                s.select(selections)
 5932            });
 5933            this.refresh_inline_completion(true, false, window, cx);
 5934        });
 5935    }
 5936
 5937    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5938        if self.read_only(cx) {
 5939            return;
 5940        }
 5941        let mut selections = self.selections.all::<Point>(cx);
 5942        let mut prev_edited_row = 0;
 5943        let mut row_delta = 0;
 5944        let mut edits = Vec::new();
 5945        let buffer = self.buffer.read(cx);
 5946        let snapshot = buffer.snapshot(cx);
 5947        for selection in &mut selections {
 5948            if selection.start.row != prev_edited_row {
 5949                row_delta = 0;
 5950            }
 5951            prev_edited_row = selection.end.row;
 5952
 5953            row_delta =
 5954                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5955        }
 5956
 5957        self.transact(window, cx, |this, window, cx| {
 5958            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5959            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5960                s.select(selections)
 5961            });
 5962        });
 5963    }
 5964
 5965    fn indent_selection(
 5966        buffer: &MultiBuffer,
 5967        snapshot: &MultiBufferSnapshot,
 5968        selection: &mut Selection<Point>,
 5969        edits: &mut Vec<(Range<Point>, String)>,
 5970        delta_for_start_row: u32,
 5971        cx: &App,
 5972    ) -> u32 {
 5973        let settings = buffer.settings_at(selection.start, cx);
 5974        let tab_size = settings.tab_size.get();
 5975        let indent_kind = if settings.hard_tabs {
 5976            IndentKind::Tab
 5977        } else {
 5978            IndentKind::Space
 5979        };
 5980        let mut start_row = selection.start.row;
 5981        let mut end_row = selection.end.row + 1;
 5982
 5983        // If a selection ends at the beginning of a line, don't indent
 5984        // that last line.
 5985        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5986            end_row -= 1;
 5987        }
 5988
 5989        // Avoid re-indenting a row that has already been indented by a
 5990        // previous selection, but still update this selection's column
 5991        // to reflect that indentation.
 5992        if delta_for_start_row > 0 {
 5993            start_row += 1;
 5994            selection.start.column += delta_for_start_row;
 5995            if selection.end.row == selection.start.row {
 5996                selection.end.column += delta_for_start_row;
 5997            }
 5998        }
 5999
 6000        let mut delta_for_end_row = 0;
 6001        let has_multiple_rows = start_row + 1 != end_row;
 6002        for row in start_row..end_row {
 6003            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6004            let indent_delta = match (current_indent.kind, indent_kind) {
 6005                (IndentKind::Space, IndentKind::Space) => {
 6006                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6007                    IndentSize::spaces(columns_to_next_tab_stop)
 6008                }
 6009                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6010                (_, IndentKind::Tab) => IndentSize::tab(),
 6011            };
 6012
 6013            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6014                0
 6015            } else {
 6016                selection.start.column
 6017            };
 6018            let row_start = Point::new(row, start);
 6019            edits.push((
 6020                row_start..row_start,
 6021                indent_delta.chars().collect::<String>(),
 6022            ));
 6023
 6024            // Update this selection's endpoints to reflect the indentation.
 6025            if row == selection.start.row {
 6026                selection.start.column += indent_delta.len;
 6027            }
 6028            if row == selection.end.row {
 6029                selection.end.column += indent_delta.len;
 6030                delta_for_end_row = indent_delta.len;
 6031            }
 6032        }
 6033
 6034        if selection.start.row == selection.end.row {
 6035            delta_for_start_row + delta_for_end_row
 6036        } else {
 6037            delta_for_end_row
 6038        }
 6039    }
 6040
 6041    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6042        if self.read_only(cx) {
 6043            return;
 6044        }
 6045        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6046        let selections = self.selections.all::<Point>(cx);
 6047        let mut deletion_ranges = Vec::new();
 6048        let mut last_outdent = None;
 6049        {
 6050            let buffer = self.buffer.read(cx);
 6051            let snapshot = buffer.snapshot(cx);
 6052            for selection in &selections {
 6053                let settings = buffer.settings_at(selection.start, cx);
 6054                let tab_size = settings.tab_size.get();
 6055                let mut rows = selection.spanned_rows(false, &display_map);
 6056
 6057                // Avoid re-outdenting a row that has already been outdented by a
 6058                // previous selection.
 6059                if let Some(last_row) = last_outdent {
 6060                    if last_row == rows.start {
 6061                        rows.start = rows.start.next_row();
 6062                    }
 6063                }
 6064                let has_multiple_rows = rows.len() > 1;
 6065                for row in rows.iter_rows() {
 6066                    let indent_size = snapshot.indent_size_for_line(row);
 6067                    if indent_size.len > 0 {
 6068                        let deletion_len = match indent_size.kind {
 6069                            IndentKind::Space => {
 6070                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6071                                if columns_to_prev_tab_stop == 0 {
 6072                                    tab_size
 6073                                } else {
 6074                                    columns_to_prev_tab_stop
 6075                                }
 6076                            }
 6077                            IndentKind::Tab => 1,
 6078                        };
 6079                        let start = if has_multiple_rows
 6080                            || deletion_len > selection.start.column
 6081                            || indent_size.len < selection.start.column
 6082                        {
 6083                            0
 6084                        } else {
 6085                            selection.start.column - deletion_len
 6086                        };
 6087                        deletion_ranges.push(
 6088                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6089                        );
 6090                        last_outdent = Some(row);
 6091                    }
 6092                }
 6093            }
 6094        }
 6095
 6096        self.transact(window, cx, |this, window, cx| {
 6097            this.buffer.update(cx, |buffer, cx| {
 6098                let empty_str: Arc<str> = Arc::default();
 6099                buffer.edit(
 6100                    deletion_ranges
 6101                        .into_iter()
 6102                        .map(|range| (range, empty_str.clone())),
 6103                    None,
 6104                    cx,
 6105                );
 6106            });
 6107            let selections = this.selections.all::<usize>(cx);
 6108            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6109                s.select(selections)
 6110            });
 6111        });
 6112    }
 6113
 6114    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6115        if self.read_only(cx) {
 6116            return;
 6117        }
 6118        let selections = self
 6119            .selections
 6120            .all::<usize>(cx)
 6121            .into_iter()
 6122            .map(|s| s.range());
 6123
 6124        self.transact(window, cx, |this, window, cx| {
 6125            this.buffer.update(cx, |buffer, cx| {
 6126                buffer.autoindent_ranges(selections, cx);
 6127            });
 6128            let selections = this.selections.all::<usize>(cx);
 6129            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6130                s.select(selections)
 6131            });
 6132        });
 6133    }
 6134
 6135    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6136        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6137        let selections = self.selections.all::<Point>(cx);
 6138
 6139        let mut new_cursors = Vec::new();
 6140        let mut edit_ranges = Vec::new();
 6141        let mut selections = selections.iter().peekable();
 6142        while let Some(selection) = selections.next() {
 6143            let mut rows = selection.spanned_rows(false, &display_map);
 6144            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6145
 6146            // Accumulate contiguous regions of rows that we want to delete.
 6147            while let Some(next_selection) = selections.peek() {
 6148                let next_rows = next_selection.spanned_rows(false, &display_map);
 6149                if next_rows.start <= rows.end {
 6150                    rows.end = next_rows.end;
 6151                    selections.next().unwrap();
 6152                } else {
 6153                    break;
 6154                }
 6155            }
 6156
 6157            let buffer = &display_map.buffer_snapshot;
 6158            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6159            let edit_end;
 6160            let cursor_buffer_row;
 6161            if buffer.max_point().row >= rows.end.0 {
 6162                // If there's a line after the range, delete the \n from the end of the row range
 6163                // and position the cursor on the next line.
 6164                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6165                cursor_buffer_row = rows.end;
 6166            } else {
 6167                // If there isn't a line after the range, delete the \n from the line before the
 6168                // start of the row range and position the cursor there.
 6169                edit_start = edit_start.saturating_sub(1);
 6170                edit_end = buffer.len();
 6171                cursor_buffer_row = rows.start.previous_row();
 6172            }
 6173
 6174            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6175            *cursor.column_mut() =
 6176                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6177
 6178            new_cursors.push((
 6179                selection.id,
 6180                buffer.anchor_after(cursor.to_point(&display_map)),
 6181            ));
 6182            edit_ranges.push(edit_start..edit_end);
 6183        }
 6184
 6185        self.transact(window, cx, |this, window, cx| {
 6186            let buffer = this.buffer.update(cx, |buffer, cx| {
 6187                let empty_str: Arc<str> = Arc::default();
 6188                buffer.edit(
 6189                    edit_ranges
 6190                        .into_iter()
 6191                        .map(|range| (range, empty_str.clone())),
 6192                    None,
 6193                    cx,
 6194                );
 6195                buffer.snapshot(cx)
 6196            });
 6197            let new_selections = new_cursors
 6198                .into_iter()
 6199                .map(|(id, cursor)| {
 6200                    let cursor = cursor.to_point(&buffer);
 6201                    Selection {
 6202                        id,
 6203                        start: cursor,
 6204                        end: cursor,
 6205                        reversed: false,
 6206                        goal: SelectionGoal::None,
 6207                    }
 6208                })
 6209                .collect();
 6210
 6211            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6212                s.select(new_selections);
 6213            });
 6214        });
 6215    }
 6216
 6217    pub fn join_lines_impl(
 6218        &mut self,
 6219        insert_whitespace: bool,
 6220        window: &mut Window,
 6221        cx: &mut Context<Self>,
 6222    ) {
 6223        if self.read_only(cx) {
 6224            return;
 6225        }
 6226        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6227        for selection in self.selections.all::<Point>(cx) {
 6228            let start = MultiBufferRow(selection.start.row);
 6229            // Treat single line selections as if they include the next line. Otherwise this action
 6230            // would do nothing for single line selections individual cursors.
 6231            let end = if selection.start.row == selection.end.row {
 6232                MultiBufferRow(selection.start.row + 1)
 6233            } else {
 6234                MultiBufferRow(selection.end.row)
 6235            };
 6236
 6237            if let Some(last_row_range) = row_ranges.last_mut() {
 6238                if start <= last_row_range.end {
 6239                    last_row_range.end = end;
 6240                    continue;
 6241                }
 6242            }
 6243            row_ranges.push(start..end);
 6244        }
 6245
 6246        let snapshot = self.buffer.read(cx).snapshot(cx);
 6247        let mut cursor_positions = Vec::new();
 6248        for row_range in &row_ranges {
 6249            let anchor = snapshot.anchor_before(Point::new(
 6250                row_range.end.previous_row().0,
 6251                snapshot.line_len(row_range.end.previous_row()),
 6252            ));
 6253            cursor_positions.push(anchor..anchor);
 6254        }
 6255
 6256        self.transact(window, cx, |this, window, cx| {
 6257            for row_range in row_ranges.into_iter().rev() {
 6258                for row in row_range.iter_rows().rev() {
 6259                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6260                    let next_line_row = row.next_row();
 6261                    let indent = snapshot.indent_size_for_line(next_line_row);
 6262                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6263
 6264                    let replace =
 6265                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6266                            " "
 6267                        } else {
 6268                            ""
 6269                        };
 6270
 6271                    this.buffer.update(cx, |buffer, cx| {
 6272                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6273                    });
 6274                }
 6275            }
 6276
 6277            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6278                s.select_anchor_ranges(cursor_positions)
 6279            });
 6280        });
 6281    }
 6282
 6283    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6284        self.join_lines_impl(true, window, cx);
 6285    }
 6286
 6287    pub fn sort_lines_case_sensitive(
 6288        &mut self,
 6289        _: &SortLinesCaseSensitive,
 6290        window: &mut Window,
 6291        cx: &mut Context<Self>,
 6292    ) {
 6293        self.manipulate_lines(window, cx, |lines| lines.sort())
 6294    }
 6295
 6296    pub fn sort_lines_case_insensitive(
 6297        &mut self,
 6298        _: &SortLinesCaseInsensitive,
 6299        window: &mut Window,
 6300        cx: &mut Context<Self>,
 6301    ) {
 6302        self.manipulate_lines(window, cx, |lines| {
 6303            lines.sort_by_key(|line| line.to_lowercase())
 6304        })
 6305    }
 6306
 6307    pub fn unique_lines_case_insensitive(
 6308        &mut self,
 6309        _: &UniqueLinesCaseInsensitive,
 6310        window: &mut Window,
 6311        cx: &mut Context<Self>,
 6312    ) {
 6313        self.manipulate_lines(window, cx, |lines| {
 6314            let mut seen = HashSet::default();
 6315            lines.retain(|line| seen.insert(line.to_lowercase()));
 6316        })
 6317    }
 6318
 6319    pub fn unique_lines_case_sensitive(
 6320        &mut self,
 6321        _: &UniqueLinesCaseSensitive,
 6322        window: &mut Window,
 6323        cx: &mut Context<Self>,
 6324    ) {
 6325        self.manipulate_lines(window, cx, |lines| {
 6326            let mut seen = HashSet::default();
 6327            lines.retain(|line| seen.insert(*line));
 6328        })
 6329    }
 6330
 6331    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6332        let mut revert_changes = HashMap::default();
 6333        let snapshot = self.snapshot(window, cx);
 6334        for hunk in snapshot
 6335            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6336        {
 6337            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6338        }
 6339        if !revert_changes.is_empty() {
 6340            self.transact(window, cx, |editor, window, cx| {
 6341                editor.revert(revert_changes, window, cx);
 6342            });
 6343        }
 6344    }
 6345
 6346    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6347        let Some(project) = self.project.clone() else {
 6348            return;
 6349        };
 6350        self.reload(project, window, cx)
 6351            .detach_and_notify_err(window, cx);
 6352    }
 6353
 6354    pub fn revert_selected_hunks(
 6355        &mut self,
 6356        _: &RevertSelectedHunks,
 6357        window: &mut Window,
 6358        cx: &mut Context<Self>,
 6359    ) {
 6360        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6361        self.revert_hunks_in_ranges(selections, window, cx);
 6362    }
 6363
 6364    fn revert_hunks_in_ranges(
 6365        &mut self,
 6366        ranges: impl Iterator<Item = Range<Point>>,
 6367        window: &mut Window,
 6368        cx: &mut Context<Editor>,
 6369    ) {
 6370        let mut revert_changes = HashMap::default();
 6371        let snapshot = self.snapshot(window, cx);
 6372        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6373            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6374        }
 6375        if !revert_changes.is_empty() {
 6376            self.transact(window, cx, |editor, window, cx| {
 6377                editor.revert(revert_changes, window, cx);
 6378            });
 6379        }
 6380    }
 6381
 6382    pub fn open_active_item_in_terminal(
 6383        &mut self,
 6384        _: &OpenInTerminal,
 6385        window: &mut Window,
 6386        cx: &mut Context<Self>,
 6387    ) {
 6388        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6389            let project_path = buffer.read(cx).project_path(cx)?;
 6390            let project = self.project.as_ref()?.read(cx);
 6391            let entry = project.entry_for_path(&project_path, cx)?;
 6392            let parent = match &entry.canonical_path {
 6393                Some(canonical_path) => canonical_path.to_path_buf(),
 6394                None => project.absolute_path(&project_path, cx)?,
 6395            }
 6396            .parent()?
 6397            .to_path_buf();
 6398            Some(parent)
 6399        }) {
 6400            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6401        }
 6402    }
 6403
 6404    pub fn prepare_revert_change(
 6405        &self,
 6406        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6407        hunk: &MultiBufferDiffHunk,
 6408        cx: &mut App,
 6409    ) -> Option<()> {
 6410        let buffer = self.buffer.read(cx);
 6411        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6412        let buffer = buffer.buffer(hunk.buffer_id)?;
 6413        let buffer = buffer.read(cx);
 6414        let original_text = change_set
 6415            .read(cx)
 6416            .base_text
 6417            .as_ref()?
 6418            .as_rope()
 6419            .slice(hunk.diff_base_byte_range.clone());
 6420        let buffer_snapshot = buffer.snapshot();
 6421        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6422        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6423            probe
 6424                .0
 6425                .start
 6426                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6427                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6428        }) {
 6429            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6430            Some(())
 6431        } else {
 6432            None
 6433        }
 6434    }
 6435
 6436    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6437        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6438    }
 6439
 6440    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6441        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6442    }
 6443
 6444    fn manipulate_lines<Fn>(
 6445        &mut self,
 6446        window: &mut Window,
 6447        cx: &mut Context<Self>,
 6448        mut callback: Fn,
 6449    ) where
 6450        Fn: FnMut(&mut Vec<&str>),
 6451    {
 6452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6453        let buffer = self.buffer.read(cx).snapshot(cx);
 6454
 6455        let mut edits = Vec::new();
 6456
 6457        let selections = self.selections.all::<Point>(cx);
 6458        let mut selections = selections.iter().peekable();
 6459        let mut contiguous_row_selections = Vec::new();
 6460        let mut new_selections = Vec::new();
 6461        let mut added_lines = 0;
 6462        let mut removed_lines = 0;
 6463
 6464        while let Some(selection) = selections.next() {
 6465            let (start_row, end_row) = consume_contiguous_rows(
 6466                &mut contiguous_row_selections,
 6467                selection,
 6468                &display_map,
 6469                &mut selections,
 6470            );
 6471
 6472            let start_point = Point::new(start_row.0, 0);
 6473            let end_point = Point::new(
 6474                end_row.previous_row().0,
 6475                buffer.line_len(end_row.previous_row()),
 6476            );
 6477            let text = buffer
 6478                .text_for_range(start_point..end_point)
 6479                .collect::<String>();
 6480
 6481            let mut lines = text.split('\n').collect_vec();
 6482
 6483            let lines_before = lines.len();
 6484            callback(&mut lines);
 6485            let lines_after = lines.len();
 6486
 6487            edits.push((start_point..end_point, lines.join("\n")));
 6488
 6489            // Selections must change based on added and removed line count
 6490            let start_row =
 6491                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6492            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6493            new_selections.push(Selection {
 6494                id: selection.id,
 6495                start: start_row,
 6496                end: end_row,
 6497                goal: SelectionGoal::None,
 6498                reversed: selection.reversed,
 6499            });
 6500
 6501            if lines_after > lines_before {
 6502                added_lines += lines_after - lines_before;
 6503            } else if lines_before > lines_after {
 6504                removed_lines += lines_before - lines_after;
 6505            }
 6506        }
 6507
 6508        self.transact(window, cx, |this, window, cx| {
 6509            let buffer = this.buffer.update(cx, |buffer, cx| {
 6510                buffer.edit(edits, None, cx);
 6511                buffer.snapshot(cx)
 6512            });
 6513
 6514            // Recalculate offsets on newly edited buffer
 6515            let new_selections = new_selections
 6516                .iter()
 6517                .map(|s| {
 6518                    let start_point = Point::new(s.start.0, 0);
 6519                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6520                    Selection {
 6521                        id: s.id,
 6522                        start: buffer.point_to_offset(start_point),
 6523                        end: buffer.point_to_offset(end_point),
 6524                        goal: s.goal,
 6525                        reversed: s.reversed,
 6526                    }
 6527                })
 6528                .collect();
 6529
 6530            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6531                s.select(new_selections);
 6532            });
 6533
 6534            this.request_autoscroll(Autoscroll::fit(), cx);
 6535        });
 6536    }
 6537
 6538    pub fn convert_to_upper_case(
 6539        &mut self,
 6540        _: &ConvertToUpperCase,
 6541        window: &mut Window,
 6542        cx: &mut Context<Self>,
 6543    ) {
 6544        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6545    }
 6546
 6547    pub fn convert_to_lower_case(
 6548        &mut self,
 6549        _: &ConvertToLowerCase,
 6550        window: &mut Window,
 6551        cx: &mut Context<Self>,
 6552    ) {
 6553        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6554    }
 6555
 6556    pub fn convert_to_title_case(
 6557        &mut self,
 6558        _: &ConvertToTitleCase,
 6559        window: &mut Window,
 6560        cx: &mut Context<Self>,
 6561    ) {
 6562        self.manipulate_text(window, cx, |text| {
 6563            text.split('\n')
 6564                .map(|line| line.to_case(Case::Title))
 6565                .join("\n")
 6566        })
 6567    }
 6568
 6569    pub fn convert_to_snake_case(
 6570        &mut self,
 6571        _: &ConvertToSnakeCase,
 6572        window: &mut Window,
 6573        cx: &mut Context<Self>,
 6574    ) {
 6575        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6576    }
 6577
 6578    pub fn convert_to_kebab_case(
 6579        &mut self,
 6580        _: &ConvertToKebabCase,
 6581        window: &mut Window,
 6582        cx: &mut Context<Self>,
 6583    ) {
 6584        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6585    }
 6586
 6587    pub fn convert_to_upper_camel_case(
 6588        &mut self,
 6589        _: &ConvertToUpperCamelCase,
 6590        window: &mut Window,
 6591        cx: &mut Context<Self>,
 6592    ) {
 6593        self.manipulate_text(window, cx, |text| {
 6594            text.split('\n')
 6595                .map(|line| line.to_case(Case::UpperCamel))
 6596                .join("\n")
 6597        })
 6598    }
 6599
 6600    pub fn convert_to_lower_camel_case(
 6601        &mut self,
 6602        _: &ConvertToLowerCamelCase,
 6603        window: &mut Window,
 6604        cx: &mut Context<Self>,
 6605    ) {
 6606        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6607    }
 6608
 6609    pub fn convert_to_opposite_case(
 6610        &mut self,
 6611        _: &ConvertToOppositeCase,
 6612        window: &mut Window,
 6613        cx: &mut Context<Self>,
 6614    ) {
 6615        self.manipulate_text(window, cx, |text| {
 6616            text.chars()
 6617                .fold(String::with_capacity(text.len()), |mut t, c| {
 6618                    if c.is_uppercase() {
 6619                        t.extend(c.to_lowercase());
 6620                    } else {
 6621                        t.extend(c.to_uppercase());
 6622                    }
 6623                    t
 6624                })
 6625        })
 6626    }
 6627
 6628    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6629    where
 6630        Fn: FnMut(&str) -> String,
 6631    {
 6632        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6633        let buffer = self.buffer.read(cx).snapshot(cx);
 6634
 6635        let mut new_selections = Vec::new();
 6636        let mut edits = Vec::new();
 6637        let mut selection_adjustment = 0i32;
 6638
 6639        for selection in self.selections.all::<usize>(cx) {
 6640            let selection_is_empty = selection.is_empty();
 6641
 6642            let (start, end) = if selection_is_empty {
 6643                let word_range = movement::surrounding_word(
 6644                    &display_map,
 6645                    selection.start.to_display_point(&display_map),
 6646                );
 6647                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6648                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6649                (start, end)
 6650            } else {
 6651                (selection.start, selection.end)
 6652            };
 6653
 6654            let text = buffer.text_for_range(start..end).collect::<String>();
 6655            let old_length = text.len() as i32;
 6656            let text = callback(&text);
 6657
 6658            new_selections.push(Selection {
 6659                start: (start as i32 - selection_adjustment) as usize,
 6660                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6661                goal: SelectionGoal::None,
 6662                ..selection
 6663            });
 6664
 6665            selection_adjustment += old_length - text.len() as i32;
 6666
 6667            edits.push((start..end, text));
 6668        }
 6669
 6670        self.transact(window, cx, |this, window, cx| {
 6671            this.buffer.update(cx, |buffer, cx| {
 6672                buffer.edit(edits, None, cx);
 6673            });
 6674
 6675            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6676                s.select(new_selections);
 6677            });
 6678
 6679            this.request_autoscroll(Autoscroll::fit(), cx);
 6680        });
 6681    }
 6682
 6683    pub fn duplicate(
 6684        &mut self,
 6685        upwards: bool,
 6686        whole_lines: bool,
 6687        window: &mut Window,
 6688        cx: &mut Context<Self>,
 6689    ) {
 6690        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6691        let buffer = &display_map.buffer_snapshot;
 6692        let selections = self.selections.all::<Point>(cx);
 6693
 6694        let mut edits = Vec::new();
 6695        let mut selections_iter = selections.iter().peekable();
 6696        while let Some(selection) = selections_iter.next() {
 6697            let mut rows = selection.spanned_rows(false, &display_map);
 6698            // duplicate line-wise
 6699            if whole_lines || selection.start == selection.end {
 6700                // Avoid duplicating the same lines twice.
 6701                while let Some(next_selection) = selections_iter.peek() {
 6702                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6703                    if next_rows.start < rows.end {
 6704                        rows.end = next_rows.end;
 6705                        selections_iter.next().unwrap();
 6706                    } else {
 6707                        break;
 6708                    }
 6709                }
 6710
 6711                // Copy the text from the selected row region and splice it either at the start
 6712                // or end of the region.
 6713                let start = Point::new(rows.start.0, 0);
 6714                let end = Point::new(
 6715                    rows.end.previous_row().0,
 6716                    buffer.line_len(rows.end.previous_row()),
 6717                );
 6718                let text = buffer
 6719                    .text_for_range(start..end)
 6720                    .chain(Some("\n"))
 6721                    .collect::<String>();
 6722                let insert_location = if upwards {
 6723                    Point::new(rows.end.0, 0)
 6724                } else {
 6725                    start
 6726                };
 6727                edits.push((insert_location..insert_location, text));
 6728            } else {
 6729                // duplicate character-wise
 6730                let start = selection.start;
 6731                let end = selection.end;
 6732                let text = buffer.text_for_range(start..end).collect::<String>();
 6733                edits.push((selection.end..selection.end, text));
 6734            }
 6735        }
 6736
 6737        self.transact(window, cx, |this, _, cx| {
 6738            this.buffer.update(cx, |buffer, cx| {
 6739                buffer.edit(edits, None, cx);
 6740            });
 6741
 6742            this.request_autoscroll(Autoscroll::fit(), cx);
 6743        });
 6744    }
 6745
 6746    pub fn duplicate_line_up(
 6747        &mut self,
 6748        _: &DuplicateLineUp,
 6749        window: &mut Window,
 6750        cx: &mut Context<Self>,
 6751    ) {
 6752        self.duplicate(true, true, window, cx);
 6753    }
 6754
 6755    pub fn duplicate_line_down(
 6756        &mut self,
 6757        _: &DuplicateLineDown,
 6758        window: &mut Window,
 6759        cx: &mut Context<Self>,
 6760    ) {
 6761        self.duplicate(false, true, window, cx);
 6762    }
 6763
 6764    pub fn duplicate_selection(
 6765        &mut self,
 6766        _: &DuplicateSelection,
 6767        window: &mut Window,
 6768        cx: &mut Context<Self>,
 6769    ) {
 6770        self.duplicate(false, false, window, cx);
 6771    }
 6772
 6773    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6774        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6775        let buffer = self.buffer.read(cx).snapshot(cx);
 6776
 6777        let mut edits = Vec::new();
 6778        let mut unfold_ranges = Vec::new();
 6779        let mut refold_creases = Vec::new();
 6780
 6781        let selections = self.selections.all::<Point>(cx);
 6782        let mut selections = selections.iter().peekable();
 6783        let mut contiguous_row_selections = Vec::new();
 6784        let mut new_selections = Vec::new();
 6785
 6786        while let Some(selection) = selections.next() {
 6787            // Find all the selections that span a contiguous row range
 6788            let (start_row, end_row) = consume_contiguous_rows(
 6789                &mut contiguous_row_selections,
 6790                selection,
 6791                &display_map,
 6792                &mut selections,
 6793            );
 6794
 6795            // Move the text spanned by the row range to be before the line preceding the row range
 6796            if start_row.0 > 0 {
 6797                let range_to_move = Point::new(
 6798                    start_row.previous_row().0,
 6799                    buffer.line_len(start_row.previous_row()),
 6800                )
 6801                    ..Point::new(
 6802                        end_row.previous_row().0,
 6803                        buffer.line_len(end_row.previous_row()),
 6804                    );
 6805                let insertion_point = display_map
 6806                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6807                    .0;
 6808
 6809                // Don't move lines across excerpts
 6810                if buffer
 6811                    .excerpt_containing(insertion_point..range_to_move.end)
 6812                    .is_some()
 6813                {
 6814                    let text = buffer
 6815                        .text_for_range(range_to_move.clone())
 6816                        .flat_map(|s| s.chars())
 6817                        .skip(1)
 6818                        .chain(['\n'])
 6819                        .collect::<String>();
 6820
 6821                    edits.push((
 6822                        buffer.anchor_after(range_to_move.start)
 6823                            ..buffer.anchor_before(range_to_move.end),
 6824                        String::new(),
 6825                    ));
 6826                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6827                    edits.push((insertion_anchor..insertion_anchor, text));
 6828
 6829                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6830
 6831                    // Move selections up
 6832                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6833                        |mut selection| {
 6834                            selection.start.row -= row_delta;
 6835                            selection.end.row -= row_delta;
 6836                            selection
 6837                        },
 6838                    ));
 6839
 6840                    // Move folds up
 6841                    unfold_ranges.push(range_to_move.clone());
 6842                    for fold in display_map.folds_in_range(
 6843                        buffer.anchor_before(range_to_move.start)
 6844                            ..buffer.anchor_after(range_to_move.end),
 6845                    ) {
 6846                        let mut start = fold.range.start.to_point(&buffer);
 6847                        let mut end = fold.range.end.to_point(&buffer);
 6848                        start.row -= row_delta;
 6849                        end.row -= row_delta;
 6850                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6851                    }
 6852                }
 6853            }
 6854
 6855            // If we didn't move line(s), preserve the existing selections
 6856            new_selections.append(&mut contiguous_row_selections);
 6857        }
 6858
 6859        self.transact(window, cx, |this, window, cx| {
 6860            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6861            this.buffer.update(cx, |buffer, cx| {
 6862                for (range, text) in edits {
 6863                    buffer.edit([(range, text)], None, cx);
 6864                }
 6865            });
 6866            this.fold_creases(refold_creases, true, window, cx);
 6867            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6868                s.select(new_selections);
 6869            })
 6870        });
 6871    }
 6872
 6873    pub fn move_line_down(
 6874        &mut self,
 6875        _: &MoveLineDown,
 6876        window: &mut Window,
 6877        cx: &mut Context<Self>,
 6878    ) {
 6879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6880        let buffer = self.buffer.read(cx).snapshot(cx);
 6881
 6882        let mut edits = Vec::new();
 6883        let mut unfold_ranges = Vec::new();
 6884        let mut refold_creases = Vec::new();
 6885
 6886        let selections = self.selections.all::<Point>(cx);
 6887        let mut selections = selections.iter().peekable();
 6888        let mut contiguous_row_selections = Vec::new();
 6889        let mut new_selections = Vec::new();
 6890
 6891        while let Some(selection) = selections.next() {
 6892            // Find all the selections that span a contiguous row range
 6893            let (start_row, end_row) = consume_contiguous_rows(
 6894                &mut contiguous_row_selections,
 6895                selection,
 6896                &display_map,
 6897                &mut selections,
 6898            );
 6899
 6900            // Move the text spanned by the row range to be after the last line of the row range
 6901            if end_row.0 <= buffer.max_point().row {
 6902                let range_to_move =
 6903                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6904                let insertion_point = display_map
 6905                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6906                    .0;
 6907
 6908                // Don't move lines across excerpt boundaries
 6909                if buffer
 6910                    .excerpt_containing(range_to_move.start..insertion_point)
 6911                    .is_some()
 6912                {
 6913                    let mut text = String::from("\n");
 6914                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6915                    text.pop(); // Drop trailing newline
 6916                    edits.push((
 6917                        buffer.anchor_after(range_to_move.start)
 6918                            ..buffer.anchor_before(range_to_move.end),
 6919                        String::new(),
 6920                    ));
 6921                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6922                    edits.push((insertion_anchor..insertion_anchor, text));
 6923
 6924                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6925
 6926                    // Move selections down
 6927                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6928                        |mut selection| {
 6929                            selection.start.row += row_delta;
 6930                            selection.end.row += row_delta;
 6931                            selection
 6932                        },
 6933                    ));
 6934
 6935                    // Move folds down
 6936                    unfold_ranges.push(range_to_move.clone());
 6937                    for fold in display_map.folds_in_range(
 6938                        buffer.anchor_before(range_to_move.start)
 6939                            ..buffer.anchor_after(range_to_move.end),
 6940                    ) {
 6941                        let mut start = fold.range.start.to_point(&buffer);
 6942                        let mut end = fold.range.end.to_point(&buffer);
 6943                        start.row += row_delta;
 6944                        end.row += row_delta;
 6945                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6946                    }
 6947                }
 6948            }
 6949
 6950            // If we didn't move line(s), preserve the existing selections
 6951            new_selections.append(&mut contiguous_row_selections);
 6952        }
 6953
 6954        self.transact(window, cx, |this, window, cx| {
 6955            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6956            this.buffer.update(cx, |buffer, cx| {
 6957                for (range, text) in edits {
 6958                    buffer.edit([(range, text)], None, cx);
 6959                }
 6960            });
 6961            this.fold_creases(refold_creases, true, window, cx);
 6962            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6963                s.select(new_selections)
 6964            });
 6965        });
 6966    }
 6967
 6968    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6969        let text_layout_details = &self.text_layout_details(window);
 6970        self.transact(window, cx, |this, window, cx| {
 6971            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6972                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6973                let line_mode = s.line_mode;
 6974                s.move_with(|display_map, selection| {
 6975                    if !selection.is_empty() || line_mode {
 6976                        return;
 6977                    }
 6978
 6979                    let mut head = selection.head();
 6980                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6981                    if head.column() == display_map.line_len(head.row()) {
 6982                        transpose_offset = display_map
 6983                            .buffer_snapshot
 6984                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6985                    }
 6986
 6987                    if transpose_offset == 0 {
 6988                        return;
 6989                    }
 6990
 6991                    *head.column_mut() += 1;
 6992                    head = display_map.clip_point(head, Bias::Right);
 6993                    let goal = SelectionGoal::HorizontalPosition(
 6994                        display_map
 6995                            .x_for_display_point(head, text_layout_details)
 6996                            .into(),
 6997                    );
 6998                    selection.collapse_to(head, goal);
 6999
 7000                    let transpose_start = display_map
 7001                        .buffer_snapshot
 7002                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7003                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7004                        let transpose_end = display_map
 7005                            .buffer_snapshot
 7006                            .clip_offset(transpose_offset + 1, Bias::Right);
 7007                        if let Some(ch) =
 7008                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7009                        {
 7010                            edits.push((transpose_start..transpose_offset, String::new()));
 7011                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7012                        }
 7013                    }
 7014                });
 7015                edits
 7016            });
 7017            this.buffer
 7018                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7019            let selections = this.selections.all::<usize>(cx);
 7020            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7021                s.select(selections);
 7022            });
 7023        });
 7024    }
 7025
 7026    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7027        self.rewrap_impl(IsVimMode::No, cx)
 7028    }
 7029
 7030    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7031        let buffer = self.buffer.read(cx).snapshot(cx);
 7032        let selections = self.selections.all::<Point>(cx);
 7033        let mut selections = selections.iter().peekable();
 7034
 7035        let mut edits = Vec::new();
 7036        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7037
 7038        while let Some(selection) = selections.next() {
 7039            let mut start_row = selection.start.row;
 7040            let mut end_row = selection.end.row;
 7041
 7042            // Skip selections that overlap with a range that has already been rewrapped.
 7043            let selection_range = start_row..end_row;
 7044            if rewrapped_row_ranges
 7045                .iter()
 7046                .any(|range| range.overlaps(&selection_range))
 7047            {
 7048                continue;
 7049            }
 7050
 7051            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7052
 7053            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7054                match language_scope.language_name().as_ref() {
 7055                    "Markdown" | "Plain Text" => {
 7056                        should_rewrap = true;
 7057                    }
 7058                    _ => {}
 7059                }
 7060            }
 7061
 7062            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7063
 7064            // Since not all lines in the selection may be at the same indent
 7065            // level, choose the indent size that is the most common between all
 7066            // of the lines.
 7067            //
 7068            // If there is a tie, we use the deepest indent.
 7069            let (indent_size, indent_end) = {
 7070                let mut indent_size_occurrences = HashMap::default();
 7071                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7072
 7073                for row in start_row..=end_row {
 7074                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7075                    rows_by_indent_size.entry(indent).or_default().push(row);
 7076                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7077                }
 7078
 7079                let indent_size = indent_size_occurrences
 7080                    .into_iter()
 7081                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7082                    .map(|(indent, _)| indent)
 7083                    .unwrap_or_default();
 7084                let row = rows_by_indent_size[&indent_size][0];
 7085                let indent_end = Point::new(row, indent_size.len);
 7086
 7087                (indent_size, indent_end)
 7088            };
 7089
 7090            let mut line_prefix = indent_size.chars().collect::<String>();
 7091
 7092            if let Some(comment_prefix) =
 7093                buffer
 7094                    .language_scope_at(selection.head())
 7095                    .and_then(|language| {
 7096                        language
 7097                            .line_comment_prefixes()
 7098                            .iter()
 7099                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7100                            .cloned()
 7101                    })
 7102            {
 7103                line_prefix.push_str(&comment_prefix);
 7104                should_rewrap = true;
 7105            }
 7106
 7107            if !should_rewrap {
 7108                continue;
 7109            }
 7110
 7111            if selection.is_empty() {
 7112                'expand_upwards: while start_row > 0 {
 7113                    let prev_row = start_row - 1;
 7114                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7115                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7116                    {
 7117                        start_row = prev_row;
 7118                    } else {
 7119                        break 'expand_upwards;
 7120                    }
 7121                }
 7122
 7123                'expand_downwards: while end_row < buffer.max_point().row {
 7124                    let next_row = end_row + 1;
 7125                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7126                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7127                    {
 7128                        end_row = next_row;
 7129                    } else {
 7130                        break 'expand_downwards;
 7131                    }
 7132                }
 7133            }
 7134
 7135            let start = Point::new(start_row, 0);
 7136            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7137            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7138            let Some(lines_without_prefixes) = selection_text
 7139                .lines()
 7140                .map(|line| {
 7141                    line.strip_prefix(&line_prefix)
 7142                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7143                        .ok_or_else(|| {
 7144                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7145                        })
 7146                })
 7147                .collect::<Result<Vec<_>, _>>()
 7148                .log_err()
 7149            else {
 7150                continue;
 7151            };
 7152
 7153            let wrap_column = buffer
 7154                .settings_at(Point::new(start_row, 0), cx)
 7155                .preferred_line_length as usize;
 7156            let wrapped_text = wrap_with_prefix(
 7157                line_prefix,
 7158                lines_without_prefixes.join(" "),
 7159                wrap_column,
 7160                tab_size,
 7161            );
 7162
 7163            // TODO: should always use char-based diff while still supporting cursor behavior that
 7164            // matches vim.
 7165            let diff = match is_vim_mode {
 7166                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7167                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7168            };
 7169            let mut offset = start.to_offset(&buffer);
 7170            let mut moved_since_edit = true;
 7171
 7172            for change in diff.iter_all_changes() {
 7173                let value = change.value();
 7174                match change.tag() {
 7175                    ChangeTag::Equal => {
 7176                        offset += value.len();
 7177                        moved_since_edit = true;
 7178                    }
 7179                    ChangeTag::Delete => {
 7180                        let start = buffer.anchor_after(offset);
 7181                        let end = buffer.anchor_before(offset + value.len());
 7182
 7183                        if moved_since_edit {
 7184                            edits.push((start..end, String::new()));
 7185                        } else {
 7186                            edits.last_mut().unwrap().0.end = end;
 7187                        }
 7188
 7189                        offset += value.len();
 7190                        moved_since_edit = false;
 7191                    }
 7192                    ChangeTag::Insert => {
 7193                        if moved_since_edit {
 7194                            let anchor = buffer.anchor_after(offset);
 7195                            edits.push((anchor..anchor, value.to_string()));
 7196                        } else {
 7197                            edits.last_mut().unwrap().1.push_str(value);
 7198                        }
 7199
 7200                        moved_since_edit = false;
 7201                    }
 7202                }
 7203            }
 7204
 7205            rewrapped_row_ranges.push(start_row..=end_row);
 7206        }
 7207
 7208        self.buffer
 7209            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7210    }
 7211
 7212    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7213        let mut text = String::new();
 7214        let buffer = self.buffer.read(cx).snapshot(cx);
 7215        let mut selections = self.selections.all::<Point>(cx);
 7216        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7217        {
 7218            let max_point = buffer.max_point();
 7219            let mut is_first = true;
 7220            for selection in &mut selections {
 7221                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7222                if is_entire_line {
 7223                    selection.start = Point::new(selection.start.row, 0);
 7224                    if !selection.is_empty() && selection.end.column == 0 {
 7225                        selection.end = cmp::min(max_point, selection.end);
 7226                    } else {
 7227                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7228                    }
 7229                    selection.goal = SelectionGoal::None;
 7230                }
 7231                if is_first {
 7232                    is_first = false;
 7233                } else {
 7234                    text += "\n";
 7235                }
 7236                let mut len = 0;
 7237                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7238                    text.push_str(chunk);
 7239                    len += chunk.len();
 7240                }
 7241                clipboard_selections.push(ClipboardSelection {
 7242                    len,
 7243                    is_entire_line,
 7244                    first_line_indent: buffer
 7245                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7246                        .len,
 7247                });
 7248            }
 7249        }
 7250
 7251        self.transact(window, cx, |this, window, cx| {
 7252            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7253                s.select(selections);
 7254            });
 7255            this.insert("", window, cx);
 7256        });
 7257        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7258    }
 7259
 7260    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7261        let item = self.cut_common(window, cx);
 7262        cx.write_to_clipboard(item);
 7263    }
 7264
 7265    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7266        self.change_selections(None, window, cx, |s| {
 7267            s.move_with(|snapshot, sel| {
 7268                if sel.is_empty() {
 7269                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7270                }
 7271            });
 7272        });
 7273        let item = self.cut_common(window, cx);
 7274        cx.set_global(KillRing(item))
 7275    }
 7276
 7277    pub fn kill_ring_yank(
 7278        &mut self,
 7279        _: &KillRingYank,
 7280        window: &mut Window,
 7281        cx: &mut Context<Self>,
 7282    ) {
 7283        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7284            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7285                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7286            } else {
 7287                return;
 7288            }
 7289        } else {
 7290            return;
 7291        };
 7292        self.do_paste(&text, metadata, false, window, cx);
 7293    }
 7294
 7295    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7296        let selections = self.selections.all::<Point>(cx);
 7297        let buffer = self.buffer.read(cx).read(cx);
 7298        let mut text = String::new();
 7299
 7300        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7301        {
 7302            let max_point = buffer.max_point();
 7303            let mut is_first = true;
 7304            for selection in selections.iter() {
 7305                let mut start = selection.start;
 7306                let mut end = selection.end;
 7307                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7308                if is_entire_line {
 7309                    start = Point::new(start.row, 0);
 7310                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7311                }
 7312                if is_first {
 7313                    is_first = false;
 7314                } else {
 7315                    text += "\n";
 7316                }
 7317                let mut len = 0;
 7318                for chunk in buffer.text_for_range(start..end) {
 7319                    text.push_str(chunk);
 7320                    len += chunk.len();
 7321                }
 7322                clipboard_selections.push(ClipboardSelection {
 7323                    len,
 7324                    is_entire_line,
 7325                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7326                });
 7327            }
 7328        }
 7329
 7330        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7331            text,
 7332            clipboard_selections,
 7333        ));
 7334    }
 7335
 7336    pub fn do_paste(
 7337        &mut self,
 7338        text: &String,
 7339        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7340        handle_entire_lines: bool,
 7341        window: &mut Window,
 7342        cx: &mut Context<Self>,
 7343    ) {
 7344        if self.read_only(cx) {
 7345            return;
 7346        }
 7347
 7348        let clipboard_text = Cow::Borrowed(text);
 7349
 7350        self.transact(window, cx, |this, window, cx| {
 7351            if let Some(mut clipboard_selections) = clipboard_selections {
 7352                let old_selections = this.selections.all::<usize>(cx);
 7353                let all_selections_were_entire_line =
 7354                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7355                let first_selection_indent_column =
 7356                    clipboard_selections.first().map(|s| s.first_line_indent);
 7357                if clipboard_selections.len() != old_selections.len() {
 7358                    clipboard_selections.drain(..);
 7359                }
 7360                let cursor_offset = this.selections.last::<usize>(cx).head();
 7361                let mut auto_indent_on_paste = true;
 7362
 7363                this.buffer.update(cx, |buffer, cx| {
 7364                    let snapshot = buffer.read(cx);
 7365                    auto_indent_on_paste =
 7366                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7367
 7368                    let mut start_offset = 0;
 7369                    let mut edits = Vec::new();
 7370                    let mut original_indent_columns = Vec::new();
 7371                    for (ix, selection) in old_selections.iter().enumerate() {
 7372                        let to_insert;
 7373                        let entire_line;
 7374                        let original_indent_column;
 7375                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7376                            let end_offset = start_offset + clipboard_selection.len;
 7377                            to_insert = &clipboard_text[start_offset..end_offset];
 7378                            entire_line = clipboard_selection.is_entire_line;
 7379                            start_offset = end_offset + 1;
 7380                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7381                        } else {
 7382                            to_insert = clipboard_text.as_str();
 7383                            entire_line = all_selections_were_entire_line;
 7384                            original_indent_column = first_selection_indent_column
 7385                        }
 7386
 7387                        // If the corresponding selection was empty when this slice of the
 7388                        // clipboard text was written, then the entire line containing the
 7389                        // selection was copied. If this selection is also currently empty,
 7390                        // then paste the line before the current line of the buffer.
 7391                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7392                            let column = selection.start.to_point(&snapshot).column as usize;
 7393                            let line_start = selection.start - column;
 7394                            line_start..line_start
 7395                        } else {
 7396                            selection.range()
 7397                        };
 7398
 7399                        edits.push((range, to_insert));
 7400                        original_indent_columns.extend(original_indent_column);
 7401                    }
 7402                    drop(snapshot);
 7403
 7404                    buffer.edit(
 7405                        edits,
 7406                        if auto_indent_on_paste {
 7407                            Some(AutoindentMode::Block {
 7408                                original_indent_columns,
 7409                            })
 7410                        } else {
 7411                            None
 7412                        },
 7413                        cx,
 7414                    );
 7415                });
 7416
 7417                let selections = this.selections.all::<usize>(cx);
 7418                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7419                    s.select(selections)
 7420                });
 7421            } else {
 7422                this.insert(&clipboard_text, window, cx);
 7423            }
 7424        });
 7425    }
 7426
 7427    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7428        if let Some(item) = cx.read_from_clipboard() {
 7429            let entries = item.entries();
 7430
 7431            match entries.first() {
 7432                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7433                // of all the pasted entries.
 7434                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7435                    .do_paste(
 7436                        clipboard_string.text(),
 7437                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7438                        true,
 7439                        window,
 7440                        cx,
 7441                    ),
 7442                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7443            }
 7444        }
 7445    }
 7446
 7447    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7448        if self.read_only(cx) {
 7449            return;
 7450        }
 7451
 7452        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7453            if let Some((selections, _)) =
 7454                self.selection_history.transaction(transaction_id).cloned()
 7455            {
 7456                self.change_selections(None, window, cx, |s| {
 7457                    s.select_anchors(selections.to_vec());
 7458                });
 7459            }
 7460            self.request_autoscroll(Autoscroll::fit(), cx);
 7461            self.unmark_text(window, cx);
 7462            self.refresh_inline_completion(true, false, window, cx);
 7463            cx.emit(EditorEvent::Edited { transaction_id });
 7464            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7465        }
 7466    }
 7467
 7468    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7469        if self.read_only(cx) {
 7470            return;
 7471        }
 7472
 7473        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7474            if let Some((_, Some(selections))) =
 7475                self.selection_history.transaction(transaction_id).cloned()
 7476            {
 7477                self.change_selections(None, window, cx, |s| {
 7478                    s.select_anchors(selections.to_vec());
 7479                });
 7480            }
 7481            self.request_autoscroll(Autoscroll::fit(), cx);
 7482            self.unmark_text(window, cx);
 7483            self.refresh_inline_completion(true, false, window, cx);
 7484            cx.emit(EditorEvent::Edited { transaction_id });
 7485        }
 7486    }
 7487
 7488    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7489        self.buffer
 7490            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7491    }
 7492
 7493    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7494        self.buffer
 7495            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7496    }
 7497
 7498    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7499        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7500            let line_mode = s.line_mode;
 7501            s.move_with(|map, selection| {
 7502                let cursor = if selection.is_empty() && !line_mode {
 7503                    movement::left(map, selection.start)
 7504                } else {
 7505                    selection.start
 7506                };
 7507                selection.collapse_to(cursor, SelectionGoal::None);
 7508            });
 7509        })
 7510    }
 7511
 7512    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7513        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7514            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7515        })
 7516    }
 7517
 7518    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7519        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7520            let line_mode = s.line_mode;
 7521            s.move_with(|map, selection| {
 7522                let cursor = if selection.is_empty() && !line_mode {
 7523                    movement::right(map, selection.end)
 7524                } else {
 7525                    selection.end
 7526                };
 7527                selection.collapse_to(cursor, SelectionGoal::None)
 7528            });
 7529        })
 7530    }
 7531
 7532    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7533        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7534            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7535        })
 7536    }
 7537
 7538    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7539        if self.take_rename(true, window, cx).is_some() {
 7540            return;
 7541        }
 7542
 7543        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7544            cx.propagate();
 7545            return;
 7546        }
 7547
 7548        let text_layout_details = &self.text_layout_details(window);
 7549        let selection_count = self.selections.count();
 7550        let first_selection = self.selections.first_anchor();
 7551
 7552        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7553            let line_mode = s.line_mode;
 7554            s.move_with(|map, selection| {
 7555                if !selection.is_empty() && !line_mode {
 7556                    selection.goal = SelectionGoal::None;
 7557                }
 7558                let (cursor, goal) = movement::up(
 7559                    map,
 7560                    selection.start,
 7561                    selection.goal,
 7562                    false,
 7563                    text_layout_details,
 7564                );
 7565                selection.collapse_to(cursor, goal);
 7566            });
 7567        });
 7568
 7569        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7570        {
 7571            cx.propagate();
 7572        }
 7573    }
 7574
 7575    pub fn move_up_by_lines(
 7576        &mut self,
 7577        action: &MoveUpByLines,
 7578        window: &mut Window,
 7579        cx: &mut Context<Self>,
 7580    ) {
 7581        if self.take_rename(true, window, cx).is_some() {
 7582            return;
 7583        }
 7584
 7585        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7586            cx.propagate();
 7587            return;
 7588        }
 7589
 7590        let text_layout_details = &self.text_layout_details(window);
 7591
 7592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7593            let line_mode = s.line_mode;
 7594            s.move_with(|map, selection| {
 7595                if !selection.is_empty() && !line_mode {
 7596                    selection.goal = SelectionGoal::None;
 7597                }
 7598                let (cursor, goal) = movement::up_by_rows(
 7599                    map,
 7600                    selection.start,
 7601                    action.lines,
 7602                    selection.goal,
 7603                    false,
 7604                    text_layout_details,
 7605                );
 7606                selection.collapse_to(cursor, goal);
 7607            });
 7608        })
 7609    }
 7610
 7611    pub fn move_down_by_lines(
 7612        &mut self,
 7613        action: &MoveDownByLines,
 7614        window: &mut Window,
 7615        cx: &mut Context<Self>,
 7616    ) {
 7617        if self.take_rename(true, window, cx).is_some() {
 7618            return;
 7619        }
 7620
 7621        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7622            cx.propagate();
 7623            return;
 7624        }
 7625
 7626        let text_layout_details = &self.text_layout_details(window);
 7627
 7628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7629            let line_mode = s.line_mode;
 7630            s.move_with(|map, selection| {
 7631                if !selection.is_empty() && !line_mode {
 7632                    selection.goal = SelectionGoal::None;
 7633                }
 7634                let (cursor, goal) = movement::down_by_rows(
 7635                    map,
 7636                    selection.start,
 7637                    action.lines,
 7638                    selection.goal,
 7639                    false,
 7640                    text_layout_details,
 7641                );
 7642                selection.collapse_to(cursor, goal);
 7643            });
 7644        })
 7645    }
 7646
 7647    pub fn select_down_by_lines(
 7648        &mut self,
 7649        action: &SelectDownByLines,
 7650        window: &mut Window,
 7651        cx: &mut Context<Self>,
 7652    ) {
 7653        let text_layout_details = &self.text_layout_details(window);
 7654        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7655            s.move_heads_with(|map, head, goal| {
 7656                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7657            })
 7658        })
 7659    }
 7660
 7661    pub fn select_up_by_lines(
 7662        &mut self,
 7663        action: &SelectUpByLines,
 7664        window: &mut Window,
 7665        cx: &mut Context<Self>,
 7666    ) {
 7667        let text_layout_details = &self.text_layout_details(window);
 7668        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7669            s.move_heads_with(|map, head, goal| {
 7670                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7671            })
 7672        })
 7673    }
 7674
 7675    pub fn select_page_up(
 7676        &mut self,
 7677        _: &SelectPageUp,
 7678        window: &mut Window,
 7679        cx: &mut Context<Self>,
 7680    ) {
 7681        let Some(row_count) = self.visible_row_count() else {
 7682            return;
 7683        };
 7684
 7685        let text_layout_details = &self.text_layout_details(window);
 7686
 7687        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7688            s.move_heads_with(|map, head, goal| {
 7689                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7690            })
 7691        })
 7692    }
 7693
 7694    pub fn move_page_up(
 7695        &mut self,
 7696        action: &MovePageUp,
 7697        window: &mut Window,
 7698        cx: &mut Context<Self>,
 7699    ) {
 7700        if self.take_rename(true, window, cx).is_some() {
 7701            return;
 7702        }
 7703
 7704        if self
 7705            .context_menu
 7706            .borrow_mut()
 7707            .as_mut()
 7708            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7709            .unwrap_or(false)
 7710        {
 7711            return;
 7712        }
 7713
 7714        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7715            cx.propagate();
 7716            return;
 7717        }
 7718
 7719        let Some(row_count) = self.visible_row_count() else {
 7720            return;
 7721        };
 7722
 7723        let autoscroll = if action.center_cursor {
 7724            Autoscroll::center()
 7725        } else {
 7726            Autoscroll::fit()
 7727        };
 7728
 7729        let text_layout_details = &self.text_layout_details(window);
 7730
 7731        self.change_selections(Some(autoscroll), window, cx, |s| {
 7732            let line_mode = s.line_mode;
 7733            s.move_with(|map, selection| {
 7734                if !selection.is_empty() && !line_mode {
 7735                    selection.goal = SelectionGoal::None;
 7736                }
 7737                let (cursor, goal) = movement::up_by_rows(
 7738                    map,
 7739                    selection.end,
 7740                    row_count,
 7741                    selection.goal,
 7742                    false,
 7743                    text_layout_details,
 7744                );
 7745                selection.collapse_to(cursor, goal);
 7746            });
 7747        });
 7748    }
 7749
 7750    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7751        let text_layout_details = &self.text_layout_details(window);
 7752        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7753            s.move_heads_with(|map, head, goal| {
 7754                movement::up(map, head, goal, false, text_layout_details)
 7755            })
 7756        })
 7757    }
 7758
 7759    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7760        self.take_rename(true, window, cx);
 7761
 7762        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7763            cx.propagate();
 7764            return;
 7765        }
 7766
 7767        let text_layout_details = &self.text_layout_details(window);
 7768        let selection_count = self.selections.count();
 7769        let first_selection = self.selections.first_anchor();
 7770
 7771        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7772            let line_mode = s.line_mode;
 7773            s.move_with(|map, selection| {
 7774                if !selection.is_empty() && !line_mode {
 7775                    selection.goal = SelectionGoal::None;
 7776                }
 7777                let (cursor, goal) = movement::down(
 7778                    map,
 7779                    selection.end,
 7780                    selection.goal,
 7781                    false,
 7782                    text_layout_details,
 7783                );
 7784                selection.collapse_to(cursor, goal);
 7785            });
 7786        });
 7787
 7788        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7789        {
 7790            cx.propagate();
 7791        }
 7792    }
 7793
 7794    pub fn select_page_down(
 7795        &mut self,
 7796        _: &SelectPageDown,
 7797        window: &mut Window,
 7798        cx: &mut Context<Self>,
 7799    ) {
 7800        let Some(row_count) = self.visible_row_count() else {
 7801            return;
 7802        };
 7803
 7804        let text_layout_details = &self.text_layout_details(window);
 7805
 7806        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7807            s.move_heads_with(|map, head, goal| {
 7808                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7809            })
 7810        })
 7811    }
 7812
 7813    pub fn move_page_down(
 7814        &mut self,
 7815        action: &MovePageDown,
 7816        window: &mut Window,
 7817        cx: &mut Context<Self>,
 7818    ) {
 7819        if self.take_rename(true, window, cx).is_some() {
 7820            return;
 7821        }
 7822
 7823        if self
 7824            .context_menu
 7825            .borrow_mut()
 7826            .as_mut()
 7827            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7828            .unwrap_or(false)
 7829        {
 7830            return;
 7831        }
 7832
 7833        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7834            cx.propagate();
 7835            return;
 7836        }
 7837
 7838        let Some(row_count) = self.visible_row_count() else {
 7839            return;
 7840        };
 7841
 7842        let autoscroll = if action.center_cursor {
 7843            Autoscroll::center()
 7844        } else {
 7845            Autoscroll::fit()
 7846        };
 7847
 7848        let text_layout_details = &self.text_layout_details(window);
 7849        self.change_selections(Some(autoscroll), window, cx, |s| {
 7850            let line_mode = s.line_mode;
 7851            s.move_with(|map, selection| {
 7852                if !selection.is_empty() && !line_mode {
 7853                    selection.goal = SelectionGoal::None;
 7854                }
 7855                let (cursor, goal) = movement::down_by_rows(
 7856                    map,
 7857                    selection.end,
 7858                    row_count,
 7859                    selection.goal,
 7860                    false,
 7861                    text_layout_details,
 7862                );
 7863                selection.collapse_to(cursor, goal);
 7864            });
 7865        });
 7866    }
 7867
 7868    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7869        let text_layout_details = &self.text_layout_details(window);
 7870        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7871            s.move_heads_with(|map, head, goal| {
 7872                movement::down(map, head, goal, false, text_layout_details)
 7873            })
 7874        });
 7875    }
 7876
 7877    pub fn context_menu_first(
 7878        &mut self,
 7879        _: &ContextMenuFirst,
 7880        _window: &mut Window,
 7881        cx: &mut Context<Self>,
 7882    ) {
 7883        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7884            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7885        }
 7886    }
 7887
 7888    pub fn context_menu_prev(
 7889        &mut self,
 7890        _: &ContextMenuPrev,
 7891        _window: &mut Window,
 7892        cx: &mut Context<Self>,
 7893    ) {
 7894        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7895            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7896        }
 7897    }
 7898
 7899    pub fn context_menu_next(
 7900        &mut self,
 7901        _: &ContextMenuNext,
 7902        _window: &mut Window,
 7903        cx: &mut Context<Self>,
 7904    ) {
 7905        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7906            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7907        }
 7908    }
 7909
 7910    pub fn context_menu_last(
 7911        &mut self,
 7912        _: &ContextMenuLast,
 7913        _window: &mut Window,
 7914        cx: &mut Context<Self>,
 7915    ) {
 7916        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7917            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7918        }
 7919    }
 7920
 7921    pub fn move_to_previous_word_start(
 7922        &mut self,
 7923        _: &MoveToPreviousWordStart,
 7924        window: &mut Window,
 7925        cx: &mut Context<Self>,
 7926    ) {
 7927        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7928            s.move_cursors_with(|map, head, _| {
 7929                (
 7930                    movement::previous_word_start(map, head),
 7931                    SelectionGoal::None,
 7932                )
 7933            });
 7934        })
 7935    }
 7936
 7937    pub fn move_to_previous_subword_start(
 7938        &mut self,
 7939        _: &MoveToPreviousSubwordStart,
 7940        window: &mut Window,
 7941        cx: &mut Context<Self>,
 7942    ) {
 7943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7944            s.move_cursors_with(|map, head, _| {
 7945                (
 7946                    movement::previous_subword_start(map, head),
 7947                    SelectionGoal::None,
 7948                )
 7949            });
 7950        })
 7951    }
 7952
 7953    pub fn select_to_previous_word_start(
 7954        &mut self,
 7955        _: &SelectToPreviousWordStart,
 7956        window: &mut Window,
 7957        cx: &mut Context<Self>,
 7958    ) {
 7959        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7960            s.move_heads_with(|map, head, _| {
 7961                (
 7962                    movement::previous_word_start(map, head),
 7963                    SelectionGoal::None,
 7964                )
 7965            });
 7966        })
 7967    }
 7968
 7969    pub fn select_to_previous_subword_start(
 7970        &mut self,
 7971        _: &SelectToPreviousSubwordStart,
 7972        window: &mut Window,
 7973        cx: &mut Context<Self>,
 7974    ) {
 7975        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7976            s.move_heads_with(|map, head, _| {
 7977                (
 7978                    movement::previous_subword_start(map, head),
 7979                    SelectionGoal::None,
 7980                )
 7981            });
 7982        })
 7983    }
 7984
 7985    pub fn delete_to_previous_word_start(
 7986        &mut self,
 7987        action: &DeleteToPreviousWordStart,
 7988        window: &mut Window,
 7989        cx: &mut Context<Self>,
 7990    ) {
 7991        self.transact(window, cx, |this, window, cx| {
 7992            this.select_autoclose_pair(window, cx);
 7993            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7994                let line_mode = s.line_mode;
 7995                s.move_with(|map, selection| {
 7996                    if selection.is_empty() && !line_mode {
 7997                        let cursor = if action.ignore_newlines {
 7998                            movement::previous_word_start(map, selection.head())
 7999                        } else {
 8000                            movement::previous_word_start_or_newline(map, selection.head())
 8001                        };
 8002                        selection.set_head(cursor, SelectionGoal::None);
 8003                    }
 8004                });
 8005            });
 8006            this.insert("", window, cx);
 8007        });
 8008    }
 8009
 8010    pub fn delete_to_previous_subword_start(
 8011        &mut self,
 8012        _: &DeleteToPreviousSubwordStart,
 8013        window: &mut Window,
 8014        cx: &mut Context<Self>,
 8015    ) {
 8016        self.transact(window, cx, |this, window, cx| {
 8017            this.select_autoclose_pair(window, cx);
 8018            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8019                let line_mode = s.line_mode;
 8020                s.move_with(|map, selection| {
 8021                    if selection.is_empty() && !line_mode {
 8022                        let cursor = movement::previous_subword_start(map, selection.head());
 8023                        selection.set_head(cursor, SelectionGoal::None);
 8024                    }
 8025                });
 8026            });
 8027            this.insert("", window, cx);
 8028        });
 8029    }
 8030
 8031    pub fn move_to_next_word_end(
 8032        &mut self,
 8033        _: &MoveToNextWordEnd,
 8034        window: &mut Window,
 8035        cx: &mut Context<Self>,
 8036    ) {
 8037        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8038            s.move_cursors_with(|map, head, _| {
 8039                (movement::next_word_end(map, head), SelectionGoal::None)
 8040            });
 8041        })
 8042    }
 8043
 8044    pub fn move_to_next_subword_end(
 8045        &mut self,
 8046        _: &MoveToNextSubwordEnd,
 8047        window: &mut Window,
 8048        cx: &mut Context<Self>,
 8049    ) {
 8050        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8051            s.move_cursors_with(|map, head, _| {
 8052                (movement::next_subword_end(map, head), SelectionGoal::None)
 8053            });
 8054        })
 8055    }
 8056
 8057    pub fn select_to_next_word_end(
 8058        &mut self,
 8059        _: &SelectToNextWordEnd,
 8060        window: &mut Window,
 8061        cx: &mut Context<Self>,
 8062    ) {
 8063        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8064            s.move_heads_with(|map, head, _| {
 8065                (movement::next_word_end(map, head), SelectionGoal::None)
 8066            });
 8067        })
 8068    }
 8069
 8070    pub fn select_to_next_subword_end(
 8071        &mut self,
 8072        _: &SelectToNextSubwordEnd,
 8073        window: &mut Window,
 8074        cx: &mut Context<Self>,
 8075    ) {
 8076        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8077            s.move_heads_with(|map, head, _| {
 8078                (movement::next_subword_end(map, head), SelectionGoal::None)
 8079            });
 8080        })
 8081    }
 8082
 8083    pub fn delete_to_next_word_end(
 8084        &mut self,
 8085        action: &DeleteToNextWordEnd,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) {
 8089        self.transact(window, cx, |this, window, cx| {
 8090            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8091                let line_mode = s.line_mode;
 8092                s.move_with(|map, selection| {
 8093                    if selection.is_empty() && !line_mode {
 8094                        let cursor = if action.ignore_newlines {
 8095                            movement::next_word_end(map, selection.head())
 8096                        } else {
 8097                            movement::next_word_end_or_newline(map, selection.head())
 8098                        };
 8099                        selection.set_head(cursor, SelectionGoal::None);
 8100                    }
 8101                });
 8102            });
 8103            this.insert("", window, cx);
 8104        });
 8105    }
 8106
 8107    pub fn delete_to_next_subword_end(
 8108        &mut self,
 8109        _: &DeleteToNextSubwordEnd,
 8110        window: &mut Window,
 8111        cx: &mut Context<Self>,
 8112    ) {
 8113        self.transact(window, cx, |this, window, cx| {
 8114            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8115                s.move_with(|map, selection| {
 8116                    if selection.is_empty() {
 8117                        let cursor = movement::next_subword_end(map, selection.head());
 8118                        selection.set_head(cursor, SelectionGoal::None);
 8119                    }
 8120                });
 8121            });
 8122            this.insert("", window, cx);
 8123        });
 8124    }
 8125
 8126    pub fn move_to_beginning_of_line(
 8127        &mut self,
 8128        action: &MoveToBeginningOfLine,
 8129        window: &mut Window,
 8130        cx: &mut Context<Self>,
 8131    ) {
 8132        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8133            s.move_cursors_with(|map, head, _| {
 8134                (
 8135                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8136                    SelectionGoal::None,
 8137                )
 8138            });
 8139        })
 8140    }
 8141
 8142    pub fn select_to_beginning_of_line(
 8143        &mut self,
 8144        action: &SelectToBeginningOfLine,
 8145        window: &mut Window,
 8146        cx: &mut Context<Self>,
 8147    ) {
 8148        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8149            s.move_heads_with(|map, head, _| {
 8150                (
 8151                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8152                    SelectionGoal::None,
 8153                )
 8154            });
 8155        });
 8156    }
 8157
 8158    pub fn delete_to_beginning_of_line(
 8159        &mut self,
 8160        _: &DeleteToBeginningOfLine,
 8161        window: &mut Window,
 8162        cx: &mut Context<Self>,
 8163    ) {
 8164        self.transact(window, cx, |this, window, cx| {
 8165            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8166                s.move_with(|_, selection| {
 8167                    selection.reversed = true;
 8168                });
 8169            });
 8170
 8171            this.select_to_beginning_of_line(
 8172                &SelectToBeginningOfLine {
 8173                    stop_at_soft_wraps: false,
 8174                },
 8175                window,
 8176                cx,
 8177            );
 8178            this.backspace(&Backspace, window, cx);
 8179        });
 8180    }
 8181
 8182    pub fn move_to_end_of_line(
 8183        &mut self,
 8184        action: &MoveToEndOfLine,
 8185        window: &mut Window,
 8186        cx: &mut Context<Self>,
 8187    ) {
 8188        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8189            s.move_cursors_with(|map, head, _| {
 8190                (
 8191                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8192                    SelectionGoal::None,
 8193                )
 8194            });
 8195        })
 8196    }
 8197
 8198    pub fn select_to_end_of_line(
 8199        &mut self,
 8200        action: &SelectToEndOfLine,
 8201        window: &mut Window,
 8202        cx: &mut Context<Self>,
 8203    ) {
 8204        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8205            s.move_heads_with(|map, head, _| {
 8206                (
 8207                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8208                    SelectionGoal::None,
 8209                )
 8210            });
 8211        })
 8212    }
 8213
 8214    pub fn delete_to_end_of_line(
 8215        &mut self,
 8216        _: &DeleteToEndOfLine,
 8217        window: &mut Window,
 8218        cx: &mut Context<Self>,
 8219    ) {
 8220        self.transact(window, cx, |this, window, cx| {
 8221            this.select_to_end_of_line(
 8222                &SelectToEndOfLine {
 8223                    stop_at_soft_wraps: false,
 8224                },
 8225                window,
 8226                cx,
 8227            );
 8228            this.delete(&Delete, window, cx);
 8229        });
 8230    }
 8231
 8232    pub fn cut_to_end_of_line(
 8233        &mut self,
 8234        _: &CutToEndOfLine,
 8235        window: &mut Window,
 8236        cx: &mut Context<Self>,
 8237    ) {
 8238        self.transact(window, cx, |this, window, cx| {
 8239            this.select_to_end_of_line(
 8240                &SelectToEndOfLine {
 8241                    stop_at_soft_wraps: false,
 8242                },
 8243                window,
 8244                cx,
 8245            );
 8246            this.cut(&Cut, window, cx);
 8247        });
 8248    }
 8249
 8250    pub fn move_to_start_of_paragraph(
 8251        &mut self,
 8252        _: &MoveToStartOfParagraph,
 8253        window: &mut Window,
 8254        cx: &mut Context<Self>,
 8255    ) {
 8256        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8257            cx.propagate();
 8258            return;
 8259        }
 8260
 8261        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8262            s.move_with(|map, selection| {
 8263                selection.collapse_to(
 8264                    movement::start_of_paragraph(map, selection.head(), 1),
 8265                    SelectionGoal::None,
 8266                )
 8267            });
 8268        })
 8269    }
 8270
 8271    pub fn move_to_end_of_paragraph(
 8272        &mut self,
 8273        _: &MoveToEndOfParagraph,
 8274        window: &mut Window,
 8275        cx: &mut Context<Self>,
 8276    ) {
 8277        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8278            cx.propagate();
 8279            return;
 8280        }
 8281
 8282        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8283            s.move_with(|map, selection| {
 8284                selection.collapse_to(
 8285                    movement::end_of_paragraph(map, selection.head(), 1),
 8286                    SelectionGoal::None,
 8287                )
 8288            });
 8289        })
 8290    }
 8291
 8292    pub fn select_to_start_of_paragraph(
 8293        &mut self,
 8294        _: &SelectToStartOfParagraph,
 8295        window: &mut Window,
 8296        cx: &mut Context<Self>,
 8297    ) {
 8298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8299            cx.propagate();
 8300            return;
 8301        }
 8302
 8303        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8304            s.move_heads_with(|map, head, _| {
 8305                (
 8306                    movement::start_of_paragraph(map, head, 1),
 8307                    SelectionGoal::None,
 8308                )
 8309            });
 8310        })
 8311    }
 8312
 8313    pub fn select_to_end_of_paragraph(
 8314        &mut self,
 8315        _: &SelectToEndOfParagraph,
 8316        window: &mut Window,
 8317        cx: &mut Context<Self>,
 8318    ) {
 8319        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8320            cx.propagate();
 8321            return;
 8322        }
 8323
 8324        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8325            s.move_heads_with(|map, head, _| {
 8326                (
 8327                    movement::end_of_paragraph(map, head, 1),
 8328                    SelectionGoal::None,
 8329                )
 8330            });
 8331        })
 8332    }
 8333
 8334    pub fn move_to_beginning(
 8335        &mut self,
 8336        _: &MoveToBeginning,
 8337        window: &mut Window,
 8338        cx: &mut Context<Self>,
 8339    ) {
 8340        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8341            cx.propagate();
 8342            return;
 8343        }
 8344
 8345        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8346            s.select_ranges(vec![0..0]);
 8347        });
 8348    }
 8349
 8350    pub fn select_to_beginning(
 8351        &mut self,
 8352        _: &SelectToBeginning,
 8353        window: &mut Window,
 8354        cx: &mut Context<Self>,
 8355    ) {
 8356        let mut selection = self.selections.last::<Point>(cx);
 8357        selection.set_head(Point::zero(), SelectionGoal::None);
 8358
 8359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8360            s.select(vec![selection]);
 8361        });
 8362    }
 8363
 8364    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8365        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8366            cx.propagate();
 8367            return;
 8368        }
 8369
 8370        let cursor = self.buffer.read(cx).read(cx).len();
 8371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8372            s.select_ranges(vec![cursor..cursor])
 8373        });
 8374    }
 8375
 8376    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8377        self.nav_history = nav_history;
 8378    }
 8379
 8380    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8381        self.nav_history.as_ref()
 8382    }
 8383
 8384    fn push_to_nav_history(
 8385        &mut self,
 8386        cursor_anchor: Anchor,
 8387        new_position: Option<Point>,
 8388        cx: &mut Context<Self>,
 8389    ) {
 8390        if let Some(nav_history) = self.nav_history.as_mut() {
 8391            let buffer = self.buffer.read(cx).read(cx);
 8392            let cursor_position = cursor_anchor.to_point(&buffer);
 8393            let scroll_state = self.scroll_manager.anchor();
 8394            let scroll_top_row = scroll_state.top_row(&buffer);
 8395            drop(buffer);
 8396
 8397            if let Some(new_position) = new_position {
 8398                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8399                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8400                    return;
 8401                }
 8402            }
 8403
 8404            nav_history.push(
 8405                Some(NavigationData {
 8406                    cursor_anchor,
 8407                    cursor_position,
 8408                    scroll_anchor: scroll_state,
 8409                    scroll_top_row,
 8410                }),
 8411                cx,
 8412            );
 8413        }
 8414    }
 8415
 8416    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8417        let buffer = self.buffer.read(cx).snapshot(cx);
 8418        let mut selection = self.selections.first::<usize>(cx);
 8419        selection.set_head(buffer.len(), SelectionGoal::None);
 8420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421            s.select(vec![selection]);
 8422        });
 8423    }
 8424
 8425    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8426        let end = self.buffer.read(cx).read(cx).len();
 8427        self.change_selections(None, window, cx, |s| {
 8428            s.select_ranges(vec![0..end]);
 8429        });
 8430    }
 8431
 8432    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8434        let mut selections = self.selections.all::<Point>(cx);
 8435        let max_point = display_map.buffer_snapshot.max_point();
 8436        for selection in &mut selections {
 8437            let rows = selection.spanned_rows(true, &display_map);
 8438            selection.start = Point::new(rows.start.0, 0);
 8439            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8440            selection.reversed = false;
 8441        }
 8442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8443            s.select(selections);
 8444        });
 8445    }
 8446
 8447    pub fn split_selection_into_lines(
 8448        &mut self,
 8449        _: &SplitSelectionIntoLines,
 8450        window: &mut Window,
 8451        cx: &mut Context<Self>,
 8452    ) {
 8453        let mut to_unfold = Vec::new();
 8454        let mut new_selection_ranges = Vec::new();
 8455        {
 8456            let selections = self.selections.all::<Point>(cx);
 8457            let buffer = self.buffer.read(cx).read(cx);
 8458            for selection in selections {
 8459                for row in selection.start.row..selection.end.row {
 8460                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8461                    new_selection_ranges.push(cursor..cursor);
 8462                }
 8463                new_selection_ranges.push(selection.end..selection.end);
 8464                to_unfold.push(selection.start..selection.end);
 8465            }
 8466        }
 8467        self.unfold_ranges(&to_unfold, true, true, cx);
 8468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8469            s.select_ranges(new_selection_ranges);
 8470        });
 8471    }
 8472
 8473    pub fn add_selection_above(
 8474        &mut self,
 8475        _: &AddSelectionAbove,
 8476        window: &mut Window,
 8477        cx: &mut Context<Self>,
 8478    ) {
 8479        self.add_selection(true, window, cx);
 8480    }
 8481
 8482    pub fn add_selection_below(
 8483        &mut self,
 8484        _: &AddSelectionBelow,
 8485        window: &mut Window,
 8486        cx: &mut Context<Self>,
 8487    ) {
 8488        self.add_selection(false, window, cx);
 8489    }
 8490
 8491    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8493        let mut selections = self.selections.all::<Point>(cx);
 8494        let text_layout_details = self.text_layout_details(window);
 8495        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8496            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8497            let range = oldest_selection.display_range(&display_map).sorted();
 8498
 8499            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8500            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8501            let positions = start_x.min(end_x)..start_x.max(end_x);
 8502
 8503            selections.clear();
 8504            let mut stack = Vec::new();
 8505            for row in range.start.row().0..=range.end.row().0 {
 8506                if let Some(selection) = self.selections.build_columnar_selection(
 8507                    &display_map,
 8508                    DisplayRow(row),
 8509                    &positions,
 8510                    oldest_selection.reversed,
 8511                    &text_layout_details,
 8512                ) {
 8513                    stack.push(selection.id);
 8514                    selections.push(selection);
 8515                }
 8516            }
 8517
 8518            if above {
 8519                stack.reverse();
 8520            }
 8521
 8522            AddSelectionsState { above, stack }
 8523        });
 8524
 8525        let last_added_selection = *state.stack.last().unwrap();
 8526        let mut new_selections = Vec::new();
 8527        if above == state.above {
 8528            let end_row = if above {
 8529                DisplayRow(0)
 8530            } else {
 8531                display_map.max_point().row()
 8532            };
 8533
 8534            'outer: for selection in selections {
 8535                if selection.id == last_added_selection {
 8536                    let range = selection.display_range(&display_map).sorted();
 8537                    debug_assert_eq!(range.start.row(), range.end.row());
 8538                    let mut row = range.start.row();
 8539                    let positions =
 8540                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8541                            px(start)..px(end)
 8542                        } else {
 8543                            let start_x =
 8544                                display_map.x_for_display_point(range.start, &text_layout_details);
 8545                            let end_x =
 8546                                display_map.x_for_display_point(range.end, &text_layout_details);
 8547                            start_x.min(end_x)..start_x.max(end_x)
 8548                        };
 8549
 8550                    while row != end_row {
 8551                        if above {
 8552                            row.0 -= 1;
 8553                        } else {
 8554                            row.0 += 1;
 8555                        }
 8556
 8557                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8558                            &display_map,
 8559                            row,
 8560                            &positions,
 8561                            selection.reversed,
 8562                            &text_layout_details,
 8563                        ) {
 8564                            state.stack.push(new_selection.id);
 8565                            if above {
 8566                                new_selections.push(new_selection);
 8567                                new_selections.push(selection);
 8568                            } else {
 8569                                new_selections.push(selection);
 8570                                new_selections.push(new_selection);
 8571                            }
 8572
 8573                            continue 'outer;
 8574                        }
 8575                    }
 8576                }
 8577
 8578                new_selections.push(selection);
 8579            }
 8580        } else {
 8581            new_selections = selections;
 8582            new_selections.retain(|s| s.id != last_added_selection);
 8583            state.stack.pop();
 8584        }
 8585
 8586        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8587            s.select(new_selections);
 8588        });
 8589        if state.stack.len() > 1 {
 8590            self.add_selections_state = Some(state);
 8591        }
 8592    }
 8593
 8594    pub fn select_next_match_internal(
 8595        &mut self,
 8596        display_map: &DisplaySnapshot,
 8597        replace_newest: bool,
 8598        autoscroll: Option<Autoscroll>,
 8599        window: &mut Window,
 8600        cx: &mut Context<Self>,
 8601    ) -> Result<()> {
 8602        fn select_next_match_ranges(
 8603            this: &mut Editor,
 8604            range: Range<usize>,
 8605            replace_newest: bool,
 8606            auto_scroll: Option<Autoscroll>,
 8607            window: &mut Window,
 8608            cx: &mut Context<Editor>,
 8609        ) {
 8610            this.unfold_ranges(&[range.clone()], false, true, cx);
 8611            this.change_selections(auto_scroll, window, cx, |s| {
 8612                if replace_newest {
 8613                    s.delete(s.newest_anchor().id);
 8614                }
 8615                s.insert_range(range.clone());
 8616            });
 8617        }
 8618
 8619        let buffer = &display_map.buffer_snapshot;
 8620        let mut selections = self.selections.all::<usize>(cx);
 8621        if let Some(mut select_next_state) = self.select_next_state.take() {
 8622            let query = &select_next_state.query;
 8623            if !select_next_state.done {
 8624                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8625                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8626                let mut next_selected_range = None;
 8627
 8628                let bytes_after_last_selection =
 8629                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8630                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8631                let query_matches = query
 8632                    .stream_find_iter(bytes_after_last_selection)
 8633                    .map(|result| (last_selection.end, result))
 8634                    .chain(
 8635                        query
 8636                            .stream_find_iter(bytes_before_first_selection)
 8637                            .map(|result| (0, result)),
 8638                    );
 8639
 8640                for (start_offset, query_match) in query_matches {
 8641                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8642                    let offset_range =
 8643                        start_offset + query_match.start()..start_offset + query_match.end();
 8644                    let display_range = offset_range.start.to_display_point(display_map)
 8645                        ..offset_range.end.to_display_point(display_map);
 8646
 8647                    if !select_next_state.wordwise
 8648                        || (!movement::is_inside_word(display_map, display_range.start)
 8649                            && !movement::is_inside_word(display_map, display_range.end))
 8650                    {
 8651                        // TODO: This is n^2, because we might check all the selections
 8652                        if !selections
 8653                            .iter()
 8654                            .any(|selection| selection.range().overlaps(&offset_range))
 8655                        {
 8656                            next_selected_range = Some(offset_range);
 8657                            break;
 8658                        }
 8659                    }
 8660                }
 8661
 8662                if let Some(next_selected_range) = next_selected_range {
 8663                    select_next_match_ranges(
 8664                        self,
 8665                        next_selected_range,
 8666                        replace_newest,
 8667                        autoscroll,
 8668                        window,
 8669                        cx,
 8670                    );
 8671                } else {
 8672                    select_next_state.done = true;
 8673                }
 8674            }
 8675
 8676            self.select_next_state = Some(select_next_state);
 8677        } else {
 8678            let mut only_carets = true;
 8679            let mut same_text_selected = true;
 8680            let mut selected_text = None;
 8681
 8682            let mut selections_iter = selections.iter().peekable();
 8683            while let Some(selection) = selections_iter.next() {
 8684                if selection.start != selection.end {
 8685                    only_carets = false;
 8686                }
 8687
 8688                if same_text_selected {
 8689                    if selected_text.is_none() {
 8690                        selected_text =
 8691                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8692                    }
 8693
 8694                    if let Some(next_selection) = selections_iter.peek() {
 8695                        if next_selection.range().len() == selection.range().len() {
 8696                            let next_selected_text = buffer
 8697                                .text_for_range(next_selection.range())
 8698                                .collect::<String>();
 8699                            if Some(next_selected_text) != selected_text {
 8700                                same_text_selected = false;
 8701                                selected_text = None;
 8702                            }
 8703                        } else {
 8704                            same_text_selected = false;
 8705                            selected_text = None;
 8706                        }
 8707                    }
 8708                }
 8709            }
 8710
 8711            if only_carets {
 8712                for selection in &mut selections {
 8713                    let word_range = movement::surrounding_word(
 8714                        display_map,
 8715                        selection.start.to_display_point(display_map),
 8716                    );
 8717                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8718                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8719                    selection.goal = SelectionGoal::None;
 8720                    selection.reversed = false;
 8721                    select_next_match_ranges(
 8722                        self,
 8723                        selection.start..selection.end,
 8724                        replace_newest,
 8725                        autoscroll,
 8726                        window,
 8727                        cx,
 8728                    );
 8729                }
 8730
 8731                if selections.len() == 1 {
 8732                    let selection = selections
 8733                        .last()
 8734                        .expect("ensured that there's only one selection");
 8735                    let query = buffer
 8736                        .text_for_range(selection.start..selection.end)
 8737                        .collect::<String>();
 8738                    let is_empty = query.is_empty();
 8739                    let select_state = SelectNextState {
 8740                        query: AhoCorasick::new(&[query])?,
 8741                        wordwise: true,
 8742                        done: is_empty,
 8743                    };
 8744                    self.select_next_state = Some(select_state);
 8745                } else {
 8746                    self.select_next_state = None;
 8747                }
 8748            } else if let Some(selected_text) = selected_text {
 8749                self.select_next_state = Some(SelectNextState {
 8750                    query: AhoCorasick::new(&[selected_text])?,
 8751                    wordwise: false,
 8752                    done: false,
 8753                });
 8754                self.select_next_match_internal(
 8755                    display_map,
 8756                    replace_newest,
 8757                    autoscroll,
 8758                    window,
 8759                    cx,
 8760                )?;
 8761            }
 8762        }
 8763        Ok(())
 8764    }
 8765
 8766    pub fn select_all_matches(
 8767        &mut self,
 8768        _action: &SelectAllMatches,
 8769        window: &mut Window,
 8770        cx: &mut Context<Self>,
 8771    ) -> Result<()> {
 8772        self.push_to_selection_history();
 8773        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8774
 8775        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8776        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8777            return Ok(());
 8778        };
 8779        if select_next_state.done {
 8780            return Ok(());
 8781        }
 8782
 8783        let mut new_selections = self.selections.all::<usize>(cx);
 8784
 8785        let buffer = &display_map.buffer_snapshot;
 8786        let query_matches = select_next_state
 8787            .query
 8788            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8789
 8790        for query_match in query_matches {
 8791            let query_match = query_match.unwrap(); // can only fail due to I/O
 8792            let offset_range = query_match.start()..query_match.end();
 8793            let display_range = offset_range.start.to_display_point(&display_map)
 8794                ..offset_range.end.to_display_point(&display_map);
 8795
 8796            if !select_next_state.wordwise
 8797                || (!movement::is_inside_word(&display_map, display_range.start)
 8798                    && !movement::is_inside_word(&display_map, display_range.end))
 8799            {
 8800                self.selections.change_with(cx, |selections| {
 8801                    new_selections.push(Selection {
 8802                        id: selections.new_selection_id(),
 8803                        start: offset_range.start,
 8804                        end: offset_range.end,
 8805                        reversed: false,
 8806                        goal: SelectionGoal::None,
 8807                    });
 8808                });
 8809            }
 8810        }
 8811
 8812        new_selections.sort_by_key(|selection| selection.start);
 8813        let mut ix = 0;
 8814        while ix + 1 < new_selections.len() {
 8815            let current_selection = &new_selections[ix];
 8816            let next_selection = &new_selections[ix + 1];
 8817            if current_selection.range().overlaps(&next_selection.range()) {
 8818                if current_selection.id < next_selection.id {
 8819                    new_selections.remove(ix + 1);
 8820                } else {
 8821                    new_selections.remove(ix);
 8822                }
 8823            } else {
 8824                ix += 1;
 8825            }
 8826        }
 8827
 8828        select_next_state.done = true;
 8829        self.unfold_ranges(
 8830            &new_selections
 8831                .iter()
 8832                .map(|selection| selection.range())
 8833                .collect::<Vec<_>>(),
 8834            false,
 8835            false,
 8836            cx,
 8837        );
 8838        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8839            selections.select(new_selections)
 8840        });
 8841
 8842        Ok(())
 8843    }
 8844
 8845    pub fn select_next(
 8846        &mut self,
 8847        action: &SelectNext,
 8848        window: &mut Window,
 8849        cx: &mut Context<Self>,
 8850    ) -> Result<()> {
 8851        self.push_to_selection_history();
 8852        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8853        self.select_next_match_internal(
 8854            &display_map,
 8855            action.replace_newest,
 8856            Some(Autoscroll::newest()),
 8857            window,
 8858            cx,
 8859        )?;
 8860        Ok(())
 8861    }
 8862
 8863    pub fn select_previous(
 8864        &mut self,
 8865        action: &SelectPrevious,
 8866        window: &mut Window,
 8867        cx: &mut Context<Self>,
 8868    ) -> Result<()> {
 8869        self.push_to_selection_history();
 8870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8871        let buffer = &display_map.buffer_snapshot;
 8872        let mut selections = self.selections.all::<usize>(cx);
 8873        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8874            let query = &select_prev_state.query;
 8875            if !select_prev_state.done {
 8876                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8877                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8878                let mut next_selected_range = None;
 8879                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8880                let bytes_before_last_selection =
 8881                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8882                let bytes_after_first_selection =
 8883                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8884                let query_matches = query
 8885                    .stream_find_iter(bytes_before_last_selection)
 8886                    .map(|result| (last_selection.start, result))
 8887                    .chain(
 8888                        query
 8889                            .stream_find_iter(bytes_after_first_selection)
 8890                            .map(|result| (buffer.len(), result)),
 8891                    );
 8892                for (end_offset, query_match) in query_matches {
 8893                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8894                    let offset_range =
 8895                        end_offset - query_match.end()..end_offset - query_match.start();
 8896                    let display_range = offset_range.start.to_display_point(&display_map)
 8897                        ..offset_range.end.to_display_point(&display_map);
 8898
 8899                    if !select_prev_state.wordwise
 8900                        || (!movement::is_inside_word(&display_map, display_range.start)
 8901                            && !movement::is_inside_word(&display_map, display_range.end))
 8902                    {
 8903                        next_selected_range = Some(offset_range);
 8904                        break;
 8905                    }
 8906                }
 8907
 8908                if let Some(next_selected_range) = next_selected_range {
 8909                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8910                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8911                        if action.replace_newest {
 8912                            s.delete(s.newest_anchor().id);
 8913                        }
 8914                        s.insert_range(next_selected_range);
 8915                    });
 8916                } else {
 8917                    select_prev_state.done = true;
 8918                }
 8919            }
 8920
 8921            self.select_prev_state = Some(select_prev_state);
 8922        } else {
 8923            let mut only_carets = true;
 8924            let mut same_text_selected = true;
 8925            let mut selected_text = None;
 8926
 8927            let mut selections_iter = selections.iter().peekable();
 8928            while let Some(selection) = selections_iter.next() {
 8929                if selection.start != selection.end {
 8930                    only_carets = false;
 8931                }
 8932
 8933                if same_text_selected {
 8934                    if selected_text.is_none() {
 8935                        selected_text =
 8936                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8937                    }
 8938
 8939                    if let Some(next_selection) = selections_iter.peek() {
 8940                        if next_selection.range().len() == selection.range().len() {
 8941                            let next_selected_text = buffer
 8942                                .text_for_range(next_selection.range())
 8943                                .collect::<String>();
 8944                            if Some(next_selected_text) != selected_text {
 8945                                same_text_selected = false;
 8946                                selected_text = None;
 8947                            }
 8948                        } else {
 8949                            same_text_selected = false;
 8950                            selected_text = None;
 8951                        }
 8952                    }
 8953                }
 8954            }
 8955
 8956            if only_carets {
 8957                for selection in &mut selections {
 8958                    let word_range = movement::surrounding_word(
 8959                        &display_map,
 8960                        selection.start.to_display_point(&display_map),
 8961                    );
 8962                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8963                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8964                    selection.goal = SelectionGoal::None;
 8965                    selection.reversed = false;
 8966                }
 8967                if selections.len() == 1 {
 8968                    let selection = selections
 8969                        .last()
 8970                        .expect("ensured that there's only one selection");
 8971                    let query = buffer
 8972                        .text_for_range(selection.start..selection.end)
 8973                        .collect::<String>();
 8974                    let is_empty = query.is_empty();
 8975                    let select_state = SelectNextState {
 8976                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8977                        wordwise: true,
 8978                        done: is_empty,
 8979                    };
 8980                    self.select_prev_state = Some(select_state);
 8981                } else {
 8982                    self.select_prev_state = None;
 8983                }
 8984
 8985                self.unfold_ranges(
 8986                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8987                    false,
 8988                    true,
 8989                    cx,
 8990                );
 8991                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8992                    s.select(selections);
 8993                });
 8994            } else if let Some(selected_text) = selected_text {
 8995                self.select_prev_state = Some(SelectNextState {
 8996                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8997                    wordwise: false,
 8998                    done: false,
 8999                });
 9000                self.select_previous(action, window, cx)?;
 9001            }
 9002        }
 9003        Ok(())
 9004    }
 9005
 9006    pub fn toggle_comments(
 9007        &mut self,
 9008        action: &ToggleComments,
 9009        window: &mut Window,
 9010        cx: &mut Context<Self>,
 9011    ) {
 9012        if self.read_only(cx) {
 9013            return;
 9014        }
 9015        let text_layout_details = &self.text_layout_details(window);
 9016        self.transact(window, cx, |this, window, cx| {
 9017            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9018            let mut edits = Vec::new();
 9019            let mut selection_edit_ranges = Vec::new();
 9020            let mut last_toggled_row = None;
 9021            let snapshot = this.buffer.read(cx).read(cx);
 9022            let empty_str: Arc<str> = Arc::default();
 9023            let mut suffixes_inserted = Vec::new();
 9024            let ignore_indent = action.ignore_indent;
 9025
 9026            fn comment_prefix_range(
 9027                snapshot: &MultiBufferSnapshot,
 9028                row: MultiBufferRow,
 9029                comment_prefix: &str,
 9030                comment_prefix_whitespace: &str,
 9031                ignore_indent: bool,
 9032            ) -> Range<Point> {
 9033                let indent_size = if ignore_indent {
 9034                    0
 9035                } else {
 9036                    snapshot.indent_size_for_line(row).len
 9037                };
 9038
 9039                let start = Point::new(row.0, indent_size);
 9040
 9041                let mut line_bytes = snapshot
 9042                    .bytes_in_range(start..snapshot.max_point())
 9043                    .flatten()
 9044                    .copied();
 9045
 9046                // If this line currently begins with the line comment prefix, then record
 9047                // the range containing the prefix.
 9048                if line_bytes
 9049                    .by_ref()
 9050                    .take(comment_prefix.len())
 9051                    .eq(comment_prefix.bytes())
 9052                {
 9053                    // Include any whitespace that matches the comment prefix.
 9054                    let matching_whitespace_len = line_bytes
 9055                        .zip(comment_prefix_whitespace.bytes())
 9056                        .take_while(|(a, b)| a == b)
 9057                        .count() as u32;
 9058                    let end = Point::new(
 9059                        start.row,
 9060                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9061                    );
 9062                    start..end
 9063                } else {
 9064                    start..start
 9065                }
 9066            }
 9067
 9068            fn comment_suffix_range(
 9069                snapshot: &MultiBufferSnapshot,
 9070                row: MultiBufferRow,
 9071                comment_suffix: &str,
 9072                comment_suffix_has_leading_space: bool,
 9073            ) -> Range<Point> {
 9074                let end = Point::new(row.0, snapshot.line_len(row));
 9075                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9076
 9077                let mut line_end_bytes = snapshot
 9078                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9079                    .flatten()
 9080                    .copied();
 9081
 9082                let leading_space_len = if suffix_start_column > 0
 9083                    && line_end_bytes.next() == Some(b' ')
 9084                    && comment_suffix_has_leading_space
 9085                {
 9086                    1
 9087                } else {
 9088                    0
 9089                };
 9090
 9091                // If this line currently begins with the line comment prefix, then record
 9092                // the range containing the prefix.
 9093                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9094                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9095                    start..end
 9096                } else {
 9097                    end..end
 9098                }
 9099            }
 9100
 9101            // TODO: Handle selections that cross excerpts
 9102            for selection in &mut selections {
 9103                let start_column = snapshot
 9104                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9105                    .len;
 9106                let language = if let Some(language) =
 9107                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9108                {
 9109                    language
 9110                } else {
 9111                    continue;
 9112                };
 9113
 9114                selection_edit_ranges.clear();
 9115
 9116                // If multiple selections contain a given row, avoid processing that
 9117                // row more than once.
 9118                let mut start_row = MultiBufferRow(selection.start.row);
 9119                if last_toggled_row == Some(start_row) {
 9120                    start_row = start_row.next_row();
 9121                }
 9122                let end_row =
 9123                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9124                        MultiBufferRow(selection.end.row - 1)
 9125                    } else {
 9126                        MultiBufferRow(selection.end.row)
 9127                    };
 9128                last_toggled_row = Some(end_row);
 9129
 9130                if start_row > end_row {
 9131                    continue;
 9132                }
 9133
 9134                // If the language has line comments, toggle those.
 9135                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9136
 9137                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9138                if ignore_indent {
 9139                    full_comment_prefixes = full_comment_prefixes
 9140                        .into_iter()
 9141                        .map(|s| Arc::from(s.trim_end()))
 9142                        .collect();
 9143                }
 9144
 9145                if !full_comment_prefixes.is_empty() {
 9146                    let first_prefix = full_comment_prefixes
 9147                        .first()
 9148                        .expect("prefixes is non-empty");
 9149                    let prefix_trimmed_lengths = full_comment_prefixes
 9150                        .iter()
 9151                        .map(|p| p.trim_end_matches(' ').len())
 9152                        .collect::<SmallVec<[usize; 4]>>();
 9153
 9154                    let mut all_selection_lines_are_comments = true;
 9155
 9156                    for row in start_row.0..=end_row.0 {
 9157                        let row = MultiBufferRow(row);
 9158                        if start_row < end_row && snapshot.is_line_blank(row) {
 9159                            continue;
 9160                        }
 9161
 9162                        let prefix_range = full_comment_prefixes
 9163                            .iter()
 9164                            .zip(prefix_trimmed_lengths.iter().copied())
 9165                            .map(|(prefix, trimmed_prefix_len)| {
 9166                                comment_prefix_range(
 9167                                    snapshot.deref(),
 9168                                    row,
 9169                                    &prefix[..trimmed_prefix_len],
 9170                                    &prefix[trimmed_prefix_len..],
 9171                                    ignore_indent,
 9172                                )
 9173                            })
 9174                            .max_by_key(|range| range.end.column - range.start.column)
 9175                            .expect("prefixes is non-empty");
 9176
 9177                        if prefix_range.is_empty() {
 9178                            all_selection_lines_are_comments = false;
 9179                        }
 9180
 9181                        selection_edit_ranges.push(prefix_range);
 9182                    }
 9183
 9184                    if all_selection_lines_are_comments {
 9185                        edits.extend(
 9186                            selection_edit_ranges
 9187                                .iter()
 9188                                .cloned()
 9189                                .map(|range| (range, empty_str.clone())),
 9190                        );
 9191                    } else {
 9192                        let min_column = selection_edit_ranges
 9193                            .iter()
 9194                            .map(|range| range.start.column)
 9195                            .min()
 9196                            .unwrap_or(0);
 9197                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9198                            let position = Point::new(range.start.row, min_column);
 9199                            (position..position, first_prefix.clone())
 9200                        }));
 9201                    }
 9202                } else if let Some((full_comment_prefix, comment_suffix)) =
 9203                    language.block_comment_delimiters()
 9204                {
 9205                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9206                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9207                    let prefix_range = comment_prefix_range(
 9208                        snapshot.deref(),
 9209                        start_row,
 9210                        comment_prefix,
 9211                        comment_prefix_whitespace,
 9212                        ignore_indent,
 9213                    );
 9214                    let suffix_range = comment_suffix_range(
 9215                        snapshot.deref(),
 9216                        end_row,
 9217                        comment_suffix.trim_start_matches(' '),
 9218                        comment_suffix.starts_with(' '),
 9219                    );
 9220
 9221                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9222                        edits.push((
 9223                            prefix_range.start..prefix_range.start,
 9224                            full_comment_prefix.clone(),
 9225                        ));
 9226                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9227                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9228                    } else {
 9229                        edits.push((prefix_range, empty_str.clone()));
 9230                        edits.push((suffix_range, empty_str.clone()));
 9231                    }
 9232                } else {
 9233                    continue;
 9234                }
 9235            }
 9236
 9237            drop(snapshot);
 9238            this.buffer.update(cx, |buffer, cx| {
 9239                buffer.edit(edits, None, cx);
 9240            });
 9241
 9242            // Adjust selections so that they end before any comment suffixes that
 9243            // were inserted.
 9244            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9245            let mut selections = this.selections.all::<Point>(cx);
 9246            let snapshot = this.buffer.read(cx).read(cx);
 9247            for selection in &mut selections {
 9248                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9249                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9250                        Ordering::Less => {
 9251                            suffixes_inserted.next();
 9252                            continue;
 9253                        }
 9254                        Ordering::Greater => break,
 9255                        Ordering::Equal => {
 9256                            if selection.end.column == snapshot.line_len(row) {
 9257                                if selection.is_empty() {
 9258                                    selection.start.column -= suffix_len as u32;
 9259                                }
 9260                                selection.end.column -= suffix_len as u32;
 9261                            }
 9262                            break;
 9263                        }
 9264                    }
 9265                }
 9266            }
 9267
 9268            drop(snapshot);
 9269            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9270                s.select(selections)
 9271            });
 9272
 9273            let selections = this.selections.all::<Point>(cx);
 9274            let selections_on_single_row = selections.windows(2).all(|selections| {
 9275                selections[0].start.row == selections[1].start.row
 9276                    && selections[0].end.row == selections[1].end.row
 9277                    && selections[0].start.row == selections[0].end.row
 9278            });
 9279            let selections_selecting = selections
 9280                .iter()
 9281                .any(|selection| selection.start != selection.end);
 9282            let advance_downwards = action.advance_downwards
 9283                && selections_on_single_row
 9284                && !selections_selecting
 9285                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9286
 9287            if advance_downwards {
 9288                let snapshot = this.buffer.read(cx).snapshot(cx);
 9289
 9290                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9291                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9292                        let mut point = display_point.to_point(display_snapshot);
 9293                        point.row += 1;
 9294                        point = snapshot.clip_point(point, Bias::Left);
 9295                        let display_point = point.to_display_point(display_snapshot);
 9296                        let goal = SelectionGoal::HorizontalPosition(
 9297                            display_snapshot
 9298                                .x_for_display_point(display_point, text_layout_details)
 9299                                .into(),
 9300                        );
 9301                        (display_point, goal)
 9302                    })
 9303                });
 9304            }
 9305        });
 9306    }
 9307
 9308    pub fn select_enclosing_symbol(
 9309        &mut self,
 9310        _: &SelectEnclosingSymbol,
 9311        window: &mut Window,
 9312        cx: &mut Context<Self>,
 9313    ) {
 9314        let buffer = self.buffer.read(cx).snapshot(cx);
 9315        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9316
 9317        fn update_selection(
 9318            selection: &Selection<usize>,
 9319            buffer_snap: &MultiBufferSnapshot,
 9320        ) -> Option<Selection<usize>> {
 9321            let cursor = selection.head();
 9322            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9323            for symbol in symbols.iter().rev() {
 9324                let start = symbol.range.start.to_offset(buffer_snap);
 9325                let end = symbol.range.end.to_offset(buffer_snap);
 9326                let new_range = start..end;
 9327                if start < selection.start || end > selection.end {
 9328                    return Some(Selection {
 9329                        id: selection.id,
 9330                        start: new_range.start,
 9331                        end: new_range.end,
 9332                        goal: SelectionGoal::None,
 9333                        reversed: selection.reversed,
 9334                    });
 9335                }
 9336            }
 9337            None
 9338        }
 9339
 9340        let mut selected_larger_symbol = false;
 9341        let new_selections = old_selections
 9342            .iter()
 9343            .map(|selection| match update_selection(selection, &buffer) {
 9344                Some(new_selection) => {
 9345                    if new_selection.range() != selection.range() {
 9346                        selected_larger_symbol = true;
 9347                    }
 9348                    new_selection
 9349                }
 9350                None => selection.clone(),
 9351            })
 9352            .collect::<Vec<_>>();
 9353
 9354        if selected_larger_symbol {
 9355            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9356                s.select(new_selections);
 9357            });
 9358        }
 9359    }
 9360
 9361    pub fn select_larger_syntax_node(
 9362        &mut self,
 9363        _: &SelectLargerSyntaxNode,
 9364        window: &mut Window,
 9365        cx: &mut Context<Self>,
 9366    ) {
 9367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9368        let buffer = self.buffer.read(cx).snapshot(cx);
 9369        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9370
 9371        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9372        let mut selected_larger_node = false;
 9373        let new_selections = old_selections
 9374            .iter()
 9375            .map(|selection| {
 9376                let old_range = selection.start..selection.end;
 9377                let mut new_range = old_range.clone();
 9378                let mut new_node = None;
 9379                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9380                {
 9381                    new_node = Some(node);
 9382                    new_range = containing_range;
 9383                    if !display_map.intersects_fold(new_range.start)
 9384                        && !display_map.intersects_fold(new_range.end)
 9385                    {
 9386                        break;
 9387                    }
 9388                }
 9389
 9390                if let Some(node) = new_node {
 9391                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9392                    // nodes. Parent and grandparent are also logged because this operation will not
 9393                    // visit nodes that have the same range as their parent.
 9394                    log::info!("Node: {node:?}");
 9395                    let parent = node.parent();
 9396                    log::info!("Parent: {parent:?}");
 9397                    let grandparent = parent.and_then(|x| x.parent());
 9398                    log::info!("Grandparent: {grandparent:?}");
 9399                }
 9400
 9401                selected_larger_node |= new_range != old_range;
 9402                Selection {
 9403                    id: selection.id,
 9404                    start: new_range.start,
 9405                    end: new_range.end,
 9406                    goal: SelectionGoal::None,
 9407                    reversed: selection.reversed,
 9408                }
 9409            })
 9410            .collect::<Vec<_>>();
 9411
 9412        if selected_larger_node {
 9413            stack.push(old_selections);
 9414            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9415                s.select(new_selections);
 9416            });
 9417        }
 9418        self.select_larger_syntax_node_stack = stack;
 9419    }
 9420
 9421    pub fn select_smaller_syntax_node(
 9422        &mut self,
 9423        _: &SelectSmallerSyntaxNode,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) {
 9427        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9428        if let Some(selections) = stack.pop() {
 9429            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9430                s.select(selections.to_vec());
 9431            });
 9432        }
 9433        self.select_larger_syntax_node_stack = stack;
 9434    }
 9435
 9436    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9437        if !EditorSettings::get_global(cx).gutter.runnables {
 9438            self.clear_tasks();
 9439            return Task::ready(());
 9440        }
 9441        let project = self.project.as_ref().map(Entity::downgrade);
 9442        cx.spawn_in(window, |this, mut cx| async move {
 9443            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9444            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9445                return;
 9446            };
 9447            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9448                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9449            }) else {
 9450                return;
 9451            };
 9452
 9453            let hide_runnables = project
 9454                .update(&mut cx, |project, cx| {
 9455                    // Do not display any test indicators in non-dev server remote projects.
 9456                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9457                })
 9458                .unwrap_or(true);
 9459            if hide_runnables {
 9460                return;
 9461            }
 9462            let new_rows =
 9463                cx.background_executor()
 9464                    .spawn({
 9465                        let snapshot = display_snapshot.clone();
 9466                        async move {
 9467                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9468                        }
 9469                    })
 9470                    .await;
 9471
 9472            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9473            this.update(&mut cx, |this, _| {
 9474                this.clear_tasks();
 9475                for (key, value) in rows {
 9476                    this.insert_tasks(key, value);
 9477                }
 9478            })
 9479            .ok();
 9480        })
 9481    }
 9482    fn fetch_runnable_ranges(
 9483        snapshot: &DisplaySnapshot,
 9484        range: Range<Anchor>,
 9485    ) -> Vec<language::RunnableRange> {
 9486        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9487    }
 9488
 9489    fn runnable_rows(
 9490        project: Entity<Project>,
 9491        snapshot: DisplaySnapshot,
 9492        runnable_ranges: Vec<RunnableRange>,
 9493        mut cx: AsyncWindowContext,
 9494    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9495        runnable_ranges
 9496            .into_iter()
 9497            .filter_map(|mut runnable| {
 9498                let tasks = cx
 9499                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9500                    .ok()?;
 9501                if tasks.is_empty() {
 9502                    return None;
 9503                }
 9504
 9505                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9506
 9507                let row = snapshot
 9508                    .buffer_snapshot
 9509                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9510                    .1
 9511                    .start
 9512                    .row;
 9513
 9514                let context_range =
 9515                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9516                Some((
 9517                    (runnable.buffer_id, row),
 9518                    RunnableTasks {
 9519                        templates: tasks,
 9520                        offset: MultiBufferOffset(runnable.run_range.start),
 9521                        context_range,
 9522                        column: point.column,
 9523                        extra_variables: runnable.extra_captures,
 9524                    },
 9525                ))
 9526            })
 9527            .collect()
 9528    }
 9529
 9530    fn templates_with_tags(
 9531        project: &Entity<Project>,
 9532        runnable: &mut Runnable,
 9533        cx: &mut App,
 9534    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9535        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9536            let (worktree_id, file) = project
 9537                .buffer_for_id(runnable.buffer, cx)
 9538                .and_then(|buffer| buffer.read(cx).file())
 9539                .map(|file| (file.worktree_id(cx), file.clone()))
 9540                .unzip();
 9541
 9542            (
 9543                project.task_store().read(cx).task_inventory().cloned(),
 9544                worktree_id,
 9545                file,
 9546            )
 9547        });
 9548
 9549        let tags = mem::take(&mut runnable.tags);
 9550        let mut tags: Vec<_> = tags
 9551            .into_iter()
 9552            .flat_map(|tag| {
 9553                let tag = tag.0.clone();
 9554                inventory
 9555                    .as_ref()
 9556                    .into_iter()
 9557                    .flat_map(|inventory| {
 9558                        inventory.read(cx).list_tasks(
 9559                            file.clone(),
 9560                            Some(runnable.language.clone()),
 9561                            worktree_id,
 9562                            cx,
 9563                        )
 9564                    })
 9565                    .filter(move |(_, template)| {
 9566                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9567                    })
 9568            })
 9569            .sorted_by_key(|(kind, _)| kind.to_owned())
 9570            .collect();
 9571        if let Some((leading_tag_source, _)) = tags.first() {
 9572            // Strongest source wins; if we have worktree tag binding, prefer that to
 9573            // global and language bindings;
 9574            // if we have a global binding, prefer that to language binding.
 9575            let first_mismatch = tags
 9576                .iter()
 9577                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9578            if let Some(index) = first_mismatch {
 9579                tags.truncate(index);
 9580            }
 9581        }
 9582
 9583        tags
 9584    }
 9585
 9586    pub fn move_to_enclosing_bracket(
 9587        &mut self,
 9588        _: &MoveToEnclosingBracket,
 9589        window: &mut Window,
 9590        cx: &mut Context<Self>,
 9591    ) {
 9592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9593            s.move_offsets_with(|snapshot, selection| {
 9594                let Some(enclosing_bracket_ranges) =
 9595                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9596                else {
 9597                    return;
 9598                };
 9599
 9600                let mut best_length = usize::MAX;
 9601                let mut best_inside = false;
 9602                let mut best_in_bracket_range = false;
 9603                let mut best_destination = None;
 9604                for (open, close) in enclosing_bracket_ranges {
 9605                    let close = close.to_inclusive();
 9606                    let length = close.end() - open.start;
 9607                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9608                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9609                        || close.contains(&selection.head());
 9610
 9611                    // If best is next to a bracket and current isn't, skip
 9612                    if !in_bracket_range && best_in_bracket_range {
 9613                        continue;
 9614                    }
 9615
 9616                    // Prefer smaller lengths unless best is inside and current isn't
 9617                    if length > best_length && (best_inside || !inside) {
 9618                        continue;
 9619                    }
 9620
 9621                    best_length = length;
 9622                    best_inside = inside;
 9623                    best_in_bracket_range = in_bracket_range;
 9624                    best_destination = Some(
 9625                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9626                            if inside {
 9627                                open.end
 9628                            } else {
 9629                                open.start
 9630                            }
 9631                        } else if inside {
 9632                            *close.start()
 9633                        } else {
 9634                            *close.end()
 9635                        },
 9636                    );
 9637                }
 9638
 9639                if let Some(destination) = best_destination {
 9640                    selection.collapse_to(destination, SelectionGoal::None);
 9641                }
 9642            })
 9643        });
 9644    }
 9645
 9646    pub fn undo_selection(
 9647        &mut self,
 9648        _: &UndoSelection,
 9649        window: &mut Window,
 9650        cx: &mut Context<Self>,
 9651    ) {
 9652        self.end_selection(window, cx);
 9653        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9654        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9655            self.change_selections(None, window, cx, |s| {
 9656                s.select_anchors(entry.selections.to_vec())
 9657            });
 9658            self.select_next_state = entry.select_next_state;
 9659            self.select_prev_state = entry.select_prev_state;
 9660            self.add_selections_state = entry.add_selections_state;
 9661            self.request_autoscroll(Autoscroll::newest(), cx);
 9662        }
 9663        self.selection_history.mode = SelectionHistoryMode::Normal;
 9664    }
 9665
 9666    pub fn redo_selection(
 9667        &mut self,
 9668        _: &RedoSelection,
 9669        window: &mut Window,
 9670        cx: &mut Context<Self>,
 9671    ) {
 9672        self.end_selection(window, cx);
 9673        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9674        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9675            self.change_selections(None, window, cx, |s| {
 9676                s.select_anchors(entry.selections.to_vec())
 9677            });
 9678            self.select_next_state = entry.select_next_state;
 9679            self.select_prev_state = entry.select_prev_state;
 9680            self.add_selections_state = entry.add_selections_state;
 9681            self.request_autoscroll(Autoscroll::newest(), cx);
 9682        }
 9683        self.selection_history.mode = SelectionHistoryMode::Normal;
 9684    }
 9685
 9686    pub fn expand_excerpts(
 9687        &mut self,
 9688        action: &ExpandExcerpts,
 9689        _: &mut Window,
 9690        cx: &mut Context<Self>,
 9691    ) {
 9692        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9693    }
 9694
 9695    pub fn expand_excerpts_down(
 9696        &mut self,
 9697        action: &ExpandExcerptsDown,
 9698        _: &mut Window,
 9699        cx: &mut Context<Self>,
 9700    ) {
 9701        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9702    }
 9703
 9704    pub fn expand_excerpts_up(
 9705        &mut self,
 9706        action: &ExpandExcerptsUp,
 9707        _: &mut Window,
 9708        cx: &mut Context<Self>,
 9709    ) {
 9710        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9711    }
 9712
 9713    pub fn expand_excerpts_for_direction(
 9714        &mut self,
 9715        lines: u32,
 9716        direction: ExpandExcerptDirection,
 9717
 9718        cx: &mut Context<Self>,
 9719    ) {
 9720        let selections = self.selections.disjoint_anchors();
 9721
 9722        let lines = if lines == 0 {
 9723            EditorSettings::get_global(cx).expand_excerpt_lines
 9724        } else {
 9725            lines
 9726        };
 9727
 9728        self.buffer.update(cx, |buffer, cx| {
 9729            let snapshot = buffer.snapshot(cx);
 9730            let mut excerpt_ids = selections
 9731                .iter()
 9732                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9733                .collect::<Vec<_>>();
 9734            excerpt_ids.sort();
 9735            excerpt_ids.dedup();
 9736            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9737        })
 9738    }
 9739
 9740    pub fn expand_excerpt(
 9741        &mut self,
 9742        excerpt: ExcerptId,
 9743        direction: ExpandExcerptDirection,
 9744        cx: &mut Context<Self>,
 9745    ) {
 9746        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9747        self.buffer.update(cx, |buffer, cx| {
 9748            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9749        })
 9750    }
 9751
 9752    pub fn go_to_singleton_buffer_point(
 9753        &mut self,
 9754        point: Point,
 9755        window: &mut Window,
 9756        cx: &mut Context<Self>,
 9757    ) {
 9758        self.go_to_singleton_buffer_range(point..point, window, cx);
 9759    }
 9760
 9761    pub fn go_to_singleton_buffer_range(
 9762        &mut self,
 9763        range: Range<Point>,
 9764        window: &mut Window,
 9765        cx: &mut Context<Self>,
 9766    ) {
 9767        let multibuffer = self.buffer().read(cx);
 9768        let Some(buffer) = multibuffer.as_singleton() else {
 9769            return;
 9770        };
 9771        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9772            return;
 9773        };
 9774        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9775            return;
 9776        };
 9777        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9778            s.select_anchor_ranges([start..end])
 9779        });
 9780    }
 9781
 9782    fn go_to_diagnostic(
 9783        &mut self,
 9784        _: &GoToDiagnostic,
 9785        window: &mut Window,
 9786        cx: &mut Context<Self>,
 9787    ) {
 9788        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9789    }
 9790
 9791    fn go_to_prev_diagnostic(
 9792        &mut self,
 9793        _: &GoToPrevDiagnostic,
 9794        window: &mut Window,
 9795        cx: &mut Context<Self>,
 9796    ) {
 9797        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9798    }
 9799
 9800    pub fn go_to_diagnostic_impl(
 9801        &mut self,
 9802        direction: Direction,
 9803        window: &mut Window,
 9804        cx: &mut Context<Self>,
 9805    ) {
 9806        let buffer = self.buffer.read(cx).snapshot(cx);
 9807        let selection = self.selections.newest::<usize>(cx);
 9808
 9809        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9810        if direction == Direction::Next {
 9811            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9812                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9813                    return;
 9814                };
 9815                self.activate_diagnostics(
 9816                    buffer_id,
 9817                    popover.local_diagnostic.diagnostic.group_id,
 9818                    window,
 9819                    cx,
 9820                );
 9821                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9822                    let primary_range_start = active_diagnostics.primary_range.start;
 9823                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9824                        let mut new_selection = s.newest_anchor().clone();
 9825                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9826                        s.select_anchors(vec![new_selection.clone()]);
 9827                    });
 9828                    self.refresh_inline_completion(false, true, window, cx);
 9829                }
 9830                return;
 9831            }
 9832        }
 9833
 9834        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9835            active_diagnostics
 9836                .primary_range
 9837                .to_offset(&buffer)
 9838                .to_inclusive()
 9839        });
 9840        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9841            if active_primary_range.contains(&selection.head()) {
 9842                *active_primary_range.start()
 9843            } else {
 9844                selection.head()
 9845            }
 9846        } else {
 9847            selection.head()
 9848        };
 9849        let snapshot = self.snapshot(window, cx);
 9850        loop {
 9851            let mut diagnostics;
 9852            if direction == Direction::Prev {
 9853                diagnostics = buffer
 9854                    .diagnostics_in_range::<_, usize>(0..search_start)
 9855                    .collect::<Vec<_>>();
 9856                diagnostics.reverse();
 9857            } else {
 9858                diagnostics = buffer
 9859                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9860                    .collect::<Vec<_>>();
 9861            };
 9862            let group = diagnostics
 9863                .into_iter()
 9864                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9865                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9866                // be sorted in a stable way
 9867                // skip until we are at current active diagnostic, if it exists
 9868                .skip_while(|entry| {
 9869                    let is_in_range = match direction {
 9870                        Direction::Prev => entry.range.end > search_start,
 9871                        Direction::Next => entry.range.start < search_start,
 9872                    };
 9873                    is_in_range
 9874                        && self
 9875                            .active_diagnostics
 9876                            .as_ref()
 9877                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9878                })
 9879                .find_map(|entry| {
 9880                    if entry.diagnostic.is_primary
 9881                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9882                        && entry.range.start != entry.range.end
 9883                        // if we match with the active diagnostic, skip it
 9884                        && Some(entry.diagnostic.group_id)
 9885                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9886                    {
 9887                        Some((entry.range, entry.diagnostic.group_id))
 9888                    } else {
 9889                        None
 9890                    }
 9891                });
 9892
 9893            if let Some((primary_range, group_id)) = group {
 9894                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9895                    return;
 9896                };
 9897                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9898                if self.active_diagnostics.is_some() {
 9899                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9900                        s.select(vec![Selection {
 9901                            id: selection.id,
 9902                            start: primary_range.start,
 9903                            end: primary_range.start,
 9904                            reversed: false,
 9905                            goal: SelectionGoal::None,
 9906                        }]);
 9907                    });
 9908                    self.refresh_inline_completion(false, true, window, cx);
 9909                }
 9910                break;
 9911            } else {
 9912                // Cycle around to the start of the buffer, potentially moving back to the start of
 9913                // the currently active diagnostic.
 9914                active_primary_range.take();
 9915                if direction == Direction::Prev {
 9916                    if search_start == buffer.len() {
 9917                        break;
 9918                    } else {
 9919                        search_start = buffer.len();
 9920                    }
 9921                } else if search_start == 0 {
 9922                    break;
 9923                } else {
 9924                    search_start = 0;
 9925                }
 9926            }
 9927        }
 9928    }
 9929
 9930    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9931        let snapshot = self.snapshot(window, cx);
 9932        let selection = self.selections.newest::<Point>(cx);
 9933        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9934    }
 9935
 9936    fn go_to_hunk_after_position(
 9937        &mut self,
 9938        snapshot: &EditorSnapshot,
 9939        position: Point,
 9940        window: &mut Window,
 9941        cx: &mut Context<Editor>,
 9942    ) -> Option<MultiBufferDiffHunk> {
 9943        let mut hunk = snapshot
 9944            .buffer_snapshot
 9945            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9946            .find(|hunk| hunk.row_range.start.0 > position.row);
 9947        if hunk.is_none() {
 9948            hunk = snapshot
 9949                .buffer_snapshot
 9950                .diff_hunks_in_range(Point::zero()..position)
 9951                .find(|hunk| hunk.row_range.end.0 < position.row)
 9952        }
 9953        if let Some(hunk) = &hunk {
 9954            let destination = Point::new(hunk.row_range.start.0, 0);
 9955            self.unfold_ranges(&[destination..destination], false, false, cx);
 9956            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9957                s.select_ranges(vec![destination..destination]);
 9958            });
 9959        }
 9960
 9961        hunk
 9962    }
 9963
 9964    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9965        let snapshot = self.snapshot(window, cx);
 9966        let selection = self.selections.newest::<Point>(cx);
 9967        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9968    }
 9969
 9970    fn go_to_hunk_before_position(
 9971        &mut self,
 9972        snapshot: &EditorSnapshot,
 9973        position: Point,
 9974        window: &mut Window,
 9975        cx: &mut Context<Editor>,
 9976    ) -> Option<MultiBufferDiffHunk> {
 9977        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9978        if hunk.is_none() {
 9979            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9980        }
 9981        if let Some(hunk) = &hunk {
 9982            let destination = Point::new(hunk.row_range.start.0, 0);
 9983            self.unfold_ranges(&[destination..destination], false, false, cx);
 9984            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9985                s.select_ranges(vec![destination..destination]);
 9986            });
 9987        }
 9988
 9989        hunk
 9990    }
 9991
 9992    pub fn go_to_definition(
 9993        &mut self,
 9994        _: &GoToDefinition,
 9995        window: &mut Window,
 9996        cx: &mut Context<Self>,
 9997    ) -> Task<Result<Navigated>> {
 9998        let definition =
 9999            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10000        cx.spawn_in(window, |editor, mut cx| async move {
10001            if definition.await? == Navigated::Yes {
10002                return Ok(Navigated::Yes);
10003            }
10004            match editor.update_in(&mut cx, |editor, window, cx| {
10005                editor.find_all_references(&FindAllReferences, window, cx)
10006            })? {
10007                Some(references) => references.await,
10008                None => Ok(Navigated::No),
10009            }
10010        })
10011    }
10012
10013    pub fn go_to_declaration(
10014        &mut self,
10015        _: &GoToDeclaration,
10016        window: &mut Window,
10017        cx: &mut Context<Self>,
10018    ) -> Task<Result<Navigated>> {
10019        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10020    }
10021
10022    pub fn go_to_declaration_split(
10023        &mut self,
10024        _: &GoToDeclaration,
10025        window: &mut Window,
10026        cx: &mut Context<Self>,
10027    ) -> Task<Result<Navigated>> {
10028        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10029    }
10030
10031    pub fn go_to_implementation(
10032        &mut self,
10033        _: &GoToImplementation,
10034        window: &mut Window,
10035        cx: &mut Context<Self>,
10036    ) -> Task<Result<Navigated>> {
10037        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10038    }
10039
10040    pub fn go_to_implementation_split(
10041        &mut self,
10042        _: &GoToImplementationSplit,
10043        window: &mut Window,
10044        cx: &mut Context<Self>,
10045    ) -> Task<Result<Navigated>> {
10046        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10047    }
10048
10049    pub fn go_to_type_definition(
10050        &mut self,
10051        _: &GoToTypeDefinition,
10052        window: &mut Window,
10053        cx: &mut Context<Self>,
10054    ) -> Task<Result<Navigated>> {
10055        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10056    }
10057
10058    pub fn go_to_definition_split(
10059        &mut self,
10060        _: &GoToDefinitionSplit,
10061        window: &mut Window,
10062        cx: &mut Context<Self>,
10063    ) -> Task<Result<Navigated>> {
10064        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10065    }
10066
10067    pub fn go_to_type_definition_split(
10068        &mut self,
10069        _: &GoToTypeDefinitionSplit,
10070        window: &mut Window,
10071        cx: &mut Context<Self>,
10072    ) -> Task<Result<Navigated>> {
10073        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10074    }
10075
10076    fn go_to_definition_of_kind(
10077        &mut self,
10078        kind: GotoDefinitionKind,
10079        split: bool,
10080        window: &mut Window,
10081        cx: &mut Context<Self>,
10082    ) -> Task<Result<Navigated>> {
10083        let Some(provider) = self.semantics_provider.clone() else {
10084            return Task::ready(Ok(Navigated::No));
10085        };
10086        let head = self.selections.newest::<usize>(cx).head();
10087        let buffer = self.buffer.read(cx);
10088        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10089            text_anchor
10090        } else {
10091            return Task::ready(Ok(Navigated::No));
10092        };
10093
10094        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10095            return Task::ready(Ok(Navigated::No));
10096        };
10097
10098        cx.spawn_in(window, |editor, mut cx| async move {
10099            let definitions = definitions.await?;
10100            let navigated = editor
10101                .update_in(&mut cx, |editor, window, cx| {
10102                    editor.navigate_to_hover_links(
10103                        Some(kind),
10104                        definitions
10105                            .into_iter()
10106                            .filter(|location| {
10107                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10108                            })
10109                            .map(HoverLink::Text)
10110                            .collect::<Vec<_>>(),
10111                        split,
10112                        window,
10113                        cx,
10114                    )
10115                })?
10116                .await?;
10117            anyhow::Ok(navigated)
10118        })
10119    }
10120
10121    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10122        let selection = self.selections.newest_anchor();
10123        let head = selection.head();
10124        let tail = selection.tail();
10125
10126        let Some((buffer, start_position)) =
10127            self.buffer.read(cx).text_anchor_for_position(head, cx)
10128        else {
10129            return;
10130        };
10131
10132        let end_position = if head != tail {
10133            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10134                return;
10135            };
10136            Some(pos)
10137        } else {
10138            None
10139        };
10140
10141        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10142            let url = if let Some(end_pos) = end_position {
10143                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10144            } else {
10145                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10146            };
10147
10148            if let Some(url) = url {
10149                editor.update(&mut cx, |_, cx| {
10150                    cx.open_url(&url);
10151                })
10152            } else {
10153                Ok(())
10154            }
10155        });
10156
10157        url_finder.detach();
10158    }
10159
10160    pub fn open_selected_filename(
10161        &mut self,
10162        _: &OpenSelectedFilename,
10163        window: &mut Window,
10164        cx: &mut Context<Self>,
10165    ) {
10166        let Some(workspace) = self.workspace() else {
10167            return;
10168        };
10169
10170        let position = self.selections.newest_anchor().head();
10171
10172        let Some((buffer, buffer_position)) =
10173            self.buffer.read(cx).text_anchor_for_position(position, cx)
10174        else {
10175            return;
10176        };
10177
10178        let project = self.project.clone();
10179
10180        cx.spawn_in(window, |_, mut cx| async move {
10181            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10182
10183            if let Some((_, path)) = result {
10184                workspace
10185                    .update_in(&mut cx, |workspace, window, cx| {
10186                        workspace.open_resolved_path(path, window, cx)
10187                    })?
10188                    .await?;
10189            }
10190            anyhow::Ok(())
10191        })
10192        .detach();
10193    }
10194
10195    pub(crate) fn navigate_to_hover_links(
10196        &mut self,
10197        kind: Option<GotoDefinitionKind>,
10198        mut definitions: Vec<HoverLink>,
10199        split: bool,
10200        window: &mut Window,
10201        cx: &mut Context<Editor>,
10202    ) -> Task<Result<Navigated>> {
10203        // If there is one definition, just open it directly
10204        if definitions.len() == 1 {
10205            let definition = definitions.pop().unwrap();
10206
10207            enum TargetTaskResult {
10208                Location(Option<Location>),
10209                AlreadyNavigated,
10210            }
10211
10212            let target_task = match definition {
10213                HoverLink::Text(link) => {
10214                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10215                }
10216                HoverLink::InlayHint(lsp_location, server_id) => {
10217                    let computation =
10218                        self.compute_target_location(lsp_location, server_id, window, cx);
10219                    cx.background_executor().spawn(async move {
10220                        let location = computation.await?;
10221                        Ok(TargetTaskResult::Location(location))
10222                    })
10223                }
10224                HoverLink::Url(url) => {
10225                    cx.open_url(&url);
10226                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10227                }
10228                HoverLink::File(path) => {
10229                    if let Some(workspace) = self.workspace() {
10230                        cx.spawn_in(window, |_, mut cx| async move {
10231                            workspace
10232                                .update_in(&mut cx, |workspace, window, cx| {
10233                                    workspace.open_resolved_path(path, window, cx)
10234                                })?
10235                                .await
10236                                .map(|_| TargetTaskResult::AlreadyNavigated)
10237                        })
10238                    } else {
10239                        Task::ready(Ok(TargetTaskResult::Location(None)))
10240                    }
10241                }
10242            };
10243            cx.spawn_in(window, |editor, mut cx| async move {
10244                let target = match target_task.await.context("target resolution task")? {
10245                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10246                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10247                    TargetTaskResult::Location(Some(target)) => target,
10248                };
10249
10250                editor.update_in(&mut cx, |editor, window, cx| {
10251                    let Some(workspace) = editor.workspace() else {
10252                        return Navigated::No;
10253                    };
10254                    let pane = workspace.read(cx).active_pane().clone();
10255
10256                    let range = target.range.to_point(target.buffer.read(cx));
10257                    let range = editor.range_for_match(&range);
10258                    let range = collapse_multiline_range(range);
10259
10260                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10261                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10262                    } else {
10263                        window.defer(cx, move |window, cx| {
10264                            let target_editor: Entity<Self> =
10265                                workspace.update(cx, |workspace, cx| {
10266                                    let pane = if split {
10267                                        workspace.adjacent_pane(window, cx)
10268                                    } else {
10269                                        workspace.active_pane().clone()
10270                                    };
10271
10272                                    workspace.open_project_item(
10273                                        pane,
10274                                        target.buffer.clone(),
10275                                        true,
10276                                        true,
10277                                        window,
10278                                        cx,
10279                                    )
10280                                });
10281                            target_editor.update(cx, |target_editor, cx| {
10282                                // When selecting a definition in a different buffer, disable the nav history
10283                                // to avoid creating a history entry at the previous cursor location.
10284                                pane.update(cx, |pane, _| pane.disable_history());
10285                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10286                                pane.update(cx, |pane, _| pane.enable_history());
10287                            });
10288                        });
10289                    }
10290                    Navigated::Yes
10291                })
10292            })
10293        } else if !definitions.is_empty() {
10294            cx.spawn_in(window, |editor, mut cx| async move {
10295                let (title, location_tasks, workspace) = editor
10296                    .update_in(&mut cx, |editor, window, cx| {
10297                        let tab_kind = match kind {
10298                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10299                            _ => "Definitions",
10300                        };
10301                        let title = definitions
10302                            .iter()
10303                            .find_map(|definition| match definition {
10304                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10305                                    let buffer = origin.buffer.read(cx);
10306                                    format!(
10307                                        "{} for {}",
10308                                        tab_kind,
10309                                        buffer
10310                                            .text_for_range(origin.range.clone())
10311                                            .collect::<String>()
10312                                    )
10313                                }),
10314                                HoverLink::InlayHint(_, _) => None,
10315                                HoverLink::Url(_) => None,
10316                                HoverLink::File(_) => None,
10317                            })
10318                            .unwrap_or(tab_kind.to_string());
10319                        let location_tasks = definitions
10320                            .into_iter()
10321                            .map(|definition| match definition {
10322                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10323                                HoverLink::InlayHint(lsp_location, server_id) => editor
10324                                    .compute_target_location(lsp_location, server_id, window, cx),
10325                                HoverLink::Url(_) => Task::ready(Ok(None)),
10326                                HoverLink::File(_) => Task::ready(Ok(None)),
10327                            })
10328                            .collect::<Vec<_>>();
10329                        (title, location_tasks, editor.workspace().clone())
10330                    })
10331                    .context("location tasks preparation")?;
10332
10333                let locations = future::join_all(location_tasks)
10334                    .await
10335                    .into_iter()
10336                    .filter_map(|location| location.transpose())
10337                    .collect::<Result<_>>()
10338                    .context("location tasks")?;
10339
10340                let Some(workspace) = workspace else {
10341                    return Ok(Navigated::No);
10342                };
10343                let opened = workspace
10344                    .update_in(&mut cx, |workspace, window, cx| {
10345                        Self::open_locations_in_multibuffer(
10346                            workspace,
10347                            locations,
10348                            title,
10349                            split,
10350                            MultibufferSelectionMode::First,
10351                            window,
10352                            cx,
10353                        )
10354                    })
10355                    .ok();
10356
10357                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10358            })
10359        } else {
10360            Task::ready(Ok(Navigated::No))
10361        }
10362    }
10363
10364    fn compute_target_location(
10365        &self,
10366        lsp_location: lsp::Location,
10367        server_id: LanguageServerId,
10368        window: &mut Window,
10369        cx: &mut Context<Self>,
10370    ) -> Task<anyhow::Result<Option<Location>>> {
10371        let Some(project) = self.project.clone() else {
10372            return Task::ready(Ok(None));
10373        };
10374
10375        cx.spawn_in(window, move |editor, mut cx| async move {
10376            let location_task = editor.update(&mut cx, |_, cx| {
10377                project.update(cx, |project, cx| {
10378                    let language_server_name = project
10379                        .language_server_statuses(cx)
10380                        .find(|(id, _)| server_id == *id)
10381                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10382                    language_server_name.map(|language_server_name| {
10383                        project.open_local_buffer_via_lsp(
10384                            lsp_location.uri.clone(),
10385                            server_id,
10386                            language_server_name,
10387                            cx,
10388                        )
10389                    })
10390                })
10391            })?;
10392            let location = match location_task {
10393                Some(task) => Some({
10394                    let target_buffer_handle = task.await.context("open local buffer")?;
10395                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10396                        let target_start = target_buffer
10397                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10398                        let target_end = target_buffer
10399                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10400                        target_buffer.anchor_after(target_start)
10401                            ..target_buffer.anchor_before(target_end)
10402                    })?;
10403                    Location {
10404                        buffer: target_buffer_handle,
10405                        range,
10406                    }
10407                }),
10408                None => None,
10409            };
10410            Ok(location)
10411        })
10412    }
10413
10414    pub fn find_all_references(
10415        &mut self,
10416        _: &FindAllReferences,
10417        window: &mut Window,
10418        cx: &mut Context<Self>,
10419    ) -> Option<Task<Result<Navigated>>> {
10420        let selection = self.selections.newest::<usize>(cx);
10421        let multi_buffer = self.buffer.read(cx);
10422        let head = selection.head();
10423
10424        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10425        let head_anchor = multi_buffer_snapshot.anchor_at(
10426            head,
10427            if head < selection.tail() {
10428                Bias::Right
10429            } else {
10430                Bias::Left
10431            },
10432        );
10433
10434        match self
10435            .find_all_references_task_sources
10436            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10437        {
10438            Ok(_) => {
10439                log::info!(
10440                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10441                );
10442                return None;
10443            }
10444            Err(i) => {
10445                self.find_all_references_task_sources.insert(i, head_anchor);
10446            }
10447        }
10448
10449        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10450        let workspace = self.workspace()?;
10451        let project = workspace.read(cx).project().clone();
10452        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10453        Some(cx.spawn_in(window, |editor, mut cx| async move {
10454            let _cleanup = defer({
10455                let mut cx = cx.clone();
10456                move || {
10457                    let _ = editor.update(&mut cx, |editor, _| {
10458                        if let Ok(i) =
10459                            editor
10460                                .find_all_references_task_sources
10461                                .binary_search_by(|anchor| {
10462                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10463                                })
10464                        {
10465                            editor.find_all_references_task_sources.remove(i);
10466                        }
10467                    });
10468                }
10469            });
10470
10471            let locations = references.await?;
10472            if locations.is_empty() {
10473                return anyhow::Ok(Navigated::No);
10474            }
10475
10476            workspace.update_in(&mut cx, |workspace, window, cx| {
10477                let title = locations
10478                    .first()
10479                    .as_ref()
10480                    .map(|location| {
10481                        let buffer = location.buffer.read(cx);
10482                        format!(
10483                            "References to `{}`",
10484                            buffer
10485                                .text_for_range(location.range.clone())
10486                                .collect::<String>()
10487                        )
10488                    })
10489                    .unwrap();
10490                Self::open_locations_in_multibuffer(
10491                    workspace,
10492                    locations,
10493                    title,
10494                    false,
10495                    MultibufferSelectionMode::First,
10496                    window,
10497                    cx,
10498                );
10499                Navigated::Yes
10500            })
10501        }))
10502    }
10503
10504    /// Opens a multibuffer with the given project locations in it
10505    pub fn open_locations_in_multibuffer(
10506        workspace: &mut Workspace,
10507        mut locations: Vec<Location>,
10508        title: String,
10509        split: bool,
10510        multibuffer_selection_mode: MultibufferSelectionMode,
10511        window: &mut Window,
10512        cx: &mut Context<Workspace>,
10513    ) {
10514        // If there are multiple definitions, open them in a multibuffer
10515        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10516        let mut locations = locations.into_iter().peekable();
10517        let mut ranges = Vec::new();
10518        let capability = workspace.project().read(cx).capability();
10519
10520        let excerpt_buffer = cx.new(|cx| {
10521            let mut multibuffer = MultiBuffer::new(capability);
10522            while let Some(location) = locations.next() {
10523                let buffer = location.buffer.read(cx);
10524                let mut ranges_for_buffer = Vec::new();
10525                let range = location.range.to_offset(buffer);
10526                ranges_for_buffer.push(range.clone());
10527
10528                while let Some(next_location) = locations.peek() {
10529                    if next_location.buffer == location.buffer {
10530                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10531                        locations.next();
10532                    } else {
10533                        break;
10534                    }
10535                }
10536
10537                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10538                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10539                    location.buffer.clone(),
10540                    ranges_for_buffer,
10541                    DEFAULT_MULTIBUFFER_CONTEXT,
10542                    cx,
10543                ))
10544            }
10545
10546            multibuffer.with_title(title)
10547        });
10548
10549        let editor = cx.new(|cx| {
10550            Editor::for_multibuffer(
10551                excerpt_buffer,
10552                Some(workspace.project().clone()),
10553                true,
10554                window,
10555                cx,
10556            )
10557        });
10558        editor.update(cx, |editor, cx| {
10559            match multibuffer_selection_mode {
10560                MultibufferSelectionMode::First => {
10561                    if let Some(first_range) = ranges.first() {
10562                        editor.change_selections(None, window, cx, |selections| {
10563                            selections.clear_disjoint();
10564                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10565                        });
10566                    }
10567                    editor.highlight_background::<Self>(
10568                        &ranges,
10569                        |theme| theme.editor_highlighted_line_background,
10570                        cx,
10571                    );
10572                }
10573                MultibufferSelectionMode::All => {
10574                    editor.change_selections(None, window, cx, |selections| {
10575                        selections.clear_disjoint();
10576                        selections.select_anchor_ranges(ranges);
10577                    });
10578                }
10579            }
10580            editor.register_buffers_with_language_servers(cx);
10581        });
10582
10583        let item = Box::new(editor);
10584        let item_id = item.item_id();
10585
10586        if split {
10587            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10588        } else {
10589            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10590                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10591                    pane.close_current_preview_item(window, cx)
10592                } else {
10593                    None
10594                }
10595            });
10596            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10597        }
10598        workspace.active_pane().update(cx, |pane, cx| {
10599            pane.set_preview_item_id(Some(item_id), cx);
10600        });
10601    }
10602
10603    pub fn rename(
10604        &mut self,
10605        _: &Rename,
10606        window: &mut Window,
10607        cx: &mut Context<Self>,
10608    ) -> Option<Task<Result<()>>> {
10609        use language::ToOffset as _;
10610
10611        let provider = self.semantics_provider.clone()?;
10612        let selection = self.selections.newest_anchor().clone();
10613        let (cursor_buffer, cursor_buffer_position) = self
10614            .buffer
10615            .read(cx)
10616            .text_anchor_for_position(selection.head(), cx)?;
10617        let (tail_buffer, cursor_buffer_position_end) = self
10618            .buffer
10619            .read(cx)
10620            .text_anchor_for_position(selection.tail(), cx)?;
10621        if tail_buffer != cursor_buffer {
10622            return None;
10623        }
10624
10625        let snapshot = cursor_buffer.read(cx).snapshot();
10626        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10627        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10628        let prepare_rename = provider
10629            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10630            .unwrap_or_else(|| Task::ready(Ok(None)));
10631        drop(snapshot);
10632
10633        Some(cx.spawn_in(window, |this, mut cx| async move {
10634            let rename_range = if let Some(range) = prepare_rename.await? {
10635                Some(range)
10636            } else {
10637                this.update(&mut cx, |this, cx| {
10638                    let buffer = this.buffer.read(cx).snapshot(cx);
10639                    let mut buffer_highlights = this
10640                        .document_highlights_for_position(selection.head(), &buffer)
10641                        .filter(|highlight| {
10642                            highlight.start.excerpt_id == selection.head().excerpt_id
10643                                && highlight.end.excerpt_id == selection.head().excerpt_id
10644                        });
10645                    buffer_highlights
10646                        .next()
10647                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10648                })?
10649            };
10650            if let Some(rename_range) = rename_range {
10651                this.update_in(&mut cx, |this, window, cx| {
10652                    let snapshot = cursor_buffer.read(cx).snapshot();
10653                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10654                    let cursor_offset_in_rename_range =
10655                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10656                    let cursor_offset_in_rename_range_end =
10657                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10658
10659                    this.take_rename(false, window, cx);
10660                    let buffer = this.buffer.read(cx).read(cx);
10661                    let cursor_offset = selection.head().to_offset(&buffer);
10662                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10663                    let rename_end = rename_start + rename_buffer_range.len();
10664                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10665                    let mut old_highlight_id = None;
10666                    let old_name: Arc<str> = buffer
10667                        .chunks(rename_start..rename_end, true)
10668                        .map(|chunk| {
10669                            if old_highlight_id.is_none() {
10670                                old_highlight_id = chunk.syntax_highlight_id;
10671                            }
10672                            chunk.text
10673                        })
10674                        .collect::<String>()
10675                        .into();
10676
10677                    drop(buffer);
10678
10679                    // Position the selection in the rename editor so that it matches the current selection.
10680                    this.show_local_selections = false;
10681                    let rename_editor = cx.new(|cx| {
10682                        let mut editor = Editor::single_line(window, cx);
10683                        editor.buffer.update(cx, |buffer, cx| {
10684                            buffer.edit([(0..0, old_name.clone())], None, cx)
10685                        });
10686                        let rename_selection_range = match cursor_offset_in_rename_range
10687                            .cmp(&cursor_offset_in_rename_range_end)
10688                        {
10689                            Ordering::Equal => {
10690                                editor.select_all(&SelectAll, window, cx);
10691                                return editor;
10692                            }
10693                            Ordering::Less => {
10694                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10695                            }
10696                            Ordering::Greater => {
10697                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10698                            }
10699                        };
10700                        if rename_selection_range.end > old_name.len() {
10701                            editor.select_all(&SelectAll, window, cx);
10702                        } else {
10703                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704                                s.select_ranges([rename_selection_range]);
10705                            });
10706                        }
10707                        editor
10708                    });
10709                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10710                        if e == &EditorEvent::Focused {
10711                            cx.emit(EditorEvent::FocusedIn)
10712                        }
10713                    })
10714                    .detach();
10715
10716                    let write_highlights =
10717                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10718                    let read_highlights =
10719                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10720                    let ranges = write_highlights
10721                        .iter()
10722                        .flat_map(|(_, ranges)| ranges.iter())
10723                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10724                        .cloned()
10725                        .collect();
10726
10727                    this.highlight_text::<Rename>(
10728                        ranges,
10729                        HighlightStyle {
10730                            fade_out: Some(0.6),
10731                            ..Default::default()
10732                        },
10733                        cx,
10734                    );
10735                    let rename_focus_handle = rename_editor.focus_handle(cx);
10736                    window.focus(&rename_focus_handle);
10737                    let block_id = this.insert_blocks(
10738                        [BlockProperties {
10739                            style: BlockStyle::Flex,
10740                            placement: BlockPlacement::Below(range.start),
10741                            height: 1,
10742                            render: Arc::new({
10743                                let rename_editor = rename_editor.clone();
10744                                move |cx: &mut BlockContext| {
10745                                    let mut text_style = cx.editor_style.text.clone();
10746                                    if let Some(highlight_style) = old_highlight_id
10747                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10748                                    {
10749                                        text_style = text_style.highlight(highlight_style);
10750                                    }
10751                                    div()
10752                                        .block_mouse_down()
10753                                        .pl(cx.anchor_x)
10754                                        .child(EditorElement::new(
10755                                            &rename_editor,
10756                                            EditorStyle {
10757                                                background: cx.theme().system().transparent,
10758                                                local_player: cx.editor_style.local_player,
10759                                                text: text_style,
10760                                                scrollbar_width: cx.editor_style.scrollbar_width,
10761                                                syntax: cx.editor_style.syntax.clone(),
10762                                                status: cx.editor_style.status.clone(),
10763                                                inlay_hints_style: HighlightStyle {
10764                                                    font_weight: Some(FontWeight::BOLD),
10765                                                    ..make_inlay_hints_style(cx.app)
10766                                                },
10767                                                inline_completion_styles: make_suggestion_styles(
10768                                                    cx.app,
10769                                                ),
10770                                                ..EditorStyle::default()
10771                                            },
10772                                        ))
10773                                        .into_any_element()
10774                                }
10775                            }),
10776                            priority: 0,
10777                        }],
10778                        Some(Autoscroll::fit()),
10779                        cx,
10780                    )[0];
10781                    this.pending_rename = Some(RenameState {
10782                        range,
10783                        old_name,
10784                        editor: rename_editor,
10785                        block_id,
10786                    });
10787                })?;
10788            }
10789
10790            Ok(())
10791        }))
10792    }
10793
10794    pub fn confirm_rename(
10795        &mut self,
10796        _: &ConfirmRename,
10797        window: &mut Window,
10798        cx: &mut Context<Self>,
10799    ) -> Option<Task<Result<()>>> {
10800        let rename = self.take_rename(false, window, cx)?;
10801        let workspace = self.workspace()?.downgrade();
10802        let (buffer, start) = self
10803            .buffer
10804            .read(cx)
10805            .text_anchor_for_position(rename.range.start, cx)?;
10806        let (end_buffer, _) = self
10807            .buffer
10808            .read(cx)
10809            .text_anchor_for_position(rename.range.end, cx)?;
10810        if buffer != end_buffer {
10811            return None;
10812        }
10813
10814        let old_name = rename.old_name;
10815        let new_name = rename.editor.read(cx).text(cx);
10816
10817        let rename = self.semantics_provider.as_ref()?.perform_rename(
10818            &buffer,
10819            start,
10820            new_name.clone(),
10821            cx,
10822        )?;
10823
10824        Some(cx.spawn_in(window, |editor, mut cx| async move {
10825            let project_transaction = rename.await?;
10826            Self::open_project_transaction(
10827                &editor,
10828                workspace,
10829                project_transaction,
10830                format!("Rename: {}{}", old_name, new_name),
10831                cx.clone(),
10832            )
10833            .await?;
10834
10835            editor.update(&mut cx, |editor, cx| {
10836                editor.refresh_document_highlights(cx);
10837            })?;
10838            Ok(())
10839        }))
10840    }
10841
10842    fn take_rename(
10843        &mut self,
10844        moving_cursor: bool,
10845        window: &mut Window,
10846        cx: &mut Context<Self>,
10847    ) -> Option<RenameState> {
10848        let rename = self.pending_rename.take()?;
10849        if rename.editor.focus_handle(cx).is_focused(window) {
10850            window.focus(&self.focus_handle);
10851        }
10852
10853        self.remove_blocks(
10854            [rename.block_id].into_iter().collect(),
10855            Some(Autoscroll::fit()),
10856            cx,
10857        );
10858        self.clear_highlights::<Rename>(cx);
10859        self.show_local_selections = true;
10860
10861        if moving_cursor {
10862            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10863                editor.selections.newest::<usize>(cx).head()
10864            });
10865
10866            // Update the selection to match the position of the selection inside
10867            // the rename editor.
10868            let snapshot = self.buffer.read(cx).read(cx);
10869            let rename_range = rename.range.to_offset(&snapshot);
10870            let cursor_in_editor = snapshot
10871                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10872                .min(rename_range.end);
10873            drop(snapshot);
10874
10875            self.change_selections(None, window, cx, |s| {
10876                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10877            });
10878        } else {
10879            self.refresh_document_highlights(cx);
10880        }
10881
10882        Some(rename)
10883    }
10884
10885    pub fn pending_rename(&self) -> Option<&RenameState> {
10886        self.pending_rename.as_ref()
10887    }
10888
10889    fn format(
10890        &mut self,
10891        _: &Format,
10892        window: &mut Window,
10893        cx: &mut Context<Self>,
10894    ) -> Option<Task<Result<()>>> {
10895        let project = match &self.project {
10896            Some(project) => project.clone(),
10897            None => return None,
10898        };
10899
10900        Some(self.perform_format(
10901            project,
10902            FormatTrigger::Manual,
10903            FormatTarget::Buffers,
10904            window,
10905            cx,
10906        ))
10907    }
10908
10909    fn format_selections(
10910        &mut self,
10911        _: &FormatSelections,
10912        window: &mut Window,
10913        cx: &mut Context<Self>,
10914    ) -> Option<Task<Result<()>>> {
10915        let project = match &self.project {
10916            Some(project) => project.clone(),
10917            None => return None,
10918        };
10919
10920        let ranges = self
10921            .selections
10922            .all_adjusted(cx)
10923            .into_iter()
10924            .map(|selection| selection.range())
10925            .collect_vec();
10926
10927        Some(self.perform_format(
10928            project,
10929            FormatTrigger::Manual,
10930            FormatTarget::Ranges(ranges),
10931            window,
10932            cx,
10933        ))
10934    }
10935
10936    fn perform_format(
10937        &mut self,
10938        project: Entity<Project>,
10939        trigger: FormatTrigger,
10940        target: FormatTarget,
10941        window: &mut Window,
10942        cx: &mut Context<Self>,
10943    ) -> Task<Result<()>> {
10944        let buffer = self.buffer.clone();
10945        let (buffers, target) = match target {
10946            FormatTarget::Buffers => {
10947                let mut buffers = buffer.read(cx).all_buffers();
10948                if trigger == FormatTrigger::Save {
10949                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10950                }
10951                (buffers, LspFormatTarget::Buffers)
10952            }
10953            FormatTarget::Ranges(selection_ranges) => {
10954                let multi_buffer = buffer.read(cx);
10955                let snapshot = multi_buffer.read(cx);
10956                let mut buffers = HashSet::default();
10957                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10958                    BTreeMap::new();
10959                for selection_range in selection_ranges {
10960                    for (buffer, buffer_range, _) in
10961                        snapshot.range_to_buffer_ranges(selection_range)
10962                    {
10963                        let buffer_id = buffer.remote_id();
10964                        let start = buffer.anchor_before(buffer_range.start);
10965                        let end = buffer.anchor_after(buffer_range.end);
10966                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10967                        buffer_id_to_ranges
10968                            .entry(buffer_id)
10969                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10970                            .or_insert_with(|| vec![start..end]);
10971                    }
10972                }
10973                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10974            }
10975        };
10976
10977        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10978        let format = project.update(cx, |project, cx| {
10979            project.format(buffers, target, true, trigger, cx)
10980        });
10981
10982        cx.spawn_in(window, |_, mut cx| async move {
10983            let transaction = futures::select_biased! {
10984                () = timeout => {
10985                    log::warn!("timed out waiting for formatting");
10986                    None
10987                }
10988                transaction = format.log_err().fuse() => transaction,
10989            };
10990
10991            buffer
10992                .update(&mut cx, |buffer, cx| {
10993                    if let Some(transaction) = transaction {
10994                        if !buffer.is_singleton() {
10995                            buffer.push_transaction(&transaction.0, cx);
10996                        }
10997                    }
10998
10999                    cx.notify();
11000                })
11001                .ok();
11002
11003            Ok(())
11004        })
11005    }
11006
11007    fn restart_language_server(
11008        &mut self,
11009        _: &RestartLanguageServer,
11010        _: &mut Window,
11011        cx: &mut Context<Self>,
11012    ) {
11013        if let Some(project) = self.project.clone() {
11014            self.buffer.update(cx, |multi_buffer, cx| {
11015                project.update(cx, |project, cx| {
11016                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11017                });
11018            })
11019        }
11020    }
11021
11022    fn cancel_language_server_work(
11023        &mut self,
11024        _: &actions::CancelLanguageServerWork,
11025        _: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) {
11028        if let Some(project) = self.project.clone() {
11029            self.buffer.update(cx, |multi_buffer, cx| {
11030                project.update(cx, |project, cx| {
11031                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11032                });
11033            })
11034        }
11035    }
11036
11037    fn show_character_palette(
11038        &mut self,
11039        _: &ShowCharacterPalette,
11040        window: &mut Window,
11041        _: &mut Context<Self>,
11042    ) {
11043        window.show_character_palette();
11044    }
11045
11046    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11047        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11048            let buffer = self.buffer.read(cx).snapshot(cx);
11049            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11050            let is_valid = buffer
11051                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11052                .any(|entry| {
11053                    entry.diagnostic.is_primary
11054                        && !entry.range.is_empty()
11055                        && entry.range.start == primary_range_start
11056                        && entry.diagnostic.message == active_diagnostics.primary_message
11057                });
11058
11059            if is_valid != active_diagnostics.is_valid {
11060                active_diagnostics.is_valid = is_valid;
11061                let mut new_styles = HashMap::default();
11062                for (block_id, diagnostic) in &active_diagnostics.blocks {
11063                    new_styles.insert(
11064                        *block_id,
11065                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11066                    );
11067                }
11068                self.display_map.update(cx, |display_map, _cx| {
11069                    display_map.replace_blocks(new_styles)
11070                });
11071            }
11072        }
11073    }
11074
11075    fn activate_diagnostics(
11076        &mut self,
11077        buffer_id: BufferId,
11078        group_id: usize,
11079        window: &mut Window,
11080        cx: &mut Context<Self>,
11081    ) {
11082        self.dismiss_diagnostics(cx);
11083        let snapshot = self.snapshot(window, cx);
11084        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11085            let buffer = self.buffer.read(cx).snapshot(cx);
11086
11087            let mut primary_range = None;
11088            let mut primary_message = None;
11089            let diagnostic_group = buffer
11090                .diagnostic_group(buffer_id, group_id)
11091                .filter_map(|entry| {
11092                    let start = entry.range.start;
11093                    let end = entry.range.end;
11094                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11095                        && (start.row == end.row
11096                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11097                    {
11098                        return None;
11099                    }
11100                    if entry.diagnostic.is_primary {
11101                        primary_range = Some(entry.range.clone());
11102                        primary_message = Some(entry.diagnostic.message.clone());
11103                    }
11104                    Some(entry)
11105                })
11106                .collect::<Vec<_>>();
11107            let primary_range = primary_range?;
11108            let primary_message = primary_message?;
11109
11110            let blocks = display_map
11111                .insert_blocks(
11112                    diagnostic_group.iter().map(|entry| {
11113                        let diagnostic = entry.diagnostic.clone();
11114                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11115                        BlockProperties {
11116                            style: BlockStyle::Fixed,
11117                            placement: BlockPlacement::Below(
11118                                buffer.anchor_after(entry.range.start),
11119                            ),
11120                            height: message_height,
11121                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11122                            priority: 0,
11123                        }
11124                    }),
11125                    cx,
11126                )
11127                .into_iter()
11128                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11129                .collect();
11130
11131            Some(ActiveDiagnosticGroup {
11132                primary_range: buffer.anchor_before(primary_range.start)
11133                    ..buffer.anchor_after(primary_range.end),
11134                primary_message,
11135                group_id,
11136                blocks,
11137                is_valid: true,
11138            })
11139        });
11140    }
11141
11142    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11143        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11144            self.display_map.update(cx, |display_map, cx| {
11145                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11146            });
11147            cx.notify();
11148        }
11149    }
11150
11151    pub fn set_selections_from_remote(
11152        &mut self,
11153        selections: Vec<Selection<Anchor>>,
11154        pending_selection: Option<Selection<Anchor>>,
11155        window: &mut Window,
11156        cx: &mut Context<Self>,
11157    ) {
11158        let old_cursor_position = self.selections.newest_anchor().head();
11159        self.selections.change_with(cx, |s| {
11160            s.select_anchors(selections);
11161            if let Some(pending_selection) = pending_selection {
11162                s.set_pending(pending_selection, SelectMode::Character);
11163            } else {
11164                s.clear_pending();
11165            }
11166        });
11167        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11168    }
11169
11170    fn push_to_selection_history(&mut self) {
11171        self.selection_history.push(SelectionHistoryEntry {
11172            selections: self.selections.disjoint_anchors(),
11173            select_next_state: self.select_next_state.clone(),
11174            select_prev_state: self.select_prev_state.clone(),
11175            add_selections_state: self.add_selections_state.clone(),
11176        });
11177    }
11178
11179    pub fn transact(
11180        &mut self,
11181        window: &mut Window,
11182        cx: &mut Context<Self>,
11183        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11184    ) -> Option<TransactionId> {
11185        self.start_transaction_at(Instant::now(), window, cx);
11186        update(self, window, cx);
11187        self.end_transaction_at(Instant::now(), cx)
11188    }
11189
11190    pub fn start_transaction_at(
11191        &mut self,
11192        now: Instant,
11193        window: &mut Window,
11194        cx: &mut Context<Self>,
11195    ) {
11196        self.end_selection(window, cx);
11197        if let Some(tx_id) = self
11198            .buffer
11199            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11200        {
11201            self.selection_history
11202                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11203            cx.emit(EditorEvent::TransactionBegun {
11204                transaction_id: tx_id,
11205            })
11206        }
11207    }
11208
11209    pub fn end_transaction_at(
11210        &mut self,
11211        now: Instant,
11212        cx: &mut Context<Self>,
11213    ) -> Option<TransactionId> {
11214        if let Some(transaction_id) = self
11215            .buffer
11216            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11217        {
11218            if let Some((_, end_selections)) =
11219                self.selection_history.transaction_mut(transaction_id)
11220            {
11221                *end_selections = Some(self.selections.disjoint_anchors());
11222            } else {
11223                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11224            }
11225
11226            cx.emit(EditorEvent::Edited { transaction_id });
11227            Some(transaction_id)
11228        } else {
11229            None
11230        }
11231    }
11232
11233    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11234        if self.selection_mark_mode {
11235            self.change_selections(None, window, cx, |s| {
11236                s.move_with(|_, sel| {
11237                    sel.collapse_to(sel.head(), SelectionGoal::None);
11238                });
11239            })
11240        }
11241        self.selection_mark_mode = true;
11242        cx.notify();
11243    }
11244
11245    pub fn swap_selection_ends(
11246        &mut self,
11247        _: &actions::SwapSelectionEnds,
11248        window: &mut Window,
11249        cx: &mut Context<Self>,
11250    ) {
11251        self.change_selections(None, window, cx, |s| {
11252            s.move_with(|_, sel| {
11253                if sel.start != sel.end {
11254                    sel.reversed = !sel.reversed
11255                }
11256            });
11257        });
11258        self.request_autoscroll(Autoscroll::newest(), cx);
11259        cx.notify();
11260    }
11261
11262    pub fn toggle_fold(
11263        &mut self,
11264        _: &actions::ToggleFold,
11265        window: &mut Window,
11266        cx: &mut Context<Self>,
11267    ) {
11268        if self.is_singleton(cx) {
11269            let selection = self.selections.newest::<Point>(cx);
11270
11271            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11272            let range = if selection.is_empty() {
11273                let point = selection.head().to_display_point(&display_map);
11274                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11275                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11276                    .to_point(&display_map);
11277                start..end
11278            } else {
11279                selection.range()
11280            };
11281            if display_map.folds_in_range(range).next().is_some() {
11282                self.unfold_lines(&Default::default(), window, cx)
11283            } else {
11284                self.fold(&Default::default(), window, cx)
11285            }
11286        } else {
11287            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11288            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11289                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11290                .map(|(snapshot, _, _)| snapshot.remote_id())
11291                .collect();
11292
11293            for buffer_id in buffer_ids {
11294                if self.is_buffer_folded(buffer_id, cx) {
11295                    self.unfold_buffer(buffer_id, cx);
11296                } else {
11297                    self.fold_buffer(buffer_id, cx);
11298                }
11299            }
11300        }
11301    }
11302
11303    pub fn toggle_fold_recursive(
11304        &mut self,
11305        _: &actions::ToggleFoldRecursive,
11306        window: &mut Window,
11307        cx: &mut Context<Self>,
11308    ) {
11309        let selection = self.selections.newest::<Point>(cx);
11310
11311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11312        let range = if selection.is_empty() {
11313            let point = selection.head().to_display_point(&display_map);
11314            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11315            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11316                .to_point(&display_map);
11317            start..end
11318        } else {
11319            selection.range()
11320        };
11321        if display_map.folds_in_range(range).next().is_some() {
11322            self.unfold_recursive(&Default::default(), window, cx)
11323        } else {
11324            self.fold_recursive(&Default::default(), window, cx)
11325        }
11326    }
11327
11328    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11329        if self.is_singleton(cx) {
11330            let mut to_fold = Vec::new();
11331            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11332            let selections = self.selections.all_adjusted(cx);
11333
11334            for selection in selections {
11335                let range = selection.range().sorted();
11336                let buffer_start_row = range.start.row;
11337
11338                if range.start.row != range.end.row {
11339                    let mut found = false;
11340                    let mut row = range.start.row;
11341                    while row <= range.end.row {
11342                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11343                        {
11344                            found = true;
11345                            row = crease.range().end.row + 1;
11346                            to_fold.push(crease);
11347                        } else {
11348                            row += 1
11349                        }
11350                    }
11351                    if found {
11352                        continue;
11353                    }
11354                }
11355
11356                for row in (0..=range.start.row).rev() {
11357                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11358                        if crease.range().end.row >= buffer_start_row {
11359                            to_fold.push(crease);
11360                            if row <= range.start.row {
11361                                break;
11362                            }
11363                        }
11364                    }
11365                }
11366            }
11367
11368            self.fold_creases(to_fold, true, window, cx);
11369        } else {
11370            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11371
11372            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11373                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11374                .map(|(snapshot, _, _)| snapshot.remote_id())
11375                .collect();
11376            for buffer_id in buffer_ids {
11377                self.fold_buffer(buffer_id, cx);
11378            }
11379        }
11380    }
11381
11382    fn fold_at_level(
11383        &mut self,
11384        fold_at: &FoldAtLevel,
11385        window: &mut Window,
11386        cx: &mut Context<Self>,
11387    ) {
11388        if !self.buffer.read(cx).is_singleton() {
11389            return;
11390        }
11391
11392        let fold_at_level = fold_at.level;
11393        let snapshot = self.buffer.read(cx).snapshot(cx);
11394        let mut to_fold = Vec::new();
11395        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11396
11397        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11398            while start_row < end_row {
11399                match self
11400                    .snapshot(window, cx)
11401                    .crease_for_buffer_row(MultiBufferRow(start_row))
11402                {
11403                    Some(crease) => {
11404                        let nested_start_row = crease.range().start.row + 1;
11405                        let nested_end_row = crease.range().end.row;
11406
11407                        if current_level < fold_at_level {
11408                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11409                        } else if current_level == fold_at_level {
11410                            to_fold.push(crease);
11411                        }
11412
11413                        start_row = nested_end_row + 1;
11414                    }
11415                    None => start_row += 1,
11416                }
11417            }
11418        }
11419
11420        self.fold_creases(to_fold, true, window, cx);
11421    }
11422
11423    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11424        if self.buffer.read(cx).is_singleton() {
11425            let mut fold_ranges = Vec::new();
11426            let snapshot = self.buffer.read(cx).snapshot(cx);
11427
11428            for row in 0..snapshot.max_row().0 {
11429                if let Some(foldable_range) = self
11430                    .snapshot(window, cx)
11431                    .crease_for_buffer_row(MultiBufferRow(row))
11432                {
11433                    fold_ranges.push(foldable_range);
11434                }
11435            }
11436
11437            self.fold_creases(fold_ranges, true, window, cx);
11438        } else {
11439            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11440                editor
11441                    .update_in(&mut cx, |editor, _, cx| {
11442                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11443                            editor.fold_buffer(buffer_id, cx);
11444                        }
11445                    })
11446                    .ok();
11447            });
11448        }
11449    }
11450
11451    pub fn fold_function_bodies(
11452        &mut self,
11453        _: &actions::FoldFunctionBodies,
11454        window: &mut Window,
11455        cx: &mut Context<Self>,
11456    ) {
11457        let snapshot = self.buffer.read(cx).snapshot(cx);
11458
11459        let ranges = snapshot
11460            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11461            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11462            .collect::<Vec<_>>();
11463
11464        let creases = ranges
11465            .into_iter()
11466            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11467            .collect();
11468
11469        self.fold_creases(creases, true, window, cx);
11470    }
11471
11472    pub fn fold_recursive(
11473        &mut self,
11474        _: &actions::FoldRecursive,
11475        window: &mut Window,
11476        cx: &mut Context<Self>,
11477    ) {
11478        let mut to_fold = Vec::new();
11479        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11480        let selections = self.selections.all_adjusted(cx);
11481
11482        for selection in selections {
11483            let range = selection.range().sorted();
11484            let buffer_start_row = range.start.row;
11485
11486            if range.start.row != range.end.row {
11487                let mut found = false;
11488                for row in range.start.row..=range.end.row {
11489                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11490                        found = true;
11491                        to_fold.push(crease);
11492                    }
11493                }
11494                if found {
11495                    continue;
11496                }
11497            }
11498
11499            for row in (0..=range.start.row).rev() {
11500                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11501                    if crease.range().end.row >= buffer_start_row {
11502                        to_fold.push(crease);
11503                    } else {
11504                        break;
11505                    }
11506                }
11507            }
11508        }
11509
11510        self.fold_creases(to_fold, true, window, cx);
11511    }
11512
11513    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11514        let buffer_row = fold_at.buffer_row;
11515        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11516
11517        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11518            let autoscroll = self
11519                .selections
11520                .all::<Point>(cx)
11521                .iter()
11522                .any(|selection| crease.range().overlaps(&selection.range()));
11523
11524            self.fold_creases(vec![crease], autoscroll, window, cx);
11525        }
11526    }
11527
11528    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11529        if self.is_singleton(cx) {
11530            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11531            let buffer = &display_map.buffer_snapshot;
11532            let selections = self.selections.all::<Point>(cx);
11533            let ranges = selections
11534                .iter()
11535                .map(|s| {
11536                    let range = s.display_range(&display_map).sorted();
11537                    let mut start = range.start.to_point(&display_map);
11538                    let mut end = range.end.to_point(&display_map);
11539                    start.column = 0;
11540                    end.column = buffer.line_len(MultiBufferRow(end.row));
11541                    start..end
11542                })
11543                .collect::<Vec<_>>();
11544
11545            self.unfold_ranges(&ranges, true, true, cx);
11546        } else {
11547            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11548            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11549                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11550                .map(|(snapshot, _, _)| snapshot.remote_id())
11551                .collect();
11552            for buffer_id in buffer_ids {
11553                self.unfold_buffer(buffer_id, cx);
11554            }
11555        }
11556    }
11557
11558    pub fn unfold_recursive(
11559        &mut self,
11560        _: &UnfoldRecursive,
11561        _window: &mut Window,
11562        cx: &mut Context<Self>,
11563    ) {
11564        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11565        let selections = self.selections.all::<Point>(cx);
11566        let ranges = selections
11567            .iter()
11568            .map(|s| {
11569                let mut range = s.display_range(&display_map).sorted();
11570                *range.start.column_mut() = 0;
11571                *range.end.column_mut() = display_map.line_len(range.end.row());
11572                let start = range.start.to_point(&display_map);
11573                let end = range.end.to_point(&display_map);
11574                start..end
11575            })
11576            .collect::<Vec<_>>();
11577
11578        self.unfold_ranges(&ranges, true, true, cx);
11579    }
11580
11581    pub fn unfold_at(
11582        &mut self,
11583        unfold_at: &UnfoldAt,
11584        _window: &mut Window,
11585        cx: &mut Context<Self>,
11586    ) {
11587        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11588
11589        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11590            ..Point::new(
11591                unfold_at.buffer_row.0,
11592                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11593            );
11594
11595        let autoscroll = self
11596            .selections
11597            .all::<Point>(cx)
11598            .iter()
11599            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11600
11601        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11602    }
11603
11604    pub fn unfold_all(
11605        &mut self,
11606        _: &actions::UnfoldAll,
11607        _window: &mut Window,
11608        cx: &mut Context<Self>,
11609    ) {
11610        if self.buffer.read(cx).is_singleton() {
11611            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11612            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11613        } else {
11614            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11615                editor
11616                    .update(&mut cx, |editor, cx| {
11617                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11618                            editor.unfold_buffer(buffer_id, cx);
11619                        }
11620                    })
11621                    .ok();
11622            });
11623        }
11624    }
11625
11626    pub fn fold_selected_ranges(
11627        &mut self,
11628        _: &FoldSelectedRanges,
11629        window: &mut Window,
11630        cx: &mut Context<Self>,
11631    ) {
11632        let selections = self.selections.all::<Point>(cx);
11633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11634        let line_mode = self.selections.line_mode;
11635        let ranges = selections
11636            .into_iter()
11637            .map(|s| {
11638                if line_mode {
11639                    let start = Point::new(s.start.row, 0);
11640                    let end = Point::new(
11641                        s.end.row,
11642                        display_map
11643                            .buffer_snapshot
11644                            .line_len(MultiBufferRow(s.end.row)),
11645                    );
11646                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11647                } else {
11648                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11649                }
11650            })
11651            .collect::<Vec<_>>();
11652        self.fold_creases(ranges, true, window, cx);
11653    }
11654
11655    pub fn fold_ranges<T: ToOffset + Clone>(
11656        &mut self,
11657        ranges: Vec<Range<T>>,
11658        auto_scroll: bool,
11659        window: &mut Window,
11660        cx: &mut Context<Self>,
11661    ) {
11662        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11663        let ranges = ranges
11664            .into_iter()
11665            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11666            .collect::<Vec<_>>();
11667        self.fold_creases(ranges, auto_scroll, window, cx);
11668    }
11669
11670    pub fn fold_creases<T: ToOffset + Clone>(
11671        &mut self,
11672        creases: Vec<Crease<T>>,
11673        auto_scroll: bool,
11674        window: &mut Window,
11675        cx: &mut Context<Self>,
11676    ) {
11677        if creases.is_empty() {
11678            return;
11679        }
11680
11681        let mut buffers_affected = HashSet::default();
11682        let multi_buffer = self.buffer().read(cx);
11683        for crease in &creases {
11684            if let Some((_, buffer, _)) =
11685                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11686            {
11687                buffers_affected.insert(buffer.read(cx).remote_id());
11688            };
11689        }
11690
11691        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11692
11693        if auto_scroll {
11694            self.request_autoscroll(Autoscroll::fit(), cx);
11695        }
11696
11697        cx.notify();
11698
11699        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11700            // Clear diagnostics block when folding a range that contains it.
11701            let snapshot = self.snapshot(window, cx);
11702            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11703                drop(snapshot);
11704                self.active_diagnostics = Some(active_diagnostics);
11705                self.dismiss_diagnostics(cx);
11706            } else {
11707                self.active_diagnostics = Some(active_diagnostics);
11708            }
11709        }
11710
11711        self.scrollbar_marker_state.dirty = true;
11712    }
11713
11714    /// Removes any folds whose ranges intersect any of the given ranges.
11715    pub fn unfold_ranges<T: ToOffset + Clone>(
11716        &mut self,
11717        ranges: &[Range<T>],
11718        inclusive: bool,
11719        auto_scroll: bool,
11720        cx: &mut Context<Self>,
11721    ) {
11722        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11723            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11724        });
11725    }
11726
11727    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11728        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11729            return;
11730        }
11731        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11732            return;
11733        };
11734        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11735        self.display_map
11736            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11737        cx.emit(EditorEvent::BufferFoldToggled {
11738            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11739            folded: true,
11740        });
11741        cx.notify();
11742    }
11743
11744    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11745        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11746            return;
11747        }
11748        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11749            return;
11750        };
11751        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11752        self.display_map.update(cx, |display_map, cx| {
11753            display_map.unfold_buffer(buffer_id, cx);
11754        });
11755        cx.emit(EditorEvent::BufferFoldToggled {
11756            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11757            folded: false,
11758        });
11759        cx.notify();
11760    }
11761
11762    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11763        self.display_map.read(cx).is_buffer_folded(buffer)
11764    }
11765
11766    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11767        self.display_map.read(cx).folded_buffers()
11768    }
11769
11770    /// Removes any folds with the given ranges.
11771    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11772        &mut self,
11773        ranges: &[Range<T>],
11774        type_id: TypeId,
11775        auto_scroll: bool,
11776        cx: &mut Context<Self>,
11777    ) {
11778        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11779            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11780        });
11781    }
11782
11783    fn remove_folds_with<T: ToOffset + Clone>(
11784        &mut self,
11785        ranges: &[Range<T>],
11786        auto_scroll: bool,
11787        cx: &mut Context<Self>,
11788        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11789    ) {
11790        if ranges.is_empty() {
11791            return;
11792        }
11793
11794        let mut buffers_affected = HashSet::default();
11795        let multi_buffer = self.buffer().read(cx);
11796        for range in ranges {
11797            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11798                buffers_affected.insert(buffer.read(cx).remote_id());
11799            };
11800        }
11801
11802        self.display_map.update(cx, update);
11803
11804        if auto_scroll {
11805            self.request_autoscroll(Autoscroll::fit(), cx);
11806        }
11807
11808        cx.notify();
11809        self.scrollbar_marker_state.dirty = true;
11810        self.active_indent_guides_state.dirty = true;
11811    }
11812
11813    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11814        self.display_map.read(cx).fold_placeholder.clone()
11815    }
11816
11817    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11818        self.buffer.update(cx, |buffer, cx| {
11819            buffer.set_all_diff_hunks_expanded(cx);
11820        });
11821    }
11822
11823    pub fn expand_all_diff_hunks(
11824        &mut self,
11825        _: &ExpandAllHunkDiffs,
11826        _window: &mut Window,
11827        cx: &mut Context<Self>,
11828    ) {
11829        self.buffer.update(cx, |buffer, cx| {
11830            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11831        });
11832    }
11833
11834    pub fn toggle_selected_diff_hunks(
11835        &mut self,
11836        _: &ToggleSelectedDiffHunks,
11837        _window: &mut Window,
11838        cx: &mut Context<Self>,
11839    ) {
11840        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11841        self.toggle_diff_hunks_in_ranges(ranges, cx);
11842    }
11843
11844    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11845        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11846        self.buffer
11847            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11848    }
11849
11850    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11851        self.buffer.update(cx, |buffer, cx| {
11852            let ranges = vec![Anchor::min()..Anchor::max()];
11853            if !buffer.all_diff_hunks_expanded()
11854                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11855            {
11856                buffer.collapse_diff_hunks(ranges, cx);
11857                true
11858            } else {
11859                false
11860            }
11861        })
11862    }
11863
11864    fn toggle_diff_hunks_in_ranges(
11865        &mut self,
11866        ranges: Vec<Range<Anchor>>,
11867        cx: &mut Context<'_, Editor>,
11868    ) {
11869        self.buffer.update(cx, |buffer, cx| {
11870            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11871                buffer.collapse_diff_hunks(ranges, cx)
11872            } else {
11873                buffer.expand_diff_hunks(ranges, cx)
11874            }
11875        })
11876    }
11877
11878    pub(crate) fn apply_all_diff_hunks(
11879        &mut self,
11880        _: &ApplyAllDiffHunks,
11881        window: &mut Window,
11882        cx: &mut Context<Self>,
11883    ) {
11884        let buffers = self.buffer.read(cx).all_buffers();
11885        for branch_buffer in buffers {
11886            branch_buffer.update(cx, |branch_buffer, cx| {
11887                branch_buffer.merge_into_base(Vec::new(), cx);
11888            });
11889        }
11890
11891        if let Some(project) = self.project.clone() {
11892            self.save(true, project, window, cx).detach_and_log_err(cx);
11893        }
11894    }
11895
11896    pub(crate) fn apply_selected_diff_hunks(
11897        &mut self,
11898        _: &ApplyDiffHunk,
11899        window: &mut Window,
11900        cx: &mut Context<Self>,
11901    ) {
11902        let snapshot = self.snapshot(window, cx);
11903        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11904        let mut ranges_by_buffer = HashMap::default();
11905        self.transact(window, cx, |editor, _window, cx| {
11906            for hunk in hunks {
11907                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11908                    ranges_by_buffer
11909                        .entry(buffer.clone())
11910                        .or_insert_with(Vec::new)
11911                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11912                }
11913            }
11914
11915            for (buffer, ranges) in ranges_by_buffer {
11916                buffer.update(cx, |buffer, cx| {
11917                    buffer.merge_into_base(ranges, cx);
11918                });
11919            }
11920        });
11921
11922        if let Some(project) = self.project.clone() {
11923            self.save(true, project, window, cx).detach_and_log_err(cx);
11924        }
11925    }
11926
11927    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11928        if hovered != self.gutter_hovered {
11929            self.gutter_hovered = hovered;
11930            cx.notify();
11931        }
11932    }
11933
11934    pub fn insert_blocks(
11935        &mut self,
11936        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11937        autoscroll: Option<Autoscroll>,
11938        cx: &mut Context<Self>,
11939    ) -> Vec<CustomBlockId> {
11940        let blocks = self
11941            .display_map
11942            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11943        if let Some(autoscroll) = autoscroll {
11944            self.request_autoscroll(autoscroll, cx);
11945        }
11946        cx.notify();
11947        blocks
11948    }
11949
11950    pub fn resize_blocks(
11951        &mut self,
11952        heights: HashMap<CustomBlockId, u32>,
11953        autoscroll: Option<Autoscroll>,
11954        cx: &mut Context<Self>,
11955    ) {
11956        self.display_map
11957            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11958        if let Some(autoscroll) = autoscroll {
11959            self.request_autoscroll(autoscroll, cx);
11960        }
11961        cx.notify();
11962    }
11963
11964    pub fn replace_blocks(
11965        &mut self,
11966        renderers: HashMap<CustomBlockId, RenderBlock>,
11967        autoscroll: Option<Autoscroll>,
11968        cx: &mut Context<Self>,
11969    ) {
11970        self.display_map
11971            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11972        if let Some(autoscroll) = autoscroll {
11973            self.request_autoscroll(autoscroll, cx);
11974        }
11975        cx.notify();
11976    }
11977
11978    pub fn remove_blocks(
11979        &mut self,
11980        block_ids: HashSet<CustomBlockId>,
11981        autoscroll: Option<Autoscroll>,
11982        cx: &mut Context<Self>,
11983    ) {
11984        self.display_map.update(cx, |display_map, cx| {
11985            display_map.remove_blocks(block_ids, cx)
11986        });
11987        if let Some(autoscroll) = autoscroll {
11988            self.request_autoscroll(autoscroll, cx);
11989        }
11990        cx.notify();
11991    }
11992
11993    pub fn row_for_block(
11994        &self,
11995        block_id: CustomBlockId,
11996        cx: &mut Context<Self>,
11997    ) -> Option<DisplayRow> {
11998        self.display_map
11999            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12000    }
12001
12002    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12003        self.focused_block = Some(focused_block);
12004    }
12005
12006    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12007        self.focused_block.take()
12008    }
12009
12010    pub fn insert_creases(
12011        &mut self,
12012        creases: impl IntoIterator<Item = Crease<Anchor>>,
12013        cx: &mut Context<Self>,
12014    ) -> Vec<CreaseId> {
12015        self.display_map
12016            .update(cx, |map, cx| map.insert_creases(creases, cx))
12017    }
12018
12019    pub fn remove_creases(
12020        &mut self,
12021        ids: impl IntoIterator<Item = CreaseId>,
12022        cx: &mut Context<Self>,
12023    ) {
12024        self.display_map
12025            .update(cx, |map, cx| map.remove_creases(ids, cx));
12026    }
12027
12028    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12029        self.display_map
12030            .update(cx, |map, cx| map.snapshot(cx))
12031            .longest_row()
12032    }
12033
12034    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12035        self.display_map
12036            .update(cx, |map, cx| map.snapshot(cx))
12037            .max_point()
12038    }
12039
12040    pub fn text(&self, cx: &App) -> String {
12041        self.buffer.read(cx).read(cx).text()
12042    }
12043
12044    pub fn text_option(&self, cx: &App) -> Option<String> {
12045        let text = self.text(cx);
12046        let text = text.trim();
12047
12048        if text.is_empty() {
12049            return None;
12050        }
12051
12052        Some(text.to_string())
12053    }
12054
12055    pub fn set_text(
12056        &mut self,
12057        text: impl Into<Arc<str>>,
12058        window: &mut Window,
12059        cx: &mut Context<Self>,
12060    ) {
12061        self.transact(window, cx, |this, _, cx| {
12062            this.buffer
12063                .read(cx)
12064                .as_singleton()
12065                .expect("you can only call set_text on editors for singleton buffers")
12066                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12067        });
12068    }
12069
12070    pub fn display_text(&self, cx: &mut App) -> String {
12071        self.display_map
12072            .update(cx, |map, cx| map.snapshot(cx))
12073            .text()
12074    }
12075
12076    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12077        let mut wrap_guides = smallvec::smallvec![];
12078
12079        if self.show_wrap_guides == Some(false) {
12080            return wrap_guides;
12081        }
12082
12083        let settings = self.buffer.read(cx).settings_at(0, cx);
12084        if settings.show_wrap_guides {
12085            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12086                wrap_guides.push((soft_wrap as usize, true));
12087            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12088                wrap_guides.push((soft_wrap as usize, true));
12089            }
12090            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12091        }
12092
12093        wrap_guides
12094    }
12095
12096    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12097        let settings = self.buffer.read(cx).settings_at(0, cx);
12098        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12099        match mode {
12100            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12101                SoftWrap::None
12102            }
12103            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12104            language_settings::SoftWrap::PreferredLineLength => {
12105                SoftWrap::Column(settings.preferred_line_length)
12106            }
12107            language_settings::SoftWrap::Bounded => {
12108                SoftWrap::Bounded(settings.preferred_line_length)
12109            }
12110        }
12111    }
12112
12113    pub fn set_soft_wrap_mode(
12114        &mut self,
12115        mode: language_settings::SoftWrap,
12116
12117        cx: &mut Context<Self>,
12118    ) {
12119        self.soft_wrap_mode_override = Some(mode);
12120        cx.notify();
12121    }
12122
12123    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12124        self.text_style_refinement = Some(style);
12125    }
12126
12127    /// called by the Element so we know what style we were most recently rendered with.
12128    pub(crate) fn set_style(
12129        &mut self,
12130        style: EditorStyle,
12131        window: &mut Window,
12132        cx: &mut Context<Self>,
12133    ) {
12134        let rem_size = window.rem_size();
12135        self.display_map.update(cx, |map, cx| {
12136            map.set_font(
12137                style.text.font(),
12138                style.text.font_size.to_pixels(rem_size),
12139                cx,
12140            )
12141        });
12142        self.style = Some(style);
12143    }
12144
12145    pub fn style(&self) -> Option<&EditorStyle> {
12146        self.style.as_ref()
12147    }
12148
12149    // Called by the element. This method is not designed to be called outside of the editor
12150    // element's layout code because it does not notify when rewrapping is computed synchronously.
12151    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12152        self.display_map
12153            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12154    }
12155
12156    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12157        if self.soft_wrap_mode_override.is_some() {
12158            self.soft_wrap_mode_override.take();
12159        } else {
12160            let soft_wrap = match self.soft_wrap_mode(cx) {
12161                SoftWrap::GitDiff => return,
12162                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12163                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12164                    language_settings::SoftWrap::None
12165                }
12166            };
12167            self.soft_wrap_mode_override = Some(soft_wrap);
12168        }
12169        cx.notify();
12170    }
12171
12172    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12173        let Some(workspace) = self.workspace() else {
12174            return;
12175        };
12176        let fs = workspace.read(cx).app_state().fs.clone();
12177        let current_show = TabBarSettings::get_global(cx).show;
12178        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12179            setting.show = Some(!current_show);
12180        });
12181    }
12182
12183    pub fn toggle_indent_guides(
12184        &mut self,
12185        _: &ToggleIndentGuides,
12186        _: &mut Window,
12187        cx: &mut Context<Self>,
12188    ) {
12189        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12190            self.buffer
12191                .read(cx)
12192                .settings_at(0, cx)
12193                .indent_guides
12194                .enabled
12195        });
12196        self.show_indent_guides = Some(!currently_enabled);
12197        cx.notify();
12198    }
12199
12200    fn should_show_indent_guides(&self) -> Option<bool> {
12201        self.show_indent_guides
12202    }
12203
12204    pub fn toggle_line_numbers(
12205        &mut self,
12206        _: &ToggleLineNumbers,
12207        _: &mut Window,
12208        cx: &mut Context<Self>,
12209    ) {
12210        let mut editor_settings = EditorSettings::get_global(cx).clone();
12211        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12212        EditorSettings::override_global(editor_settings, cx);
12213    }
12214
12215    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12216        self.use_relative_line_numbers
12217            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12218    }
12219
12220    pub fn toggle_relative_line_numbers(
12221        &mut self,
12222        _: &ToggleRelativeLineNumbers,
12223        _: &mut Window,
12224        cx: &mut Context<Self>,
12225    ) {
12226        let is_relative = self.should_use_relative_line_numbers(cx);
12227        self.set_relative_line_number(Some(!is_relative), cx)
12228    }
12229
12230    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12231        self.use_relative_line_numbers = is_relative;
12232        cx.notify();
12233    }
12234
12235    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12236        self.show_gutter = show_gutter;
12237        cx.notify();
12238    }
12239
12240    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12241        self.show_scrollbars = show_scrollbars;
12242        cx.notify();
12243    }
12244
12245    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12246        self.show_line_numbers = Some(show_line_numbers);
12247        cx.notify();
12248    }
12249
12250    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12251        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12252        cx.notify();
12253    }
12254
12255    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12256        self.show_code_actions = Some(show_code_actions);
12257        cx.notify();
12258    }
12259
12260    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12261        self.show_runnables = Some(show_runnables);
12262        cx.notify();
12263    }
12264
12265    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12266        if self.display_map.read(cx).masked != masked {
12267            self.display_map.update(cx, |map, _| map.masked = masked);
12268        }
12269        cx.notify()
12270    }
12271
12272    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12273        self.show_wrap_guides = Some(show_wrap_guides);
12274        cx.notify();
12275    }
12276
12277    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12278        self.show_indent_guides = Some(show_indent_guides);
12279        cx.notify();
12280    }
12281
12282    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12283        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12284            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12285                if let Some(dir) = file.abs_path(cx).parent() {
12286                    return Some(dir.to_owned());
12287                }
12288            }
12289
12290            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12291                return Some(project_path.path.to_path_buf());
12292            }
12293        }
12294
12295        None
12296    }
12297
12298    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12299        self.active_excerpt(cx)?
12300            .1
12301            .read(cx)
12302            .file()
12303            .and_then(|f| f.as_local())
12304    }
12305
12306    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12307        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12308            let project_path = buffer.read(cx).project_path(cx)?;
12309            let project = self.project.as_ref()?.read(cx);
12310            project.absolute_path(&project_path, cx)
12311        })
12312    }
12313
12314    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12315        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12316            let project_path = buffer.read(cx).project_path(cx)?;
12317            let project = self.project.as_ref()?.read(cx);
12318            let entry = project.entry_for_path(&project_path, cx)?;
12319            let path = entry.path.to_path_buf();
12320            Some(path)
12321        })
12322    }
12323
12324    pub fn reveal_in_finder(
12325        &mut self,
12326        _: &RevealInFileManager,
12327        _window: &mut Window,
12328        cx: &mut Context<Self>,
12329    ) {
12330        if let Some(target) = self.target_file(cx) {
12331            cx.reveal_path(&target.abs_path(cx));
12332        }
12333    }
12334
12335    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12336        if let Some(path) = self.target_file_abs_path(cx) {
12337            if let Some(path) = path.to_str() {
12338                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12339            }
12340        }
12341    }
12342
12343    pub fn copy_relative_path(
12344        &mut self,
12345        _: &CopyRelativePath,
12346        _window: &mut Window,
12347        cx: &mut Context<Self>,
12348    ) {
12349        if let Some(path) = self.target_file_path(cx) {
12350            if let Some(path) = path.to_str() {
12351                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12352            }
12353        }
12354    }
12355
12356    pub fn toggle_git_blame(
12357        &mut self,
12358        _: &ToggleGitBlame,
12359        window: &mut Window,
12360        cx: &mut Context<Self>,
12361    ) {
12362        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12363
12364        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12365            self.start_git_blame(true, window, cx);
12366        }
12367
12368        cx.notify();
12369    }
12370
12371    pub fn toggle_git_blame_inline(
12372        &mut self,
12373        _: &ToggleGitBlameInline,
12374        window: &mut Window,
12375        cx: &mut Context<Self>,
12376    ) {
12377        self.toggle_git_blame_inline_internal(true, window, cx);
12378        cx.notify();
12379    }
12380
12381    pub fn git_blame_inline_enabled(&self) -> bool {
12382        self.git_blame_inline_enabled
12383    }
12384
12385    pub fn toggle_selection_menu(
12386        &mut self,
12387        _: &ToggleSelectionMenu,
12388        _: &mut Window,
12389        cx: &mut Context<Self>,
12390    ) {
12391        self.show_selection_menu = self
12392            .show_selection_menu
12393            .map(|show_selections_menu| !show_selections_menu)
12394            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12395
12396        cx.notify();
12397    }
12398
12399    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12400        self.show_selection_menu
12401            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12402    }
12403
12404    fn start_git_blame(
12405        &mut self,
12406        user_triggered: bool,
12407        window: &mut Window,
12408        cx: &mut Context<Self>,
12409    ) {
12410        if let Some(project) = self.project.as_ref() {
12411            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12412                return;
12413            };
12414
12415            if buffer.read(cx).file().is_none() {
12416                return;
12417            }
12418
12419            let focused = self.focus_handle(cx).contains_focused(window, cx);
12420
12421            let project = project.clone();
12422            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12423            self.blame_subscription =
12424                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12425            self.blame = Some(blame);
12426        }
12427    }
12428
12429    fn toggle_git_blame_inline_internal(
12430        &mut self,
12431        user_triggered: bool,
12432        window: &mut Window,
12433        cx: &mut Context<Self>,
12434    ) {
12435        if self.git_blame_inline_enabled {
12436            self.git_blame_inline_enabled = false;
12437            self.show_git_blame_inline = false;
12438            self.show_git_blame_inline_delay_task.take();
12439        } else {
12440            self.git_blame_inline_enabled = true;
12441            self.start_git_blame_inline(user_triggered, window, cx);
12442        }
12443
12444        cx.notify();
12445    }
12446
12447    fn start_git_blame_inline(
12448        &mut self,
12449        user_triggered: bool,
12450        window: &mut Window,
12451        cx: &mut Context<Self>,
12452    ) {
12453        self.start_git_blame(user_triggered, window, cx);
12454
12455        if ProjectSettings::get_global(cx)
12456            .git
12457            .inline_blame_delay()
12458            .is_some()
12459        {
12460            self.start_inline_blame_timer(window, cx);
12461        } else {
12462            self.show_git_blame_inline = true
12463        }
12464    }
12465
12466    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12467        self.blame.as_ref()
12468    }
12469
12470    pub fn show_git_blame_gutter(&self) -> bool {
12471        self.show_git_blame_gutter
12472    }
12473
12474    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12475        self.show_git_blame_gutter && self.has_blame_entries(cx)
12476    }
12477
12478    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12479        self.show_git_blame_inline
12480            && self.focus_handle.is_focused(window)
12481            && !self.newest_selection_head_on_empty_line(cx)
12482            && self.has_blame_entries(cx)
12483    }
12484
12485    fn has_blame_entries(&self, cx: &App) -> bool {
12486        self.blame()
12487            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12488    }
12489
12490    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12491        let cursor_anchor = self.selections.newest_anchor().head();
12492
12493        let snapshot = self.buffer.read(cx).snapshot(cx);
12494        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12495
12496        snapshot.line_len(buffer_row) == 0
12497    }
12498
12499    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12500        let buffer_and_selection = maybe!({
12501            let selection = self.selections.newest::<Point>(cx);
12502            let selection_range = selection.range();
12503
12504            let multi_buffer = self.buffer().read(cx);
12505            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12506            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12507
12508            let (buffer, range, _) = if selection.reversed {
12509                buffer_ranges.first()
12510            } else {
12511                buffer_ranges.last()
12512            }?;
12513
12514            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12515                ..text::ToPoint::to_point(&range.end, &buffer).row;
12516            Some((
12517                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12518                selection,
12519            ))
12520        });
12521
12522        let Some((buffer, selection)) = buffer_and_selection else {
12523            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12524        };
12525
12526        let Some(project) = self.project.as_ref() else {
12527            return Task::ready(Err(anyhow!("editor does not have project")));
12528        };
12529
12530        project.update(cx, |project, cx| {
12531            project.get_permalink_to_line(&buffer, selection, cx)
12532        })
12533    }
12534
12535    pub fn copy_permalink_to_line(
12536        &mut self,
12537        _: &CopyPermalinkToLine,
12538        window: &mut Window,
12539        cx: &mut Context<Self>,
12540    ) {
12541        let permalink_task = self.get_permalink_to_line(cx);
12542        let workspace = self.workspace();
12543
12544        cx.spawn_in(window, |_, mut cx| async move {
12545            match permalink_task.await {
12546                Ok(permalink) => {
12547                    cx.update(|_, cx| {
12548                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12549                    })
12550                    .ok();
12551                }
12552                Err(err) => {
12553                    let message = format!("Failed to copy permalink: {err}");
12554
12555                    Err::<(), anyhow::Error>(err).log_err();
12556
12557                    if let Some(workspace) = workspace {
12558                        workspace
12559                            .update_in(&mut cx, |workspace, _, cx| {
12560                                struct CopyPermalinkToLine;
12561
12562                                workspace.show_toast(
12563                                    Toast::new(
12564                                        NotificationId::unique::<CopyPermalinkToLine>(),
12565                                        message,
12566                                    ),
12567                                    cx,
12568                                )
12569                            })
12570                            .ok();
12571                    }
12572                }
12573            }
12574        })
12575        .detach();
12576    }
12577
12578    pub fn copy_file_location(
12579        &mut self,
12580        _: &CopyFileLocation,
12581        _: &mut Window,
12582        cx: &mut Context<Self>,
12583    ) {
12584        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12585        if let Some(file) = self.target_file(cx) {
12586            if let Some(path) = file.path().to_str() {
12587                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12588            }
12589        }
12590    }
12591
12592    pub fn open_permalink_to_line(
12593        &mut self,
12594        _: &OpenPermalinkToLine,
12595        window: &mut Window,
12596        cx: &mut Context<Self>,
12597    ) {
12598        let permalink_task = self.get_permalink_to_line(cx);
12599        let workspace = self.workspace();
12600
12601        cx.spawn_in(window, |_, mut cx| async move {
12602            match permalink_task.await {
12603                Ok(permalink) => {
12604                    cx.update(|_, cx| {
12605                        cx.open_url(permalink.as_ref());
12606                    })
12607                    .ok();
12608                }
12609                Err(err) => {
12610                    let message = format!("Failed to open permalink: {err}");
12611
12612                    Err::<(), anyhow::Error>(err).log_err();
12613
12614                    if let Some(workspace) = workspace {
12615                        workspace
12616                            .update(&mut cx, |workspace, cx| {
12617                                struct OpenPermalinkToLine;
12618
12619                                workspace.show_toast(
12620                                    Toast::new(
12621                                        NotificationId::unique::<OpenPermalinkToLine>(),
12622                                        message,
12623                                    ),
12624                                    cx,
12625                                )
12626                            })
12627                            .ok();
12628                    }
12629                }
12630            }
12631        })
12632        .detach();
12633    }
12634
12635    pub fn insert_uuid_v4(
12636        &mut self,
12637        _: &InsertUuidV4,
12638        window: &mut Window,
12639        cx: &mut Context<Self>,
12640    ) {
12641        self.insert_uuid(UuidVersion::V4, window, cx);
12642    }
12643
12644    pub fn insert_uuid_v7(
12645        &mut self,
12646        _: &InsertUuidV7,
12647        window: &mut Window,
12648        cx: &mut Context<Self>,
12649    ) {
12650        self.insert_uuid(UuidVersion::V7, window, cx);
12651    }
12652
12653    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12654        self.transact(window, cx, |this, window, cx| {
12655            let edits = this
12656                .selections
12657                .all::<Point>(cx)
12658                .into_iter()
12659                .map(|selection| {
12660                    let uuid = match version {
12661                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12662                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12663                    };
12664
12665                    (selection.range(), uuid.to_string())
12666                });
12667            this.edit(edits, cx);
12668            this.refresh_inline_completion(true, false, window, cx);
12669        });
12670    }
12671
12672    pub fn open_selections_in_multibuffer(
12673        &mut self,
12674        _: &OpenSelectionsInMultibuffer,
12675        window: &mut Window,
12676        cx: &mut Context<Self>,
12677    ) {
12678        let multibuffer = self.buffer.read(cx);
12679
12680        let Some(buffer) = multibuffer.as_singleton() else {
12681            return;
12682        };
12683
12684        let Some(workspace) = self.workspace() else {
12685            return;
12686        };
12687
12688        let locations = self
12689            .selections
12690            .disjoint_anchors()
12691            .iter()
12692            .map(|range| Location {
12693                buffer: buffer.clone(),
12694                range: range.start.text_anchor..range.end.text_anchor,
12695            })
12696            .collect::<Vec<_>>();
12697
12698        let title = multibuffer.title(cx).to_string();
12699
12700        cx.spawn_in(window, |_, mut cx| async move {
12701            workspace.update_in(&mut cx, |workspace, window, cx| {
12702                Self::open_locations_in_multibuffer(
12703                    workspace,
12704                    locations,
12705                    format!("Selections for '{title}'"),
12706                    false,
12707                    MultibufferSelectionMode::All,
12708                    window,
12709                    cx,
12710                );
12711            })
12712        })
12713        .detach();
12714    }
12715
12716    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12717    /// last highlight added will be used.
12718    ///
12719    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12720    pub fn highlight_rows<T: 'static>(
12721        &mut self,
12722        range: Range<Anchor>,
12723        color: Hsla,
12724        should_autoscroll: bool,
12725        cx: &mut Context<Self>,
12726    ) {
12727        let snapshot = self.buffer().read(cx).snapshot(cx);
12728        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12729        let ix = row_highlights.binary_search_by(|highlight| {
12730            Ordering::Equal
12731                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12732                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12733        });
12734
12735        if let Err(mut ix) = ix {
12736            let index = post_inc(&mut self.highlight_order);
12737
12738            // If this range intersects with the preceding highlight, then merge it with
12739            // the preceding highlight. Otherwise insert a new highlight.
12740            let mut merged = false;
12741            if ix > 0 {
12742                let prev_highlight = &mut row_highlights[ix - 1];
12743                if prev_highlight
12744                    .range
12745                    .end
12746                    .cmp(&range.start, &snapshot)
12747                    .is_ge()
12748                {
12749                    ix -= 1;
12750                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12751                        prev_highlight.range.end = range.end;
12752                    }
12753                    merged = true;
12754                    prev_highlight.index = index;
12755                    prev_highlight.color = color;
12756                    prev_highlight.should_autoscroll = should_autoscroll;
12757                }
12758            }
12759
12760            if !merged {
12761                row_highlights.insert(
12762                    ix,
12763                    RowHighlight {
12764                        range: range.clone(),
12765                        index,
12766                        color,
12767                        should_autoscroll,
12768                    },
12769                );
12770            }
12771
12772            // If any of the following highlights intersect with this one, merge them.
12773            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12774                let highlight = &row_highlights[ix];
12775                if next_highlight
12776                    .range
12777                    .start
12778                    .cmp(&highlight.range.end, &snapshot)
12779                    .is_le()
12780                {
12781                    if next_highlight
12782                        .range
12783                        .end
12784                        .cmp(&highlight.range.end, &snapshot)
12785                        .is_gt()
12786                    {
12787                        row_highlights[ix].range.end = next_highlight.range.end;
12788                    }
12789                    row_highlights.remove(ix + 1);
12790                } else {
12791                    break;
12792                }
12793            }
12794        }
12795    }
12796
12797    /// Remove any highlighted row ranges of the given type that intersect the
12798    /// given ranges.
12799    pub fn remove_highlighted_rows<T: 'static>(
12800        &mut self,
12801        ranges_to_remove: Vec<Range<Anchor>>,
12802        cx: &mut Context<Self>,
12803    ) {
12804        let snapshot = self.buffer().read(cx).snapshot(cx);
12805        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12806        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12807        row_highlights.retain(|highlight| {
12808            while let Some(range_to_remove) = ranges_to_remove.peek() {
12809                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12810                    Ordering::Less | Ordering::Equal => {
12811                        ranges_to_remove.next();
12812                    }
12813                    Ordering::Greater => {
12814                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12815                            Ordering::Less | Ordering::Equal => {
12816                                return false;
12817                            }
12818                            Ordering::Greater => break,
12819                        }
12820                    }
12821                }
12822            }
12823
12824            true
12825        })
12826    }
12827
12828    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12829    pub fn clear_row_highlights<T: 'static>(&mut self) {
12830        self.highlighted_rows.remove(&TypeId::of::<T>());
12831    }
12832
12833    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12834    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12835        self.highlighted_rows
12836            .get(&TypeId::of::<T>())
12837            .map_or(&[] as &[_], |vec| vec.as_slice())
12838            .iter()
12839            .map(|highlight| (highlight.range.clone(), highlight.color))
12840    }
12841
12842    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12843    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12844    /// Allows to ignore certain kinds of highlights.
12845    pub fn highlighted_display_rows(
12846        &self,
12847        window: &mut Window,
12848        cx: &mut App,
12849    ) -> BTreeMap<DisplayRow, Hsla> {
12850        let snapshot = self.snapshot(window, cx);
12851        let mut used_highlight_orders = HashMap::default();
12852        self.highlighted_rows
12853            .iter()
12854            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12855            .fold(
12856                BTreeMap::<DisplayRow, Hsla>::new(),
12857                |mut unique_rows, highlight| {
12858                    let start = highlight.range.start.to_display_point(&snapshot);
12859                    let end = highlight.range.end.to_display_point(&snapshot);
12860                    let start_row = start.row().0;
12861                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12862                        && end.column() == 0
12863                    {
12864                        end.row().0.saturating_sub(1)
12865                    } else {
12866                        end.row().0
12867                    };
12868                    for row in start_row..=end_row {
12869                        let used_index =
12870                            used_highlight_orders.entry(row).or_insert(highlight.index);
12871                        if highlight.index >= *used_index {
12872                            *used_index = highlight.index;
12873                            unique_rows.insert(DisplayRow(row), highlight.color);
12874                        }
12875                    }
12876                    unique_rows
12877                },
12878            )
12879    }
12880
12881    pub fn highlighted_display_row_for_autoscroll(
12882        &self,
12883        snapshot: &DisplaySnapshot,
12884    ) -> Option<DisplayRow> {
12885        self.highlighted_rows
12886            .values()
12887            .flat_map(|highlighted_rows| highlighted_rows.iter())
12888            .filter_map(|highlight| {
12889                if highlight.should_autoscroll {
12890                    Some(highlight.range.start.to_display_point(snapshot).row())
12891                } else {
12892                    None
12893                }
12894            })
12895            .min()
12896    }
12897
12898    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12899        self.highlight_background::<SearchWithinRange>(
12900            ranges,
12901            |colors| colors.editor_document_highlight_read_background,
12902            cx,
12903        )
12904    }
12905
12906    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12907        self.breadcrumb_header = Some(new_header);
12908    }
12909
12910    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12911        self.clear_background_highlights::<SearchWithinRange>(cx);
12912    }
12913
12914    pub fn highlight_background<T: 'static>(
12915        &mut self,
12916        ranges: &[Range<Anchor>],
12917        color_fetcher: fn(&ThemeColors) -> Hsla,
12918        cx: &mut Context<Self>,
12919    ) {
12920        self.background_highlights
12921            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12922        self.scrollbar_marker_state.dirty = true;
12923        cx.notify();
12924    }
12925
12926    pub fn clear_background_highlights<T: 'static>(
12927        &mut self,
12928        cx: &mut Context<Self>,
12929    ) -> Option<BackgroundHighlight> {
12930        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12931        if !text_highlights.1.is_empty() {
12932            self.scrollbar_marker_state.dirty = true;
12933            cx.notify();
12934        }
12935        Some(text_highlights)
12936    }
12937
12938    pub fn highlight_gutter<T: 'static>(
12939        &mut self,
12940        ranges: &[Range<Anchor>],
12941        color_fetcher: fn(&App) -> Hsla,
12942        cx: &mut Context<Self>,
12943    ) {
12944        self.gutter_highlights
12945            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12946        cx.notify();
12947    }
12948
12949    pub fn clear_gutter_highlights<T: 'static>(
12950        &mut self,
12951        cx: &mut Context<Self>,
12952    ) -> Option<GutterHighlight> {
12953        cx.notify();
12954        self.gutter_highlights.remove(&TypeId::of::<T>())
12955    }
12956
12957    #[cfg(feature = "test-support")]
12958    pub fn all_text_background_highlights(
12959        &self,
12960        window: &mut Window,
12961        cx: &mut Context<Self>,
12962    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12963        let snapshot = self.snapshot(window, cx);
12964        let buffer = &snapshot.buffer_snapshot;
12965        let start = buffer.anchor_before(0);
12966        let end = buffer.anchor_after(buffer.len());
12967        let theme = cx.theme().colors();
12968        self.background_highlights_in_range(start..end, &snapshot, theme)
12969    }
12970
12971    #[cfg(feature = "test-support")]
12972    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12973        let snapshot = self.buffer().read(cx).snapshot(cx);
12974
12975        let highlights = self
12976            .background_highlights
12977            .get(&TypeId::of::<items::BufferSearchHighlights>());
12978
12979        if let Some((_color, ranges)) = highlights {
12980            ranges
12981                .iter()
12982                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12983                .collect_vec()
12984        } else {
12985            vec![]
12986        }
12987    }
12988
12989    fn document_highlights_for_position<'a>(
12990        &'a self,
12991        position: Anchor,
12992        buffer: &'a MultiBufferSnapshot,
12993    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12994        let read_highlights = self
12995            .background_highlights
12996            .get(&TypeId::of::<DocumentHighlightRead>())
12997            .map(|h| &h.1);
12998        let write_highlights = self
12999            .background_highlights
13000            .get(&TypeId::of::<DocumentHighlightWrite>())
13001            .map(|h| &h.1);
13002        let left_position = position.bias_left(buffer);
13003        let right_position = position.bias_right(buffer);
13004        read_highlights
13005            .into_iter()
13006            .chain(write_highlights)
13007            .flat_map(move |ranges| {
13008                let start_ix = match ranges.binary_search_by(|probe| {
13009                    let cmp = probe.end.cmp(&left_position, buffer);
13010                    if cmp.is_ge() {
13011                        Ordering::Greater
13012                    } else {
13013                        Ordering::Less
13014                    }
13015                }) {
13016                    Ok(i) | Err(i) => i,
13017                };
13018
13019                ranges[start_ix..]
13020                    .iter()
13021                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13022            })
13023    }
13024
13025    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13026        self.background_highlights
13027            .get(&TypeId::of::<T>())
13028            .map_or(false, |(_, highlights)| !highlights.is_empty())
13029    }
13030
13031    pub fn background_highlights_in_range(
13032        &self,
13033        search_range: Range<Anchor>,
13034        display_snapshot: &DisplaySnapshot,
13035        theme: &ThemeColors,
13036    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13037        let mut results = Vec::new();
13038        for (color_fetcher, ranges) in self.background_highlights.values() {
13039            let color = color_fetcher(theme);
13040            let start_ix = match ranges.binary_search_by(|probe| {
13041                let cmp = probe
13042                    .end
13043                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13044                if cmp.is_gt() {
13045                    Ordering::Greater
13046                } else {
13047                    Ordering::Less
13048                }
13049            }) {
13050                Ok(i) | Err(i) => i,
13051            };
13052            for range in &ranges[start_ix..] {
13053                if range
13054                    .start
13055                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13056                    .is_ge()
13057                {
13058                    break;
13059                }
13060
13061                let start = range.start.to_display_point(display_snapshot);
13062                let end = range.end.to_display_point(display_snapshot);
13063                results.push((start..end, color))
13064            }
13065        }
13066        results
13067    }
13068
13069    pub fn background_highlight_row_ranges<T: 'static>(
13070        &self,
13071        search_range: Range<Anchor>,
13072        display_snapshot: &DisplaySnapshot,
13073        count: usize,
13074    ) -> Vec<RangeInclusive<DisplayPoint>> {
13075        let mut results = Vec::new();
13076        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13077            return vec![];
13078        };
13079
13080        let start_ix = match ranges.binary_search_by(|probe| {
13081            let cmp = probe
13082                .end
13083                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13084            if cmp.is_gt() {
13085                Ordering::Greater
13086            } else {
13087                Ordering::Less
13088            }
13089        }) {
13090            Ok(i) | Err(i) => i,
13091        };
13092        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13093            if let (Some(start_display), Some(end_display)) = (start, end) {
13094                results.push(
13095                    start_display.to_display_point(display_snapshot)
13096                        ..=end_display.to_display_point(display_snapshot),
13097                );
13098            }
13099        };
13100        let mut start_row: Option<Point> = None;
13101        let mut end_row: Option<Point> = None;
13102        if ranges.len() > count {
13103            return Vec::new();
13104        }
13105        for range in &ranges[start_ix..] {
13106            if range
13107                .start
13108                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13109                .is_ge()
13110            {
13111                break;
13112            }
13113            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13114            if let Some(current_row) = &end_row {
13115                if end.row == current_row.row {
13116                    continue;
13117                }
13118            }
13119            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13120            if start_row.is_none() {
13121                assert_eq!(end_row, None);
13122                start_row = Some(start);
13123                end_row = Some(end);
13124                continue;
13125            }
13126            if let Some(current_end) = end_row.as_mut() {
13127                if start.row > current_end.row + 1 {
13128                    push_region(start_row, end_row);
13129                    start_row = Some(start);
13130                    end_row = Some(end);
13131                } else {
13132                    // Merge two hunks.
13133                    *current_end = end;
13134                }
13135            } else {
13136                unreachable!();
13137            }
13138        }
13139        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13140        push_region(start_row, end_row);
13141        results
13142    }
13143
13144    pub fn gutter_highlights_in_range(
13145        &self,
13146        search_range: Range<Anchor>,
13147        display_snapshot: &DisplaySnapshot,
13148        cx: &App,
13149    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13150        let mut results = Vec::new();
13151        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13152            let color = color_fetcher(cx);
13153            let start_ix = match ranges.binary_search_by(|probe| {
13154                let cmp = probe
13155                    .end
13156                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13157                if cmp.is_gt() {
13158                    Ordering::Greater
13159                } else {
13160                    Ordering::Less
13161                }
13162            }) {
13163                Ok(i) | Err(i) => i,
13164            };
13165            for range in &ranges[start_ix..] {
13166                if range
13167                    .start
13168                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13169                    .is_ge()
13170                {
13171                    break;
13172                }
13173
13174                let start = range.start.to_display_point(display_snapshot);
13175                let end = range.end.to_display_point(display_snapshot);
13176                results.push((start..end, color))
13177            }
13178        }
13179        results
13180    }
13181
13182    /// Get the text ranges corresponding to the redaction query
13183    pub fn redacted_ranges(
13184        &self,
13185        search_range: Range<Anchor>,
13186        display_snapshot: &DisplaySnapshot,
13187        cx: &App,
13188    ) -> Vec<Range<DisplayPoint>> {
13189        display_snapshot
13190            .buffer_snapshot
13191            .redacted_ranges(search_range, |file| {
13192                if let Some(file) = file {
13193                    file.is_private()
13194                        && EditorSettings::get(
13195                            Some(SettingsLocation {
13196                                worktree_id: file.worktree_id(cx),
13197                                path: file.path().as_ref(),
13198                            }),
13199                            cx,
13200                        )
13201                        .redact_private_values
13202                } else {
13203                    false
13204                }
13205            })
13206            .map(|range| {
13207                range.start.to_display_point(display_snapshot)
13208                    ..range.end.to_display_point(display_snapshot)
13209            })
13210            .collect()
13211    }
13212
13213    pub fn highlight_text<T: 'static>(
13214        &mut self,
13215        ranges: Vec<Range<Anchor>>,
13216        style: HighlightStyle,
13217        cx: &mut Context<Self>,
13218    ) {
13219        self.display_map.update(cx, |map, _| {
13220            map.highlight_text(TypeId::of::<T>(), ranges, style)
13221        });
13222        cx.notify();
13223    }
13224
13225    pub(crate) fn highlight_inlays<T: 'static>(
13226        &mut self,
13227        highlights: Vec<InlayHighlight>,
13228        style: HighlightStyle,
13229        cx: &mut Context<Self>,
13230    ) {
13231        self.display_map.update(cx, |map, _| {
13232            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13233        });
13234        cx.notify();
13235    }
13236
13237    pub fn text_highlights<'a, T: 'static>(
13238        &'a self,
13239        cx: &'a App,
13240    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13241        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13242    }
13243
13244    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13245        let cleared = self
13246            .display_map
13247            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13248        if cleared {
13249            cx.notify();
13250        }
13251    }
13252
13253    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13254        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13255            && self.focus_handle.is_focused(window)
13256    }
13257
13258    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13259        self.show_cursor_when_unfocused = is_enabled;
13260        cx.notify();
13261    }
13262
13263    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13264        self.project
13265            .as_ref()
13266            .map(|project| project.read(cx).lsp_store())
13267    }
13268
13269    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13270        cx.notify();
13271    }
13272
13273    fn on_buffer_event(
13274        &mut self,
13275        multibuffer: &Entity<MultiBuffer>,
13276        event: &multi_buffer::Event,
13277        window: &mut Window,
13278        cx: &mut Context<Self>,
13279    ) {
13280        match event {
13281            multi_buffer::Event::Edited {
13282                singleton_buffer_edited,
13283                edited_buffer: buffer_edited,
13284            } => {
13285                self.scrollbar_marker_state.dirty = true;
13286                self.active_indent_guides_state.dirty = true;
13287                self.refresh_active_diagnostics(cx);
13288                self.refresh_code_actions(window, cx);
13289                if self.has_active_inline_completion() {
13290                    self.update_visible_inline_completion(window, cx);
13291                }
13292                if let Some(buffer) = buffer_edited {
13293                    let buffer_id = buffer.read(cx).remote_id();
13294                    if !self.registered_buffers.contains_key(&buffer_id) {
13295                        if let Some(lsp_store) = self.lsp_store(cx) {
13296                            lsp_store.update(cx, |lsp_store, cx| {
13297                                self.registered_buffers.insert(
13298                                    buffer_id,
13299                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13300                                );
13301                            })
13302                        }
13303                    }
13304                }
13305                cx.emit(EditorEvent::BufferEdited);
13306                cx.emit(SearchEvent::MatchesInvalidated);
13307                if *singleton_buffer_edited {
13308                    if let Some(project) = &self.project {
13309                        #[allow(clippy::mutable_key_type)]
13310                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
13311                            multibuffer
13312                                .all_buffers()
13313                                .into_iter()
13314                                .filter_map(|buffer| {
13315                                    buffer.update(cx, |buffer, cx| {
13316                                        let language = buffer.language()?;
13317                                        let should_discard = project.update(cx, |project, cx| {
13318                                            project.is_local()
13319                                                && project.for_language_servers_for_local_buffer(
13320                                                    buffer,
13321                                                    |it| it.count() == 0,
13322                                                    cx,
13323                                                )
13324                                        });
13325                                        should_discard.not().then_some(language.clone())
13326                                    })
13327                                })
13328                                .collect::<HashSet<_>>()
13329                        });
13330                        if !languages_affected.is_empty() {
13331                            self.refresh_inlay_hints(
13332                                InlayHintRefreshReason::BufferEdited(languages_affected),
13333                                cx,
13334                            );
13335                        }
13336                    }
13337                }
13338
13339                let Some(project) = &self.project else { return };
13340                let (telemetry, is_via_ssh) = {
13341                    let project = project.read(cx);
13342                    let telemetry = project.client().telemetry().clone();
13343                    let is_via_ssh = project.is_via_ssh();
13344                    (telemetry, is_via_ssh)
13345                };
13346                refresh_linked_ranges(self, window, cx);
13347                telemetry.log_edit_event("editor", is_via_ssh);
13348            }
13349            multi_buffer::Event::ExcerptsAdded {
13350                buffer,
13351                predecessor,
13352                excerpts,
13353            } => {
13354                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13355                let buffer_id = buffer.read(cx).remote_id();
13356                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13357                    if let Some(project) = &self.project {
13358                        get_unstaged_changes_for_buffers(
13359                            project,
13360                            [buffer.clone()],
13361                            self.buffer.clone(),
13362                            cx,
13363                        );
13364                    }
13365                }
13366                cx.emit(EditorEvent::ExcerptsAdded {
13367                    buffer: buffer.clone(),
13368                    predecessor: *predecessor,
13369                    excerpts: excerpts.clone(),
13370                });
13371                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13372            }
13373            multi_buffer::Event::ExcerptsRemoved { ids } => {
13374                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13375                let buffer = self.buffer.read(cx);
13376                self.registered_buffers
13377                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13378                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13379            }
13380            multi_buffer::Event::ExcerptsEdited { ids } => {
13381                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13382            }
13383            multi_buffer::Event::ExcerptsExpanded { ids } => {
13384                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13385                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13386            }
13387            multi_buffer::Event::Reparsed(buffer_id) => {
13388                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13389
13390                cx.emit(EditorEvent::Reparsed(*buffer_id));
13391            }
13392            multi_buffer::Event::DiffHunksToggled => {
13393                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13394            }
13395            multi_buffer::Event::LanguageChanged(buffer_id) => {
13396                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13397                cx.emit(EditorEvent::Reparsed(*buffer_id));
13398                cx.notify();
13399            }
13400            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13401            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13402            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13403                cx.emit(EditorEvent::TitleChanged)
13404            }
13405            // multi_buffer::Event::DiffBaseChanged => {
13406            //     self.scrollbar_marker_state.dirty = true;
13407            //     cx.emit(EditorEvent::DiffBaseChanged);
13408            //     cx.notify();
13409            // }
13410            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13411            multi_buffer::Event::DiagnosticsUpdated => {
13412                self.refresh_active_diagnostics(cx);
13413                self.scrollbar_marker_state.dirty = true;
13414                cx.notify();
13415            }
13416            _ => {}
13417        };
13418    }
13419
13420    fn on_display_map_changed(
13421        &mut self,
13422        _: Entity<DisplayMap>,
13423        _: &mut Window,
13424        cx: &mut Context<Self>,
13425    ) {
13426        cx.notify();
13427    }
13428
13429    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13430        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13431        self.refresh_inline_completion(true, false, window, cx);
13432        self.refresh_inlay_hints(
13433            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13434                self.selections.newest_anchor().head(),
13435                &self.buffer.read(cx).snapshot(cx),
13436                cx,
13437            )),
13438            cx,
13439        );
13440
13441        let old_cursor_shape = self.cursor_shape;
13442
13443        {
13444            let editor_settings = EditorSettings::get_global(cx);
13445            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13446            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13447            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13448        }
13449
13450        if old_cursor_shape != self.cursor_shape {
13451            cx.emit(EditorEvent::CursorShapeChanged);
13452        }
13453
13454        let project_settings = ProjectSettings::get_global(cx);
13455        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13456
13457        if self.mode == EditorMode::Full {
13458            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13459            if self.git_blame_inline_enabled != inline_blame_enabled {
13460                self.toggle_git_blame_inline_internal(false, window, cx);
13461            }
13462        }
13463
13464        cx.notify();
13465    }
13466
13467    pub fn set_searchable(&mut self, searchable: bool) {
13468        self.searchable = searchable;
13469    }
13470
13471    pub fn searchable(&self) -> bool {
13472        self.searchable
13473    }
13474
13475    fn open_proposed_changes_editor(
13476        &mut self,
13477        _: &OpenProposedChangesEditor,
13478        window: &mut Window,
13479        cx: &mut Context<Self>,
13480    ) {
13481        let Some(workspace) = self.workspace() else {
13482            cx.propagate();
13483            return;
13484        };
13485
13486        let selections = self.selections.all::<usize>(cx);
13487        let multi_buffer = self.buffer.read(cx);
13488        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13489        let mut new_selections_by_buffer = HashMap::default();
13490        for selection in selections {
13491            for (buffer, range, _) in
13492                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13493            {
13494                let mut range = range.to_point(buffer);
13495                range.start.column = 0;
13496                range.end.column = buffer.line_len(range.end.row);
13497                new_selections_by_buffer
13498                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13499                    .or_insert(Vec::new())
13500                    .push(range)
13501            }
13502        }
13503
13504        let proposed_changes_buffers = new_selections_by_buffer
13505            .into_iter()
13506            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13507            .collect::<Vec<_>>();
13508        let proposed_changes_editor = cx.new(|cx| {
13509            ProposedChangesEditor::new(
13510                "Proposed changes",
13511                proposed_changes_buffers,
13512                self.project.clone(),
13513                window,
13514                cx,
13515            )
13516        });
13517
13518        window.defer(cx, move |window, cx| {
13519            workspace.update(cx, |workspace, cx| {
13520                workspace.active_pane().update(cx, |pane, cx| {
13521                    pane.add_item(
13522                        Box::new(proposed_changes_editor),
13523                        true,
13524                        true,
13525                        None,
13526                        window,
13527                        cx,
13528                    );
13529                });
13530            });
13531        });
13532    }
13533
13534    pub fn open_excerpts_in_split(
13535        &mut self,
13536        _: &OpenExcerptsSplit,
13537        window: &mut Window,
13538        cx: &mut Context<Self>,
13539    ) {
13540        self.open_excerpts_common(None, true, window, cx)
13541    }
13542
13543    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13544        self.open_excerpts_common(None, false, window, cx)
13545    }
13546
13547    fn open_excerpts_common(
13548        &mut self,
13549        jump_data: Option<JumpData>,
13550        split: bool,
13551        window: &mut Window,
13552        cx: &mut Context<Self>,
13553    ) {
13554        let Some(workspace) = self.workspace() else {
13555            cx.propagate();
13556            return;
13557        };
13558
13559        if self.buffer.read(cx).is_singleton() {
13560            cx.propagate();
13561            return;
13562        }
13563
13564        let mut new_selections_by_buffer = HashMap::default();
13565        match &jump_data {
13566            Some(JumpData::MultiBufferPoint {
13567                excerpt_id,
13568                position,
13569                anchor,
13570                line_offset_from_top,
13571            }) => {
13572                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13573                if let Some(buffer) = multi_buffer_snapshot
13574                    .buffer_id_for_excerpt(*excerpt_id)
13575                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13576                {
13577                    let buffer_snapshot = buffer.read(cx).snapshot();
13578                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13579                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13580                    } else {
13581                        buffer_snapshot.clip_point(*position, Bias::Left)
13582                    };
13583                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13584                    new_selections_by_buffer.insert(
13585                        buffer,
13586                        (
13587                            vec![jump_to_offset..jump_to_offset],
13588                            Some(*line_offset_from_top),
13589                        ),
13590                    );
13591                }
13592            }
13593            Some(JumpData::MultiBufferRow {
13594                row,
13595                line_offset_from_top,
13596            }) => {
13597                let point = MultiBufferPoint::new(row.0, 0);
13598                if let Some((buffer, buffer_point, _)) =
13599                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13600                {
13601                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13602                    new_selections_by_buffer
13603                        .entry(buffer)
13604                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13605                        .0
13606                        .push(buffer_offset..buffer_offset)
13607                }
13608            }
13609            None => {
13610                let selections = self.selections.all::<usize>(cx);
13611                let multi_buffer = self.buffer.read(cx);
13612                for selection in selections {
13613                    for (buffer, mut range, _) in multi_buffer
13614                        .snapshot(cx)
13615                        .range_to_buffer_ranges(selection.range())
13616                    {
13617                        // When editing branch buffers, jump to the corresponding location
13618                        // in their base buffer.
13619                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13620                        let buffer = buffer_handle.read(cx);
13621                        if let Some(base_buffer) = buffer.base_buffer() {
13622                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13623                            buffer_handle = base_buffer;
13624                        }
13625
13626                        if selection.reversed {
13627                            mem::swap(&mut range.start, &mut range.end);
13628                        }
13629                        new_selections_by_buffer
13630                            .entry(buffer_handle)
13631                            .or_insert((Vec::new(), None))
13632                            .0
13633                            .push(range)
13634                    }
13635                }
13636            }
13637        }
13638
13639        if new_selections_by_buffer.is_empty() {
13640            return;
13641        }
13642
13643        // We defer the pane interaction because we ourselves are a workspace item
13644        // and activating a new item causes the pane to call a method on us reentrantly,
13645        // which panics if we're on the stack.
13646        window.defer(cx, move |window, cx| {
13647            workspace.update(cx, |workspace, cx| {
13648                let pane = if split {
13649                    workspace.adjacent_pane(window, cx)
13650                } else {
13651                    workspace.active_pane().clone()
13652                };
13653
13654                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13655                    let editor = buffer
13656                        .read(cx)
13657                        .file()
13658                        .is_none()
13659                        .then(|| {
13660                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13661                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13662                            // Instead, we try to activate the existing editor in the pane first.
13663                            let (editor, pane_item_index) =
13664                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13665                                    let editor = item.downcast::<Editor>()?;
13666                                    let singleton_buffer =
13667                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13668                                    if singleton_buffer == buffer {
13669                                        Some((editor, i))
13670                                    } else {
13671                                        None
13672                                    }
13673                                })?;
13674                            pane.update(cx, |pane, cx| {
13675                                pane.activate_item(pane_item_index, true, true, window, cx)
13676                            });
13677                            Some(editor)
13678                        })
13679                        .flatten()
13680                        .unwrap_or_else(|| {
13681                            workspace.open_project_item::<Self>(
13682                                pane.clone(),
13683                                buffer,
13684                                true,
13685                                true,
13686                                window,
13687                                cx,
13688                            )
13689                        });
13690
13691                    editor.update(cx, |editor, cx| {
13692                        let autoscroll = match scroll_offset {
13693                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13694                            None => Autoscroll::newest(),
13695                        };
13696                        let nav_history = editor.nav_history.take();
13697                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13698                            s.select_ranges(ranges);
13699                        });
13700                        editor.nav_history = nav_history;
13701                    });
13702                }
13703            })
13704        });
13705    }
13706
13707    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13708        let snapshot = self.buffer.read(cx).read(cx);
13709        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13710        Some(
13711            ranges
13712                .iter()
13713                .map(move |range| {
13714                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13715                })
13716                .collect(),
13717        )
13718    }
13719
13720    fn selection_replacement_ranges(
13721        &self,
13722        range: Range<OffsetUtf16>,
13723        cx: &mut App,
13724    ) -> Vec<Range<OffsetUtf16>> {
13725        let selections = self.selections.all::<OffsetUtf16>(cx);
13726        let newest_selection = selections
13727            .iter()
13728            .max_by_key(|selection| selection.id)
13729            .unwrap();
13730        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13731        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13732        let snapshot = self.buffer.read(cx).read(cx);
13733        selections
13734            .into_iter()
13735            .map(|mut selection| {
13736                selection.start.0 =
13737                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13738                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13739                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13740                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13741            })
13742            .collect()
13743    }
13744
13745    fn report_editor_event(
13746        &self,
13747        event_type: &'static str,
13748        file_extension: Option<String>,
13749        cx: &App,
13750    ) {
13751        if cfg!(any(test, feature = "test-support")) {
13752            return;
13753        }
13754
13755        let Some(project) = &self.project else { return };
13756
13757        // If None, we are in a file without an extension
13758        let file = self
13759            .buffer
13760            .read(cx)
13761            .as_singleton()
13762            .and_then(|b| b.read(cx).file());
13763        let file_extension = file_extension.or(file
13764            .as_ref()
13765            .and_then(|file| Path::new(file.file_name(cx)).extension())
13766            .and_then(|e| e.to_str())
13767            .map(|a| a.to_string()));
13768
13769        let vim_mode = cx
13770            .global::<SettingsStore>()
13771            .raw_user_settings()
13772            .get("vim_mode")
13773            == Some(&serde_json::Value::Bool(true));
13774
13775        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13776            == language::language_settings::InlineCompletionProvider::Copilot;
13777        let copilot_enabled_for_language = self
13778            .buffer
13779            .read(cx)
13780            .settings_at(0, cx)
13781            .show_inline_completions;
13782
13783        let project = project.read(cx);
13784        telemetry::event!(
13785            event_type,
13786            file_extension,
13787            vim_mode,
13788            copilot_enabled,
13789            copilot_enabled_for_language,
13790            is_via_ssh = project.is_via_ssh(),
13791        );
13792    }
13793
13794    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13795    /// with each line being an array of {text, highlight} objects.
13796    fn copy_highlight_json(
13797        &mut self,
13798        _: &CopyHighlightJson,
13799        window: &mut Window,
13800        cx: &mut Context<Self>,
13801    ) {
13802        #[derive(Serialize)]
13803        struct Chunk<'a> {
13804            text: String,
13805            highlight: Option<&'a str>,
13806        }
13807
13808        let snapshot = self.buffer.read(cx).snapshot(cx);
13809        let range = self
13810            .selected_text_range(false, window, cx)
13811            .and_then(|selection| {
13812                if selection.range.is_empty() {
13813                    None
13814                } else {
13815                    Some(selection.range)
13816                }
13817            })
13818            .unwrap_or_else(|| 0..snapshot.len());
13819
13820        let chunks = snapshot.chunks(range, true);
13821        let mut lines = Vec::new();
13822        let mut line: VecDeque<Chunk> = VecDeque::new();
13823
13824        let Some(style) = self.style.as_ref() else {
13825            return;
13826        };
13827
13828        for chunk in chunks {
13829            let highlight = chunk
13830                .syntax_highlight_id
13831                .and_then(|id| id.name(&style.syntax));
13832            let mut chunk_lines = chunk.text.split('\n').peekable();
13833            while let Some(text) = chunk_lines.next() {
13834                let mut merged_with_last_token = false;
13835                if let Some(last_token) = line.back_mut() {
13836                    if last_token.highlight == highlight {
13837                        last_token.text.push_str(text);
13838                        merged_with_last_token = true;
13839                    }
13840                }
13841
13842                if !merged_with_last_token {
13843                    line.push_back(Chunk {
13844                        text: text.into(),
13845                        highlight,
13846                    });
13847                }
13848
13849                if chunk_lines.peek().is_some() {
13850                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13851                        line.pop_front();
13852                    }
13853                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13854                        line.pop_back();
13855                    }
13856
13857                    lines.push(mem::take(&mut line));
13858                }
13859            }
13860        }
13861
13862        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13863            return;
13864        };
13865        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13866    }
13867
13868    pub fn open_context_menu(
13869        &mut self,
13870        _: &OpenContextMenu,
13871        window: &mut Window,
13872        cx: &mut Context<Self>,
13873    ) {
13874        self.request_autoscroll(Autoscroll::newest(), cx);
13875        let position = self.selections.newest_display(cx).start;
13876        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13877    }
13878
13879    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13880        &self.inlay_hint_cache
13881    }
13882
13883    pub fn replay_insert_event(
13884        &mut self,
13885        text: &str,
13886        relative_utf16_range: Option<Range<isize>>,
13887        window: &mut Window,
13888        cx: &mut Context<Self>,
13889    ) {
13890        if !self.input_enabled {
13891            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13892            return;
13893        }
13894        if let Some(relative_utf16_range) = relative_utf16_range {
13895            let selections = self.selections.all::<OffsetUtf16>(cx);
13896            self.change_selections(None, window, cx, |s| {
13897                let new_ranges = selections.into_iter().map(|range| {
13898                    let start = OffsetUtf16(
13899                        range
13900                            .head()
13901                            .0
13902                            .saturating_add_signed(relative_utf16_range.start),
13903                    );
13904                    let end = OffsetUtf16(
13905                        range
13906                            .head()
13907                            .0
13908                            .saturating_add_signed(relative_utf16_range.end),
13909                    );
13910                    start..end
13911                });
13912                s.select_ranges(new_ranges);
13913            });
13914        }
13915
13916        self.handle_input(text, window, cx);
13917    }
13918
13919    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
13920        let Some(provider) = self.semantics_provider.as_ref() else {
13921            return false;
13922        };
13923
13924        let mut supports = false;
13925        self.buffer().update(cx, |this, cx| {
13926            this.for_each_buffer(|buffer| {
13927                supports |= provider.supports_inlay_hints(buffer, cx);
13928            })
13929        });
13930
13931        supports
13932    }
13933    pub fn is_focused(&self, window: &mut Window) -> bool {
13934        self.focus_handle.is_focused(window)
13935    }
13936
13937    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13938        cx.emit(EditorEvent::Focused);
13939
13940        if let Some(descendant) = self
13941            .last_focused_descendant
13942            .take()
13943            .and_then(|descendant| descendant.upgrade())
13944        {
13945            window.focus(&descendant);
13946        } else {
13947            if let Some(blame) = self.blame.as_ref() {
13948                blame.update(cx, GitBlame::focus)
13949            }
13950
13951            self.blink_manager.update(cx, BlinkManager::enable);
13952            self.show_cursor_names(window, cx);
13953            self.buffer.update(cx, |buffer, cx| {
13954                buffer.finalize_last_transaction(cx);
13955                if self.leader_peer_id.is_none() {
13956                    buffer.set_active_selections(
13957                        &self.selections.disjoint_anchors(),
13958                        self.selections.line_mode,
13959                        self.cursor_shape,
13960                        cx,
13961                    );
13962                }
13963            });
13964        }
13965    }
13966
13967    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13968        cx.emit(EditorEvent::FocusedIn)
13969    }
13970
13971    fn handle_focus_out(
13972        &mut self,
13973        event: FocusOutEvent,
13974        _window: &mut Window,
13975        _cx: &mut Context<Self>,
13976    ) {
13977        if event.blurred != self.focus_handle {
13978            self.last_focused_descendant = Some(event.blurred);
13979        }
13980    }
13981
13982    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13983        self.blink_manager.update(cx, BlinkManager::disable);
13984        self.buffer
13985            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13986
13987        if let Some(blame) = self.blame.as_ref() {
13988            blame.update(cx, GitBlame::blur)
13989        }
13990        if !self.hover_state.focused(window, cx) {
13991            hide_hover(self, cx);
13992        }
13993
13994        self.hide_context_menu(window, cx);
13995        cx.emit(EditorEvent::Blurred);
13996        cx.notify();
13997    }
13998
13999    pub fn register_action<A: Action>(
14000        &mut self,
14001        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14002    ) -> Subscription {
14003        let id = self.next_editor_action_id.post_inc();
14004        let listener = Arc::new(listener);
14005        self.editor_actions.borrow_mut().insert(
14006            id,
14007            Box::new(move |window, _| {
14008                let listener = listener.clone();
14009                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14010                    let action = action.downcast_ref().unwrap();
14011                    if phase == DispatchPhase::Bubble {
14012                        listener(action, window, cx)
14013                    }
14014                })
14015            }),
14016        );
14017
14018        let editor_actions = self.editor_actions.clone();
14019        Subscription::new(move || {
14020            editor_actions.borrow_mut().remove(&id);
14021        })
14022    }
14023
14024    pub fn file_header_size(&self) -> u32 {
14025        FILE_HEADER_HEIGHT
14026    }
14027
14028    pub fn revert(
14029        &mut self,
14030        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14031        window: &mut Window,
14032        cx: &mut Context<Self>,
14033    ) {
14034        self.buffer().update(cx, |multi_buffer, cx| {
14035            for (buffer_id, changes) in revert_changes {
14036                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14037                    buffer.update(cx, |buffer, cx| {
14038                        buffer.edit(
14039                            changes.into_iter().map(|(range, text)| {
14040                                (range, text.to_string().map(Arc::<str>::from))
14041                            }),
14042                            None,
14043                            cx,
14044                        );
14045                    });
14046                }
14047            }
14048        });
14049        self.change_selections(None, window, cx, |selections| selections.refresh());
14050    }
14051
14052    pub fn to_pixel_point(
14053        &self,
14054        source: multi_buffer::Anchor,
14055        editor_snapshot: &EditorSnapshot,
14056        window: &mut Window,
14057    ) -> Option<gpui::Point<Pixels>> {
14058        let source_point = source.to_display_point(editor_snapshot);
14059        self.display_to_pixel_point(source_point, editor_snapshot, window)
14060    }
14061
14062    pub fn display_to_pixel_point(
14063        &self,
14064        source: DisplayPoint,
14065        editor_snapshot: &EditorSnapshot,
14066        window: &mut Window,
14067    ) -> Option<gpui::Point<Pixels>> {
14068        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14069        let text_layout_details = self.text_layout_details(window);
14070        let scroll_top = text_layout_details
14071            .scroll_anchor
14072            .scroll_position(editor_snapshot)
14073            .y;
14074
14075        if source.row().as_f32() < scroll_top.floor() {
14076            return None;
14077        }
14078        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14079        let source_y = line_height * (source.row().as_f32() - scroll_top);
14080        Some(gpui::Point::new(source_x, source_y))
14081    }
14082
14083    pub fn has_active_completions_menu(&self) -> bool {
14084        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14085            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14086        })
14087    }
14088
14089    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14090        self.addons
14091            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14092    }
14093
14094    pub fn unregister_addon<T: Addon>(&mut self) {
14095        self.addons.remove(&std::any::TypeId::of::<T>());
14096    }
14097
14098    pub fn addon<T: Addon>(&self) -> Option<&T> {
14099        let type_id = std::any::TypeId::of::<T>();
14100        self.addons
14101            .get(&type_id)
14102            .and_then(|item| item.to_any().downcast_ref::<T>())
14103    }
14104
14105    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14106        let text_layout_details = self.text_layout_details(window);
14107        let style = &text_layout_details.editor_style;
14108        let font_id = window.text_system().resolve_font(&style.text.font());
14109        let font_size = style.text.font_size.to_pixels(window.rem_size());
14110        let line_height = style.text.line_height_in_pixels(window.rem_size());
14111
14112        let em_width = window
14113            .text_system()
14114            .typographic_bounds(font_id, font_size, 'm')
14115            .unwrap()
14116            .size
14117            .width;
14118
14119        gpui::Point::new(em_width, line_height)
14120    }
14121}
14122
14123fn get_unstaged_changes_for_buffers(
14124    project: &Entity<Project>,
14125    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14126    buffer: Entity<MultiBuffer>,
14127    cx: &mut App,
14128) {
14129    let mut tasks = Vec::new();
14130    project.update(cx, |project, cx| {
14131        for buffer in buffers {
14132            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14133        }
14134    });
14135    cx.spawn(|mut cx| async move {
14136        let change_sets = futures::future::join_all(tasks).await;
14137        buffer
14138            .update(&mut cx, |buffer, cx| {
14139                for change_set in change_sets {
14140                    if let Some(change_set) = change_set.log_err() {
14141                        buffer.add_change_set(change_set, cx);
14142                    }
14143                }
14144            })
14145            .ok();
14146    })
14147    .detach();
14148}
14149
14150fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14151    let tab_size = tab_size.get() as usize;
14152    let mut width = offset;
14153
14154    for ch in text.chars() {
14155        width += if ch == '\t' {
14156            tab_size - (width % tab_size)
14157        } else {
14158            1
14159        };
14160    }
14161
14162    width - offset
14163}
14164
14165#[cfg(test)]
14166mod tests {
14167    use super::*;
14168
14169    #[test]
14170    fn test_string_size_with_expanded_tabs() {
14171        let nz = |val| NonZeroU32::new(val).unwrap();
14172        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14173        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14174        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14175        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14176        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14177        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14178        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14179        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14180    }
14181}
14182
14183/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14184struct WordBreakingTokenizer<'a> {
14185    input: &'a str,
14186}
14187
14188impl<'a> WordBreakingTokenizer<'a> {
14189    fn new(input: &'a str) -> Self {
14190        Self { input }
14191    }
14192}
14193
14194fn is_char_ideographic(ch: char) -> bool {
14195    use unicode_script::Script::*;
14196    use unicode_script::UnicodeScript;
14197    matches!(ch.script(), Han | Tangut | Yi)
14198}
14199
14200fn is_grapheme_ideographic(text: &str) -> bool {
14201    text.chars().any(is_char_ideographic)
14202}
14203
14204fn is_grapheme_whitespace(text: &str) -> bool {
14205    text.chars().any(|x| x.is_whitespace())
14206}
14207
14208fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14209    text.chars().next().map_or(false, |ch| {
14210        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14211    })
14212}
14213
14214#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14215struct WordBreakToken<'a> {
14216    token: &'a str,
14217    grapheme_len: usize,
14218    is_whitespace: bool,
14219}
14220
14221impl<'a> Iterator for WordBreakingTokenizer<'a> {
14222    /// Yields a span, the count of graphemes in the token, and whether it was
14223    /// whitespace. Note that it also breaks at word boundaries.
14224    type Item = WordBreakToken<'a>;
14225
14226    fn next(&mut self) -> Option<Self::Item> {
14227        use unicode_segmentation::UnicodeSegmentation;
14228        if self.input.is_empty() {
14229            return None;
14230        }
14231
14232        let mut iter = self.input.graphemes(true).peekable();
14233        let mut offset = 0;
14234        let mut graphemes = 0;
14235        if let Some(first_grapheme) = iter.next() {
14236            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14237            offset += first_grapheme.len();
14238            graphemes += 1;
14239            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14240                if let Some(grapheme) = iter.peek().copied() {
14241                    if should_stay_with_preceding_ideograph(grapheme) {
14242                        offset += grapheme.len();
14243                        graphemes += 1;
14244                    }
14245                }
14246            } else {
14247                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14248                let mut next_word_bound = words.peek().copied();
14249                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14250                    next_word_bound = words.next();
14251                }
14252                while let Some(grapheme) = iter.peek().copied() {
14253                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14254                        break;
14255                    };
14256                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14257                        break;
14258                    };
14259                    offset += grapheme.len();
14260                    graphemes += 1;
14261                    iter.next();
14262                }
14263            }
14264            let token = &self.input[..offset];
14265            self.input = &self.input[offset..];
14266            if is_whitespace {
14267                Some(WordBreakToken {
14268                    token: " ",
14269                    grapheme_len: 1,
14270                    is_whitespace: true,
14271                })
14272            } else {
14273                Some(WordBreakToken {
14274                    token,
14275                    grapheme_len: graphemes,
14276                    is_whitespace: false,
14277                })
14278            }
14279        } else {
14280            None
14281        }
14282    }
14283}
14284
14285#[test]
14286fn test_word_breaking_tokenizer() {
14287    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14288        ("", &[]),
14289        ("  ", &[(" ", 1, true)]),
14290        ("Ʒ", &[("Ʒ", 1, false)]),
14291        ("Ǽ", &[("Ǽ", 1, false)]),
14292        ("", &[("", 1, false)]),
14293        ("⋑⋑", &[("⋑⋑", 2, false)]),
14294        (
14295            "原理,进而",
14296            &[
14297                ("", 1, false),
14298                ("理,", 2, false),
14299                ("", 1, false),
14300                ("", 1, false),
14301            ],
14302        ),
14303        (
14304            "hello world",
14305            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14306        ),
14307        (
14308            "hello, world",
14309            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14310        ),
14311        (
14312            "  hello world",
14313            &[
14314                (" ", 1, true),
14315                ("hello", 5, false),
14316                (" ", 1, true),
14317                ("world", 5, false),
14318            ],
14319        ),
14320        (
14321            "这是什么 \n 钢笔",
14322            &[
14323                ("", 1, false),
14324                ("", 1, false),
14325                ("", 1, false),
14326                ("", 1, false),
14327                (" ", 1, true),
14328                ("", 1, false),
14329                ("", 1, false),
14330            ],
14331        ),
14332        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14333    ];
14334
14335    for (input, result) in tests {
14336        assert_eq!(
14337            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14338            result
14339                .iter()
14340                .copied()
14341                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14342                    token,
14343                    grapheme_len,
14344                    is_whitespace,
14345                })
14346                .collect::<Vec<_>>()
14347        );
14348    }
14349}
14350
14351fn wrap_with_prefix(
14352    line_prefix: String,
14353    unwrapped_text: String,
14354    wrap_column: usize,
14355    tab_size: NonZeroU32,
14356) -> String {
14357    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14358    let mut wrapped_text = String::new();
14359    let mut current_line = line_prefix.clone();
14360
14361    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14362    let mut current_line_len = line_prefix_len;
14363    for WordBreakToken {
14364        token,
14365        grapheme_len,
14366        is_whitespace,
14367    } in tokenizer
14368    {
14369        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14370            wrapped_text.push_str(current_line.trim_end());
14371            wrapped_text.push('\n');
14372            current_line.truncate(line_prefix.len());
14373            current_line_len = line_prefix_len;
14374            if !is_whitespace {
14375                current_line.push_str(token);
14376                current_line_len += grapheme_len;
14377            }
14378        } else if !is_whitespace {
14379            current_line.push_str(token);
14380            current_line_len += grapheme_len;
14381        } else if current_line_len != line_prefix_len {
14382            current_line.push(' ');
14383            current_line_len += 1;
14384        }
14385    }
14386
14387    if !current_line.is_empty() {
14388        wrapped_text.push_str(&current_line);
14389    }
14390    wrapped_text
14391}
14392
14393#[test]
14394fn test_wrap_with_prefix() {
14395    assert_eq!(
14396        wrap_with_prefix(
14397            "# ".to_string(),
14398            "abcdefg".to_string(),
14399            4,
14400            NonZeroU32::new(4).unwrap()
14401        ),
14402        "# abcdefg"
14403    );
14404    assert_eq!(
14405        wrap_with_prefix(
14406            "".to_string(),
14407            "\thello world".to_string(),
14408            8,
14409            NonZeroU32::new(4).unwrap()
14410        ),
14411        "hello\nworld"
14412    );
14413    assert_eq!(
14414        wrap_with_prefix(
14415            "// ".to_string(),
14416            "xx \nyy zz aa bb cc".to_string(),
14417            12,
14418            NonZeroU32::new(4).unwrap()
14419        ),
14420        "// xx yy zz\n// aa bb cc"
14421    );
14422    assert_eq!(
14423        wrap_with_prefix(
14424            String::new(),
14425            "这是什么 \n 钢笔".to_string(),
14426            3,
14427            NonZeroU32::new(4).unwrap()
14428        ),
14429        "这是什\n么 钢\n"
14430    );
14431}
14432
14433pub trait CollaborationHub {
14434    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14435    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14436    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14437}
14438
14439impl CollaborationHub for Entity<Project> {
14440    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14441        self.read(cx).collaborators()
14442    }
14443
14444    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14445        self.read(cx).user_store().read(cx).participant_indices()
14446    }
14447
14448    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14449        let this = self.read(cx);
14450        let user_ids = this.collaborators().values().map(|c| c.user_id);
14451        this.user_store().read_with(cx, |user_store, cx| {
14452            user_store.participant_names(user_ids, cx)
14453        })
14454    }
14455}
14456
14457pub trait SemanticsProvider {
14458    fn hover(
14459        &self,
14460        buffer: &Entity<Buffer>,
14461        position: text::Anchor,
14462        cx: &mut App,
14463    ) -> Option<Task<Vec<project::Hover>>>;
14464
14465    fn inlay_hints(
14466        &self,
14467        buffer_handle: Entity<Buffer>,
14468        range: Range<text::Anchor>,
14469        cx: &mut App,
14470    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14471
14472    fn resolve_inlay_hint(
14473        &self,
14474        hint: InlayHint,
14475        buffer_handle: Entity<Buffer>,
14476        server_id: LanguageServerId,
14477        cx: &mut App,
14478    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14479
14480    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
14481
14482    fn document_highlights(
14483        &self,
14484        buffer: &Entity<Buffer>,
14485        position: text::Anchor,
14486        cx: &mut App,
14487    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14488
14489    fn definitions(
14490        &self,
14491        buffer: &Entity<Buffer>,
14492        position: text::Anchor,
14493        kind: GotoDefinitionKind,
14494        cx: &mut App,
14495    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14496
14497    fn range_for_rename(
14498        &self,
14499        buffer: &Entity<Buffer>,
14500        position: text::Anchor,
14501        cx: &mut App,
14502    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14503
14504    fn perform_rename(
14505        &self,
14506        buffer: &Entity<Buffer>,
14507        position: text::Anchor,
14508        new_name: String,
14509        cx: &mut App,
14510    ) -> Option<Task<Result<ProjectTransaction>>>;
14511}
14512
14513pub trait CompletionProvider {
14514    fn completions(
14515        &self,
14516        buffer: &Entity<Buffer>,
14517        buffer_position: text::Anchor,
14518        trigger: CompletionContext,
14519        window: &mut Window,
14520        cx: &mut Context<Editor>,
14521    ) -> Task<Result<Vec<Completion>>>;
14522
14523    fn resolve_completions(
14524        &self,
14525        buffer: Entity<Buffer>,
14526        completion_indices: Vec<usize>,
14527        completions: Rc<RefCell<Box<[Completion]>>>,
14528        cx: &mut Context<Editor>,
14529    ) -> Task<Result<bool>>;
14530
14531    fn apply_additional_edits_for_completion(
14532        &self,
14533        _buffer: Entity<Buffer>,
14534        _completions: Rc<RefCell<Box<[Completion]>>>,
14535        _completion_index: usize,
14536        _push_to_history: bool,
14537        _cx: &mut Context<Editor>,
14538    ) -> Task<Result<Option<language::Transaction>>> {
14539        Task::ready(Ok(None))
14540    }
14541
14542    fn is_completion_trigger(
14543        &self,
14544        buffer: &Entity<Buffer>,
14545        position: language::Anchor,
14546        text: &str,
14547        trigger_in_words: bool,
14548        cx: &mut Context<Editor>,
14549    ) -> bool;
14550
14551    fn sort_completions(&self) -> bool {
14552        true
14553    }
14554}
14555
14556pub trait CodeActionProvider {
14557    fn id(&self) -> Arc<str>;
14558
14559    fn code_actions(
14560        &self,
14561        buffer: &Entity<Buffer>,
14562        range: Range<text::Anchor>,
14563        window: &mut Window,
14564        cx: &mut App,
14565    ) -> Task<Result<Vec<CodeAction>>>;
14566
14567    fn apply_code_action(
14568        &self,
14569        buffer_handle: Entity<Buffer>,
14570        action: CodeAction,
14571        excerpt_id: ExcerptId,
14572        push_to_history: bool,
14573        window: &mut Window,
14574        cx: &mut App,
14575    ) -> Task<Result<ProjectTransaction>>;
14576}
14577
14578impl CodeActionProvider for Entity<Project> {
14579    fn id(&self) -> Arc<str> {
14580        "project".into()
14581    }
14582
14583    fn code_actions(
14584        &self,
14585        buffer: &Entity<Buffer>,
14586        range: Range<text::Anchor>,
14587        _window: &mut Window,
14588        cx: &mut App,
14589    ) -> Task<Result<Vec<CodeAction>>> {
14590        self.update(cx, |project, cx| {
14591            project.code_actions(buffer, range, None, cx)
14592        })
14593    }
14594
14595    fn apply_code_action(
14596        &self,
14597        buffer_handle: Entity<Buffer>,
14598        action: CodeAction,
14599        _excerpt_id: ExcerptId,
14600        push_to_history: bool,
14601        _window: &mut Window,
14602        cx: &mut App,
14603    ) -> Task<Result<ProjectTransaction>> {
14604        self.update(cx, |project, cx| {
14605            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14606        })
14607    }
14608}
14609
14610fn snippet_completions(
14611    project: &Project,
14612    buffer: &Entity<Buffer>,
14613    buffer_position: text::Anchor,
14614    cx: &mut App,
14615) -> Task<Result<Vec<Completion>>> {
14616    let language = buffer.read(cx).language_at(buffer_position);
14617    let language_name = language.as_ref().map(|language| language.lsp_id());
14618    let snippet_store = project.snippets().read(cx);
14619    let snippets = snippet_store.snippets_for(language_name, cx);
14620
14621    if snippets.is_empty() {
14622        return Task::ready(Ok(vec![]));
14623    }
14624    let snapshot = buffer.read(cx).text_snapshot();
14625    let chars: String = snapshot
14626        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14627        .collect();
14628
14629    let scope = language.map(|language| language.default_scope());
14630    let executor = cx.background_executor().clone();
14631
14632    cx.background_executor().spawn(async move {
14633        let classifier = CharClassifier::new(scope).for_completion(true);
14634        let mut last_word = chars
14635            .chars()
14636            .take_while(|c| classifier.is_word(*c))
14637            .collect::<String>();
14638        last_word = last_word.chars().rev().collect();
14639
14640        if last_word.is_empty() {
14641            return Ok(vec![]);
14642        }
14643
14644        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14645        let to_lsp = |point: &text::Anchor| {
14646            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14647            point_to_lsp(end)
14648        };
14649        let lsp_end = to_lsp(&buffer_position);
14650
14651        let candidates = snippets
14652            .iter()
14653            .enumerate()
14654            .flat_map(|(ix, snippet)| {
14655                snippet
14656                    .prefix
14657                    .iter()
14658                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14659            })
14660            .collect::<Vec<StringMatchCandidate>>();
14661
14662        let mut matches = fuzzy::match_strings(
14663            &candidates,
14664            &last_word,
14665            last_word.chars().any(|c| c.is_uppercase()),
14666            100,
14667            &Default::default(),
14668            executor,
14669        )
14670        .await;
14671
14672        // Remove all candidates where the query's start does not match the start of any word in the candidate
14673        if let Some(query_start) = last_word.chars().next() {
14674            matches.retain(|string_match| {
14675                split_words(&string_match.string).any(|word| {
14676                    // Check that the first codepoint of the word as lowercase matches the first
14677                    // codepoint of the query as lowercase
14678                    word.chars()
14679                        .flat_map(|codepoint| codepoint.to_lowercase())
14680                        .zip(query_start.to_lowercase())
14681                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14682                })
14683            });
14684        }
14685
14686        let matched_strings = matches
14687            .into_iter()
14688            .map(|m| m.string)
14689            .collect::<HashSet<_>>();
14690
14691        let result: Vec<Completion> = snippets
14692            .into_iter()
14693            .filter_map(|snippet| {
14694                let matching_prefix = snippet
14695                    .prefix
14696                    .iter()
14697                    .find(|prefix| matched_strings.contains(*prefix))?;
14698                let start = as_offset - last_word.len();
14699                let start = snapshot.anchor_before(start);
14700                let range = start..buffer_position;
14701                let lsp_start = to_lsp(&start);
14702                let lsp_range = lsp::Range {
14703                    start: lsp_start,
14704                    end: lsp_end,
14705                };
14706                Some(Completion {
14707                    old_range: range,
14708                    new_text: snippet.body.clone(),
14709                    resolved: false,
14710                    label: CodeLabel {
14711                        text: matching_prefix.clone(),
14712                        runs: vec![],
14713                        filter_range: 0..matching_prefix.len(),
14714                    },
14715                    server_id: LanguageServerId(usize::MAX),
14716                    documentation: snippet.description.clone().map(Documentation::SingleLine),
14717                    lsp_completion: lsp::CompletionItem {
14718                        label: snippet.prefix.first().unwrap().clone(),
14719                        kind: Some(CompletionItemKind::SNIPPET),
14720                        label_details: snippet.description.as_ref().map(|description| {
14721                            lsp::CompletionItemLabelDetails {
14722                                detail: Some(description.clone()),
14723                                description: None,
14724                            }
14725                        }),
14726                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14727                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14728                            lsp::InsertReplaceEdit {
14729                                new_text: snippet.body.clone(),
14730                                insert: lsp_range,
14731                                replace: lsp_range,
14732                            },
14733                        )),
14734                        filter_text: Some(snippet.body.clone()),
14735                        sort_text: Some(char::MAX.to_string()),
14736                        ..Default::default()
14737                    },
14738                    confirm: None,
14739                })
14740            })
14741            .collect();
14742
14743        Ok(result)
14744    })
14745}
14746
14747impl CompletionProvider for Entity<Project> {
14748    fn completions(
14749        &self,
14750        buffer: &Entity<Buffer>,
14751        buffer_position: text::Anchor,
14752        options: CompletionContext,
14753        _window: &mut Window,
14754        cx: &mut Context<Editor>,
14755    ) -> Task<Result<Vec<Completion>>> {
14756        self.update(cx, |project, cx| {
14757            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14758            let project_completions = project.completions(buffer, buffer_position, options, cx);
14759            cx.background_executor().spawn(async move {
14760                let mut completions = project_completions.await?;
14761                let snippets_completions = snippets.await?;
14762                completions.extend(snippets_completions);
14763                Ok(completions)
14764            })
14765        })
14766    }
14767
14768    fn resolve_completions(
14769        &self,
14770        buffer: Entity<Buffer>,
14771        completion_indices: Vec<usize>,
14772        completions: Rc<RefCell<Box<[Completion]>>>,
14773        cx: &mut Context<Editor>,
14774    ) -> Task<Result<bool>> {
14775        self.update(cx, |project, cx| {
14776            project.lsp_store().update(cx, |lsp_store, cx| {
14777                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14778            })
14779        })
14780    }
14781
14782    fn apply_additional_edits_for_completion(
14783        &self,
14784        buffer: Entity<Buffer>,
14785        completions: Rc<RefCell<Box<[Completion]>>>,
14786        completion_index: usize,
14787        push_to_history: bool,
14788        cx: &mut Context<Editor>,
14789    ) -> Task<Result<Option<language::Transaction>>> {
14790        self.update(cx, |project, cx| {
14791            project.lsp_store().update(cx, |lsp_store, cx| {
14792                lsp_store.apply_additional_edits_for_completion(
14793                    buffer,
14794                    completions,
14795                    completion_index,
14796                    push_to_history,
14797                    cx,
14798                )
14799            })
14800        })
14801    }
14802
14803    fn is_completion_trigger(
14804        &self,
14805        buffer: &Entity<Buffer>,
14806        position: language::Anchor,
14807        text: &str,
14808        trigger_in_words: bool,
14809        cx: &mut Context<Editor>,
14810    ) -> bool {
14811        let mut chars = text.chars();
14812        let char = if let Some(char) = chars.next() {
14813            char
14814        } else {
14815            return false;
14816        };
14817        if chars.next().is_some() {
14818            return false;
14819        }
14820
14821        let buffer = buffer.read(cx);
14822        let snapshot = buffer.snapshot();
14823        if !snapshot.settings_at(position, cx).show_completions_on_input {
14824            return false;
14825        }
14826        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14827        if trigger_in_words && classifier.is_word(char) {
14828            return true;
14829        }
14830
14831        buffer.completion_triggers().contains(text)
14832    }
14833}
14834
14835impl SemanticsProvider for Entity<Project> {
14836    fn hover(
14837        &self,
14838        buffer: &Entity<Buffer>,
14839        position: text::Anchor,
14840        cx: &mut App,
14841    ) -> Option<Task<Vec<project::Hover>>> {
14842        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14843    }
14844
14845    fn document_highlights(
14846        &self,
14847        buffer: &Entity<Buffer>,
14848        position: text::Anchor,
14849        cx: &mut App,
14850    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14851        Some(self.update(cx, |project, cx| {
14852            project.document_highlights(buffer, position, cx)
14853        }))
14854    }
14855
14856    fn definitions(
14857        &self,
14858        buffer: &Entity<Buffer>,
14859        position: text::Anchor,
14860        kind: GotoDefinitionKind,
14861        cx: &mut App,
14862    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14863        Some(self.update(cx, |project, cx| match kind {
14864            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14865            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14866            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14867            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14868        }))
14869    }
14870
14871    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
14872        // TODO: make this work for remote projects
14873        buffer.update(cx, |buffer, cx| {
14874            self.update(cx, |this, cx| {
14875                this.for_language_servers_for_local_buffer(
14876                    buffer,
14877                    |mut it| {
14878                        it.any(
14879                            |(_, server)| match server.capabilities().inlay_hint_provider {
14880                                Some(lsp::OneOf::Left(enabled)) => enabled,
14881                                Some(lsp::OneOf::Right(_)) => true,
14882                                None => false,
14883                            },
14884                        )
14885                    },
14886                    cx,
14887                )
14888            })
14889        })
14890    }
14891
14892    fn inlay_hints(
14893        &self,
14894        buffer_handle: Entity<Buffer>,
14895        range: Range<text::Anchor>,
14896        cx: &mut App,
14897    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14898        Some(self.update(cx, |project, cx| {
14899            project.inlay_hints(buffer_handle, range, cx)
14900        }))
14901    }
14902
14903    fn resolve_inlay_hint(
14904        &self,
14905        hint: InlayHint,
14906        buffer_handle: Entity<Buffer>,
14907        server_id: LanguageServerId,
14908        cx: &mut App,
14909    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14910        Some(self.update(cx, |project, cx| {
14911            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14912        }))
14913    }
14914
14915    fn range_for_rename(
14916        &self,
14917        buffer: &Entity<Buffer>,
14918        position: text::Anchor,
14919        cx: &mut App,
14920    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14921        Some(self.update(cx, |project, cx| {
14922            let buffer = buffer.clone();
14923            let task = project.prepare_rename(buffer.clone(), position, cx);
14924            cx.spawn(|_, mut cx| async move {
14925                Ok(match task.await? {
14926                    PrepareRenameResponse::Success(range) => Some(range),
14927                    PrepareRenameResponse::InvalidPosition => None,
14928                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14929                        // Fallback on using TreeSitter info to determine identifier range
14930                        buffer.update(&mut cx, |buffer, _| {
14931                            let snapshot = buffer.snapshot();
14932                            let (range, kind) = snapshot.surrounding_word(position);
14933                            if kind != Some(CharKind::Word) {
14934                                return None;
14935                            }
14936                            Some(
14937                                snapshot.anchor_before(range.start)
14938                                    ..snapshot.anchor_after(range.end),
14939                            )
14940                        })?
14941                    }
14942                })
14943            })
14944        }))
14945    }
14946
14947    fn perform_rename(
14948        &self,
14949        buffer: &Entity<Buffer>,
14950        position: text::Anchor,
14951        new_name: String,
14952        cx: &mut App,
14953    ) -> Option<Task<Result<ProjectTransaction>>> {
14954        Some(self.update(cx, |project, cx| {
14955            project.perform_rename(buffer.clone(), position, new_name, cx)
14956        }))
14957    }
14958}
14959
14960fn inlay_hint_settings(
14961    location: Anchor,
14962    snapshot: &MultiBufferSnapshot,
14963    cx: &mut Context<Editor>,
14964) -> InlayHintSettings {
14965    let file = snapshot.file_at(location);
14966    let language = snapshot.language_at(location).map(|l| l.name());
14967    language_settings(language, file, cx).inlay_hints
14968}
14969
14970fn consume_contiguous_rows(
14971    contiguous_row_selections: &mut Vec<Selection<Point>>,
14972    selection: &Selection<Point>,
14973    display_map: &DisplaySnapshot,
14974    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14975) -> (MultiBufferRow, MultiBufferRow) {
14976    contiguous_row_selections.push(selection.clone());
14977    let start_row = MultiBufferRow(selection.start.row);
14978    let mut end_row = ending_row(selection, display_map);
14979
14980    while let Some(next_selection) = selections.peek() {
14981        if next_selection.start.row <= end_row.0 {
14982            end_row = ending_row(next_selection, display_map);
14983            contiguous_row_selections.push(selections.next().unwrap().clone());
14984        } else {
14985            break;
14986        }
14987    }
14988    (start_row, end_row)
14989}
14990
14991fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14992    if next_selection.end.column > 0 || next_selection.is_empty() {
14993        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14994    } else {
14995        MultiBufferRow(next_selection.end.row)
14996    }
14997}
14998
14999impl EditorSnapshot {
15000    pub fn remote_selections_in_range<'a>(
15001        &'a self,
15002        range: &'a Range<Anchor>,
15003        collaboration_hub: &dyn CollaborationHub,
15004        cx: &'a App,
15005    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15006        let participant_names = collaboration_hub.user_names(cx);
15007        let participant_indices = collaboration_hub.user_participant_indices(cx);
15008        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15009        let collaborators_by_replica_id = collaborators_by_peer_id
15010            .iter()
15011            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15012            .collect::<HashMap<_, _>>();
15013        self.buffer_snapshot
15014            .selections_in_range(range, false)
15015            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15016                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15017                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15018                let user_name = participant_names.get(&collaborator.user_id).cloned();
15019                Some(RemoteSelection {
15020                    replica_id,
15021                    selection,
15022                    cursor_shape,
15023                    line_mode,
15024                    participant_index,
15025                    peer_id: collaborator.peer_id,
15026                    user_name,
15027                })
15028            })
15029    }
15030
15031    pub fn hunks_for_ranges(
15032        &self,
15033        ranges: impl Iterator<Item = Range<Point>>,
15034    ) -> Vec<MultiBufferDiffHunk> {
15035        let mut hunks = Vec::new();
15036        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15037            HashMap::default();
15038        for query_range in ranges {
15039            let query_rows =
15040                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15041            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15042                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15043            ) {
15044                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15045                // when the caret is just above or just below the deleted hunk.
15046                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15047                let related_to_selection = if allow_adjacent {
15048                    hunk.row_range.overlaps(&query_rows)
15049                        || hunk.row_range.start == query_rows.end
15050                        || hunk.row_range.end == query_rows.start
15051                } else {
15052                    hunk.row_range.overlaps(&query_rows)
15053                };
15054                if related_to_selection {
15055                    if !processed_buffer_rows
15056                        .entry(hunk.buffer_id)
15057                        .or_default()
15058                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15059                    {
15060                        continue;
15061                    }
15062                    hunks.push(hunk);
15063                }
15064            }
15065        }
15066
15067        hunks
15068    }
15069
15070    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15071        self.display_snapshot.buffer_snapshot.language_at(position)
15072    }
15073
15074    pub fn is_focused(&self) -> bool {
15075        self.is_focused
15076    }
15077
15078    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15079        self.placeholder_text.as_ref()
15080    }
15081
15082    pub fn scroll_position(&self) -> gpui::Point<f32> {
15083        self.scroll_anchor.scroll_position(&self.display_snapshot)
15084    }
15085
15086    fn gutter_dimensions(
15087        &self,
15088        font_id: FontId,
15089        font_size: Pixels,
15090        em_width: Pixels,
15091        em_advance: Pixels,
15092        max_line_number_width: Pixels,
15093        cx: &App,
15094    ) -> GutterDimensions {
15095        if !self.show_gutter {
15096            return GutterDimensions::default();
15097        }
15098        let descent = cx.text_system().descent(font_id, font_size);
15099
15100        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15101            matches!(
15102                ProjectSettings::get_global(cx).git.git_gutter,
15103                Some(GitGutterSetting::TrackedFiles)
15104            )
15105        });
15106        let gutter_settings = EditorSettings::get_global(cx).gutter;
15107        let show_line_numbers = self
15108            .show_line_numbers
15109            .unwrap_or(gutter_settings.line_numbers);
15110        let line_gutter_width = if show_line_numbers {
15111            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15112            let min_width_for_number_on_gutter = em_advance * 4.0;
15113            max_line_number_width.max(min_width_for_number_on_gutter)
15114        } else {
15115            0.0.into()
15116        };
15117
15118        let show_code_actions = self
15119            .show_code_actions
15120            .unwrap_or(gutter_settings.code_actions);
15121
15122        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15123
15124        let git_blame_entries_width =
15125            self.git_blame_gutter_max_author_length
15126                .map(|max_author_length| {
15127                    // Length of the author name, but also space for the commit hash,
15128                    // the spacing and the timestamp.
15129                    let max_char_count = max_author_length
15130                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15131                        + 7 // length of commit sha
15132                        + 14 // length of max relative timestamp ("60 minutes ago")
15133                        + 4; // gaps and margins
15134
15135                    em_advance * max_char_count
15136                });
15137
15138        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15139        left_padding += if show_code_actions || show_runnables {
15140            em_width * 3.0
15141        } else if show_git_gutter && show_line_numbers {
15142            em_width * 2.0
15143        } else if show_git_gutter || show_line_numbers {
15144            em_width
15145        } else {
15146            px(0.)
15147        };
15148
15149        let right_padding = if gutter_settings.folds && show_line_numbers {
15150            em_width * 4.0
15151        } else if gutter_settings.folds {
15152            em_width * 3.0
15153        } else if show_line_numbers {
15154            em_width
15155        } else {
15156            px(0.)
15157        };
15158
15159        GutterDimensions {
15160            left_padding,
15161            right_padding,
15162            width: line_gutter_width + left_padding + right_padding,
15163            margin: -descent,
15164            git_blame_entries_width,
15165        }
15166    }
15167
15168    pub fn render_crease_toggle(
15169        &self,
15170        buffer_row: MultiBufferRow,
15171        row_contains_cursor: bool,
15172        editor: Entity<Editor>,
15173        window: &mut Window,
15174        cx: &mut App,
15175    ) -> Option<AnyElement> {
15176        let folded = self.is_line_folded(buffer_row);
15177        let mut is_foldable = false;
15178
15179        if let Some(crease) = self
15180            .crease_snapshot
15181            .query_row(buffer_row, &self.buffer_snapshot)
15182        {
15183            is_foldable = true;
15184            match crease {
15185                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15186                    if let Some(render_toggle) = render_toggle {
15187                        let toggle_callback =
15188                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15189                                if folded {
15190                                    editor.update(cx, |editor, cx| {
15191                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15192                                    });
15193                                } else {
15194                                    editor.update(cx, |editor, cx| {
15195                                        editor.unfold_at(
15196                                            &crate::UnfoldAt { buffer_row },
15197                                            window,
15198                                            cx,
15199                                        )
15200                                    });
15201                                }
15202                            });
15203                        return Some((render_toggle)(
15204                            buffer_row,
15205                            folded,
15206                            toggle_callback,
15207                            window,
15208                            cx,
15209                        ));
15210                    }
15211                }
15212            }
15213        }
15214
15215        is_foldable |= self.starts_indent(buffer_row);
15216
15217        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15218            Some(
15219                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15220                    .toggle_state(folded)
15221                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15222                        if folded {
15223                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15224                        } else {
15225                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15226                        }
15227                    }))
15228                    .into_any_element(),
15229            )
15230        } else {
15231            None
15232        }
15233    }
15234
15235    pub fn render_crease_trailer(
15236        &self,
15237        buffer_row: MultiBufferRow,
15238        window: &mut Window,
15239        cx: &mut App,
15240    ) -> Option<AnyElement> {
15241        let folded = self.is_line_folded(buffer_row);
15242        if let Crease::Inline { render_trailer, .. } = self
15243            .crease_snapshot
15244            .query_row(buffer_row, &self.buffer_snapshot)?
15245        {
15246            let render_trailer = render_trailer.as_ref()?;
15247            Some(render_trailer(buffer_row, folded, window, cx))
15248        } else {
15249            None
15250        }
15251    }
15252}
15253
15254impl Deref for EditorSnapshot {
15255    type Target = DisplaySnapshot;
15256
15257    fn deref(&self) -> &Self::Target {
15258        &self.display_snapshot
15259    }
15260}
15261
15262#[derive(Clone, Debug, PartialEq, Eq)]
15263pub enum EditorEvent {
15264    InputIgnored {
15265        text: Arc<str>,
15266    },
15267    InputHandled {
15268        utf16_range_to_replace: Option<Range<isize>>,
15269        text: Arc<str>,
15270    },
15271    ExcerptsAdded {
15272        buffer: Entity<Buffer>,
15273        predecessor: ExcerptId,
15274        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15275    },
15276    ExcerptsRemoved {
15277        ids: Vec<ExcerptId>,
15278    },
15279    BufferFoldToggled {
15280        ids: Vec<ExcerptId>,
15281        folded: bool,
15282    },
15283    ExcerptsEdited {
15284        ids: Vec<ExcerptId>,
15285    },
15286    ExcerptsExpanded {
15287        ids: Vec<ExcerptId>,
15288    },
15289    BufferEdited,
15290    Edited {
15291        transaction_id: clock::Lamport,
15292    },
15293    Reparsed(BufferId),
15294    Focused,
15295    FocusedIn,
15296    Blurred,
15297    DirtyChanged,
15298    Saved,
15299    TitleChanged,
15300    DiffBaseChanged,
15301    SelectionsChanged {
15302        local: bool,
15303    },
15304    ScrollPositionChanged {
15305        local: bool,
15306        autoscroll: bool,
15307    },
15308    Closed,
15309    TransactionUndone {
15310        transaction_id: clock::Lamport,
15311    },
15312    TransactionBegun {
15313        transaction_id: clock::Lamport,
15314    },
15315    Reloaded,
15316    CursorShapeChanged,
15317}
15318
15319impl EventEmitter<EditorEvent> for Editor {}
15320
15321impl Focusable for Editor {
15322    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15323        self.focus_handle.clone()
15324    }
15325}
15326
15327impl Render for Editor {
15328    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15329        let settings = ThemeSettings::get_global(cx);
15330
15331        let mut text_style = match self.mode {
15332            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15333                color: cx.theme().colors().editor_foreground,
15334                font_family: settings.ui_font.family.clone(),
15335                font_features: settings.ui_font.features.clone(),
15336                font_fallbacks: settings.ui_font.fallbacks.clone(),
15337                font_size: rems(0.875).into(),
15338                font_weight: settings.ui_font.weight,
15339                line_height: relative(settings.buffer_line_height.value()),
15340                ..Default::default()
15341            },
15342            EditorMode::Full => TextStyle {
15343                color: cx.theme().colors().editor_foreground,
15344                font_family: settings.buffer_font.family.clone(),
15345                font_features: settings.buffer_font.features.clone(),
15346                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15347                font_size: settings.buffer_font_size().into(),
15348                font_weight: settings.buffer_font.weight,
15349                line_height: relative(settings.buffer_line_height.value()),
15350                ..Default::default()
15351            },
15352        };
15353        if let Some(text_style_refinement) = &self.text_style_refinement {
15354            text_style.refine(text_style_refinement)
15355        }
15356
15357        let background = match self.mode {
15358            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15359            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15360            EditorMode::Full => cx.theme().colors().editor_background,
15361        };
15362
15363        EditorElement::new(
15364            &cx.entity(),
15365            EditorStyle {
15366                background,
15367                local_player: cx.theme().players().local(),
15368                text: text_style,
15369                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15370                syntax: cx.theme().syntax().clone(),
15371                status: cx.theme().status().clone(),
15372                inlay_hints_style: make_inlay_hints_style(cx),
15373                inline_completion_styles: make_suggestion_styles(cx),
15374                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15375            },
15376        )
15377    }
15378}
15379
15380impl EntityInputHandler for Editor {
15381    fn text_for_range(
15382        &mut self,
15383        range_utf16: Range<usize>,
15384        adjusted_range: &mut Option<Range<usize>>,
15385        _: &mut Window,
15386        cx: &mut Context<Self>,
15387    ) -> Option<String> {
15388        let snapshot = self.buffer.read(cx).read(cx);
15389        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15390        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15391        if (start.0..end.0) != range_utf16 {
15392            adjusted_range.replace(start.0..end.0);
15393        }
15394        Some(snapshot.text_for_range(start..end).collect())
15395    }
15396
15397    fn selected_text_range(
15398        &mut self,
15399        ignore_disabled_input: bool,
15400        _: &mut Window,
15401        cx: &mut Context<Self>,
15402    ) -> Option<UTF16Selection> {
15403        // Prevent the IME menu from appearing when holding down an alphabetic key
15404        // while input is disabled.
15405        if !ignore_disabled_input && !self.input_enabled {
15406            return None;
15407        }
15408
15409        let selection = self.selections.newest::<OffsetUtf16>(cx);
15410        let range = selection.range();
15411
15412        Some(UTF16Selection {
15413            range: range.start.0..range.end.0,
15414            reversed: selection.reversed,
15415        })
15416    }
15417
15418    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15419        let snapshot = self.buffer.read(cx).read(cx);
15420        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15421        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15422    }
15423
15424    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15425        self.clear_highlights::<InputComposition>(cx);
15426        self.ime_transaction.take();
15427    }
15428
15429    fn replace_text_in_range(
15430        &mut self,
15431        range_utf16: Option<Range<usize>>,
15432        text: &str,
15433        window: &mut Window,
15434        cx: &mut Context<Self>,
15435    ) {
15436        if !self.input_enabled {
15437            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15438            return;
15439        }
15440
15441        self.transact(window, cx, |this, window, cx| {
15442            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15443                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15444                Some(this.selection_replacement_ranges(range_utf16, cx))
15445            } else {
15446                this.marked_text_ranges(cx)
15447            };
15448
15449            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15450                let newest_selection_id = this.selections.newest_anchor().id;
15451                this.selections
15452                    .all::<OffsetUtf16>(cx)
15453                    .iter()
15454                    .zip(ranges_to_replace.iter())
15455                    .find_map(|(selection, range)| {
15456                        if selection.id == newest_selection_id {
15457                            Some(
15458                                (range.start.0 as isize - selection.head().0 as isize)
15459                                    ..(range.end.0 as isize - selection.head().0 as isize),
15460                            )
15461                        } else {
15462                            None
15463                        }
15464                    })
15465            });
15466
15467            cx.emit(EditorEvent::InputHandled {
15468                utf16_range_to_replace: range_to_replace,
15469                text: text.into(),
15470            });
15471
15472            if let Some(new_selected_ranges) = new_selected_ranges {
15473                this.change_selections(None, window, cx, |selections| {
15474                    selections.select_ranges(new_selected_ranges)
15475                });
15476                this.backspace(&Default::default(), window, cx);
15477            }
15478
15479            this.handle_input(text, window, cx);
15480        });
15481
15482        if let Some(transaction) = self.ime_transaction {
15483            self.buffer.update(cx, |buffer, cx| {
15484                buffer.group_until_transaction(transaction, cx);
15485            });
15486        }
15487
15488        self.unmark_text(window, cx);
15489    }
15490
15491    fn replace_and_mark_text_in_range(
15492        &mut self,
15493        range_utf16: Option<Range<usize>>,
15494        text: &str,
15495        new_selected_range_utf16: Option<Range<usize>>,
15496        window: &mut Window,
15497        cx: &mut Context<Self>,
15498    ) {
15499        if !self.input_enabled {
15500            return;
15501        }
15502
15503        let transaction = self.transact(window, cx, |this, window, cx| {
15504            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15505                let snapshot = this.buffer.read(cx).read(cx);
15506                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15507                    for marked_range in &mut marked_ranges {
15508                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15509                        marked_range.start.0 += relative_range_utf16.start;
15510                        marked_range.start =
15511                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15512                        marked_range.end =
15513                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15514                    }
15515                }
15516                Some(marked_ranges)
15517            } else if let Some(range_utf16) = range_utf16 {
15518                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15519                Some(this.selection_replacement_ranges(range_utf16, cx))
15520            } else {
15521                None
15522            };
15523
15524            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15525                let newest_selection_id = this.selections.newest_anchor().id;
15526                this.selections
15527                    .all::<OffsetUtf16>(cx)
15528                    .iter()
15529                    .zip(ranges_to_replace.iter())
15530                    .find_map(|(selection, range)| {
15531                        if selection.id == newest_selection_id {
15532                            Some(
15533                                (range.start.0 as isize - selection.head().0 as isize)
15534                                    ..(range.end.0 as isize - selection.head().0 as isize),
15535                            )
15536                        } else {
15537                            None
15538                        }
15539                    })
15540            });
15541
15542            cx.emit(EditorEvent::InputHandled {
15543                utf16_range_to_replace: range_to_replace,
15544                text: text.into(),
15545            });
15546
15547            if let Some(ranges) = ranges_to_replace {
15548                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15549            }
15550
15551            let marked_ranges = {
15552                let snapshot = this.buffer.read(cx).read(cx);
15553                this.selections
15554                    .disjoint_anchors()
15555                    .iter()
15556                    .map(|selection| {
15557                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15558                    })
15559                    .collect::<Vec<_>>()
15560            };
15561
15562            if text.is_empty() {
15563                this.unmark_text(window, cx);
15564            } else {
15565                this.highlight_text::<InputComposition>(
15566                    marked_ranges.clone(),
15567                    HighlightStyle {
15568                        underline: Some(UnderlineStyle {
15569                            thickness: px(1.),
15570                            color: None,
15571                            wavy: false,
15572                        }),
15573                        ..Default::default()
15574                    },
15575                    cx,
15576                );
15577            }
15578
15579            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15580            let use_autoclose = this.use_autoclose;
15581            let use_auto_surround = this.use_auto_surround;
15582            this.set_use_autoclose(false);
15583            this.set_use_auto_surround(false);
15584            this.handle_input(text, window, cx);
15585            this.set_use_autoclose(use_autoclose);
15586            this.set_use_auto_surround(use_auto_surround);
15587
15588            if let Some(new_selected_range) = new_selected_range_utf16 {
15589                let snapshot = this.buffer.read(cx).read(cx);
15590                let new_selected_ranges = marked_ranges
15591                    .into_iter()
15592                    .map(|marked_range| {
15593                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15594                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15595                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15596                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15597                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15598                    })
15599                    .collect::<Vec<_>>();
15600
15601                drop(snapshot);
15602                this.change_selections(None, window, cx, |selections| {
15603                    selections.select_ranges(new_selected_ranges)
15604                });
15605            }
15606        });
15607
15608        self.ime_transaction = self.ime_transaction.or(transaction);
15609        if let Some(transaction) = self.ime_transaction {
15610            self.buffer.update(cx, |buffer, cx| {
15611                buffer.group_until_transaction(transaction, cx);
15612            });
15613        }
15614
15615        if self.text_highlights::<InputComposition>(cx).is_none() {
15616            self.ime_transaction.take();
15617        }
15618    }
15619
15620    fn bounds_for_range(
15621        &mut self,
15622        range_utf16: Range<usize>,
15623        element_bounds: gpui::Bounds<Pixels>,
15624        window: &mut Window,
15625        cx: &mut Context<Self>,
15626    ) -> Option<gpui::Bounds<Pixels>> {
15627        let text_layout_details = self.text_layout_details(window);
15628        let gpui::Point {
15629            x: em_width,
15630            y: line_height,
15631        } = self.character_size(window);
15632
15633        let snapshot = self.snapshot(window, cx);
15634        let scroll_position = snapshot.scroll_position();
15635        let scroll_left = scroll_position.x * em_width;
15636
15637        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15638        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15639            + self.gutter_dimensions.width
15640            + self.gutter_dimensions.margin;
15641        let y = line_height * (start.row().as_f32() - scroll_position.y);
15642
15643        Some(Bounds {
15644            origin: element_bounds.origin + point(x, y),
15645            size: size(em_width, line_height),
15646        })
15647    }
15648}
15649
15650trait SelectionExt {
15651    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15652    fn spanned_rows(
15653        &self,
15654        include_end_if_at_line_start: bool,
15655        map: &DisplaySnapshot,
15656    ) -> Range<MultiBufferRow>;
15657}
15658
15659impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15660    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15661        let start = self
15662            .start
15663            .to_point(&map.buffer_snapshot)
15664            .to_display_point(map);
15665        let end = self
15666            .end
15667            .to_point(&map.buffer_snapshot)
15668            .to_display_point(map);
15669        if self.reversed {
15670            end..start
15671        } else {
15672            start..end
15673        }
15674    }
15675
15676    fn spanned_rows(
15677        &self,
15678        include_end_if_at_line_start: bool,
15679        map: &DisplaySnapshot,
15680    ) -> Range<MultiBufferRow> {
15681        let start = self.start.to_point(&map.buffer_snapshot);
15682        let mut end = self.end.to_point(&map.buffer_snapshot);
15683        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15684            end.row -= 1;
15685        }
15686
15687        let buffer_start = map.prev_line_boundary(start).0;
15688        let buffer_end = map.next_line_boundary(end).0;
15689        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15690    }
15691}
15692
15693impl<T: InvalidationRegion> InvalidationStack<T> {
15694    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15695    where
15696        S: Clone + ToOffset,
15697    {
15698        while let Some(region) = self.last() {
15699            let all_selections_inside_invalidation_ranges =
15700                if selections.len() == region.ranges().len() {
15701                    selections
15702                        .iter()
15703                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15704                        .all(|(selection, invalidation_range)| {
15705                            let head = selection.head().to_offset(buffer);
15706                            invalidation_range.start <= head && invalidation_range.end >= head
15707                        })
15708                } else {
15709                    false
15710                };
15711
15712            if all_selections_inside_invalidation_ranges {
15713                break;
15714            } else {
15715                self.pop();
15716            }
15717        }
15718    }
15719}
15720
15721impl<T> Default for InvalidationStack<T> {
15722    fn default() -> Self {
15723        Self(Default::default())
15724    }
15725}
15726
15727impl<T> Deref for InvalidationStack<T> {
15728    type Target = Vec<T>;
15729
15730    fn deref(&self) -> &Self::Target {
15731        &self.0
15732    }
15733}
15734
15735impl<T> DerefMut for InvalidationStack<T> {
15736    fn deref_mut(&mut self) -> &mut Self::Target {
15737        &mut self.0
15738    }
15739}
15740
15741impl InvalidationRegion for SnippetState {
15742    fn ranges(&self) -> &[Range<Anchor>] {
15743        &self.ranges[self.active_index]
15744    }
15745}
15746
15747pub fn diagnostic_block_renderer(
15748    diagnostic: Diagnostic,
15749    max_message_rows: Option<u8>,
15750    allow_closing: bool,
15751    _is_valid: bool,
15752) -> RenderBlock {
15753    let (text_without_backticks, code_ranges) =
15754        highlight_diagnostic_message(&diagnostic, max_message_rows);
15755
15756    Arc::new(move |cx: &mut BlockContext| {
15757        let group_id: SharedString = cx.block_id.to_string().into();
15758
15759        let mut text_style = cx.window.text_style().clone();
15760        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15761        let theme_settings = ThemeSettings::get_global(cx);
15762        text_style.font_family = theme_settings.buffer_font.family.clone();
15763        text_style.font_style = theme_settings.buffer_font.style;
15764        text_style.font_features = theme_settings.buffer_font.features.clone();
15765        text_style.font_weight = theme_settings.buffer_font.weight;
15766
15767        let multi_line_diagnostic = diagnostic.message.contains('\n');
15768
15769        let buttons = |diagnostic: &Diagnostic| {
15770            if multi_line_diagnostic {
15771                v_flex()
15772            } else {
15773                h_flex()
15774            }
15775            .when(allow_closing, |div| {
15776                div.children(diagnostic.is_primary.then(|| {
15777                    IconButton::new("close-block", IconName::XCircle)
15778                        .icon_color(Color::Muted)
15779                        .size(ButtonSize::Compact)
15780                        .style(ButtonStyle::Transparent)
15781                        .visible_on_hover(group_id.clone())
15782                        .on_click(move |_click, window, cx| {
15783                            window.dispatch_action(Box::new(Cancel), cx)
15784                        })
15785                        .tooltip(|window, cx| {
15786                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15787                        })
15788                }))
15789            })
15790            .child(
15791                IconButton::new("copy-block", IconName::Copy)
15792                    .icon_color(Color::Muted)
15793                    .size(ButtonSize::Compact)
15794                    .style(ButtonStyle::Transparent)
15795                    .visible_on_hover(group_id.clone())
15796                    .on_click({
15797                        let message = diagnostic.message.clone();
15798                        move |_click, _, cx| {
15799                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15800                        }
15801                    })
15802                    .tooltip(Tooltip::text("Copy diagnostic message")),
15803            )
15804        };
15805
15806        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15807            AvailableSpace::min_size(),
15808            cx.window,
15809            cx.app,
15810        );
15811
15812        h_flex()
15813            .id(cx.block_id)
15814            .group(group_id.clone())
15815            .relative()
15816            .size_full()
15817            .block_mouse_down()
15818            .pl(cx.gutter_dimensions.width)
15819            .w(cx.max_width - cx.gutter_dimensions.full_width())
15820            .child(
15821                div()
15822                    .flex()
15823                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15824                    .flex_shrink(),
15825            )
15826            .child(buttons(&diagnostic))
15827            .child(div().flex().flex_shrink_0().child(
15828                StyledText::new(text_without_backticks.clone()).with_highlights(
15829                    &text_style,
15830                    code_ranges.iter().map(|range| {
15831                        (
15832                            range.clone(),
15833                            HighlightStyle {
15834                                font_weight: Some(FontWeight::BOLD),
15835                                ..Default::default()
15836                            },
15837                        )
15838                    }),
15839                ),
15840            ))
15841            .into_any_element()
15842    })
15843}
15844
15845fn inline_completion_edit_text(
15846    current_snapshot: &BufferSnapshot,
15847    edits: &[(Range<Anchor>, String)],
15848    edit_preview: &EditPreview,
15849    include_deletions: bool,
15850    cx: &App,
15851) -> Option<HighlightedEdits> {
15852    let edits = edits
15853        .iter()
15854        .map(|(anchor, text)| {
15855            (
15856                anchor.start.text_anchor..anchor.end.text_anchor,
15857                text.clone(),
15858            )
15859        })
15860        .collect::<Vec<_>>();
15861
15862    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15863}
15864
15865pub fn highlight_diagnostic_message(
15866    diagnostic: &Diagnostic,
15867    mut max_message_rows: Option<u8>,
15868) -> (SharedString, Vec<Range<usize>>) {
15869    let mut text_without_backticks = String::new();
15870    let mut code_ranges = Vec::new();
15871
15872    if let Some(source) = &diagnostic.source {
15873        text_without_backticks.push_str(source);
15874        code_ranges.push(0..source.len());
15875        text_without_backticks.push_str(": ");
15876    }
15877
15878    let mut prev_offset = 0;
15879    let mut in_code_block = false;
15880    let has_row_limit = max_message_rows.is_some();
15881    let mut newline_indices = diagnostic
15882        .message
15883        .match_indices('\n')
15884        .filter(|_| has_row_limit)
15885        .map(|(ix, _)| ix)
15886        .fuse()
15887        .peekable();
15888
15889    for (quote_ix, _) in diagnostic
15890        .message
15891        .match_indices('`')
15892        .chain([(diagnostic.message.len(), "")])
15893    {
15894        let mut first_newline_ix = None;
15895        let mut last_newline_ix = None;
15896        while let Some(newline_ix) = newline_indices.peek() {
15897            if *newline_ix < quote_ix {
15898                if first_newline_ix.is_none() {
15899                    first_newline_ix = Some(*newline_ix);
15900                }
15901                last_newline_ix = Some(*newline_ix);
15902
15903                if let Some(rows_left) = &mut max_message_rows {
15904                    if *rows_left == 0 {
15905                        break;
15906                    } else {
15907                        *rows_left -= 1;
15908                    }
15909                }
15910                let _ = newline_indices.next();
15911            } else {
15912                break;
15913            }
15914        }
15915        let prev_len = text_without_backticks.len();
15916        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15917        text_without_backticks.push_str(new_text);
15918        if in_code_block {
15919            code_ranges.push(prev_len..text_without_backticks.len());
15920        }
15921        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15922        in_code_block = !in_code_block;
15923        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15924            text_without_backticks.push_str("...");
15925            break;
15926        }
15927    }
15928
15929    (text_without_backticks.into(), code_ranges)
15930}
15931
15932fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15933    match severity {
15934        DiagnosticSeverity::ERROR => colors.error,
15935        DiagnosticSeverity::WARNING => colors.warning,
15936        DiagnosticSeverity::INFORMATION => colors.info,
15937        DiagnosticSeverity::HINT => colors.info,
15938        _ => colors.ignored,
15939    }
15940}
15941
15942pub fn styled_runs_for_code_label<'a>(
15943    label: &'a CodeLabel,
15944    syntax_theme: &'a theme::SyntaxTheme,
15945) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15946    let fade_out = HighlightStyle {
15947        fade_out: Some(0.35),
15948        ..Default::default()
15949    };
15950
15951    let mut prev_end = label.filter_range.end;
15952    label
15953        .runs
15954        .iter()
15955        .enumerate()
15956        .flat_map(move |(ix, (range, highlight_id))| {
15957            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15958                style
15959            } else {
15960                return Default::default();
15961            };
15962            let mut muted_style = style;
15963            muted_style.highlight(fade_out);
15964
15965            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15966            if range.start >= label.filter_range.end {
15967                if range.start > prev_end {
15968                    runs.push((prev_end..range.start, fade_out));
15969                }
15970                runs.push((range.clone(), muted_style));
15971            } else if range.end <= label.filter_range.end {
15972                runs.push((range.clone(), style));
15973            } else {
15974                runs.push((range.start..label.filter_range.end, style));
15975                runs.push((label.filter_range.end..range.end, muted_style));
15976            }
15977            prev_end = cmp::max(prev_end, range.end);
15978
15979            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15980                runs.push((prev_end..label.text.len(), fade_out));
15981            }
15982
15983            runs
15984        })
15985}
15986
15987pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15988    let mut prev_index = 0;
15989    let mut prev_codepoint: Option<char> = None;
15990    text.char_indices()
15991        .chain([(text.len(), '\0')])
15992        .filter_map(move |(index, codepoint)| {
15993            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15994            let is_boundary = index == text.len()
15995                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15996                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15997            if is_boundary {
15998                let chunk = &text[prev_index..index];
15999                prev_index = index;
16000                Some(chunk)
16001            } else {
16002                None
16003            }
16004        })
16005}
16006
16007pub trait RangeToAnchorExt: Sized {
16008    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16009
16010    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16011        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16012        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16013    }
16014}
16015
16016impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16017    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16018        let start_offset = self.start.to_offset(snapshot);
16019        let end_offset = self.end.to_offset(snapshot);
16020        if start_offset == end_offset {
16021            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16022        } else {
16023            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16024        }
16025    }
16026}
16027
16028pub trait RowExt {
16029    fn as_f32(&self) -> f32;
16030
16031    fn next_row(&self) -> Self;
16032
16033    fn previous_row(&self) -> Self;
16034
16035    fn minus(&self, other: Self) -> u32;
16036}
16037
16038impl RowExt for DisplayRow {
16039    fn as_f32(&self) -> f32 {
16040        self.0 as f32
16041    }
16042
16043    fn next_row(&self) -> Self {
16044        Self(self.0 + 1)
16045    }
16046
16047    fn previous_row(&self) -> Self {
16048        Self(self.0.saturating_sub(1))
16049    }
16050
16051    fn minus(&self, other: Self) -> u32 {
16052        self.0 - other.0
16053    }
16054}
16055
16056impl RowExt for MultiBufferRow {
16057    fn as_f32(&self) -> f32 {
16058        self.0 as f32
16059    }
16060
16061    fn next_row(&self) -> Self {
16062        Self(self.0 + 1)
16063    }
16064
16065    fn previous_row(&self) -> Self {
16066        Self(self.0.saturating_sub(1))
16067    }
16068
16069    fn minus(&self, other: Self) -> u32 {
16070        self.0 - other.0
16071    }
16072}
16073
16074trait RowRangeExt {
16075    type Row;
16076
16077    fn len(&self) -> usize;
16078
16079    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16080}
16081
16082impl RowRangeExt for Range<MultiBufferRow> {
16083    type Row = MultiBufferRow;
16084
16085    fn len(&self) -> usize {
16086        (self.end.0 - self.start.0) as usize
16087    }
16088
16089    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16090        (self.start.0..self.end.0).map(MultiBufferRow)
16091    }
16092}
16093
16094impl RowRangeExt for Range<DisplayRow> {
16095    type Row = DisplayRow;
16096
16097    fn len(&self) -> usize {
16098        (self.end.0 - self.start.0) as usize
16099    }
16100
16101    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16102        (self.start.0..self.end.0).map(DisplayRow)
16103    }
16104}
16105
16106/// If select range has more than one line, we
16107/// just point the cursor to range.start.
16108fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16109    if range.start.row == range.end.row {
16110        range
16111    } else {
16112        range.start..range.start
16113    }
16114}
16115pub struct KillRing(ClipboardItem);
16116impl Global for KillRing {}
16117
16118const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16119
16120fn all_edits_insertions_or_deletions(
16121    edits: &Vec<(Range<Anchor>, String)>,
16122    snapshot: &MultiBufferSnapshot,
16123) -> bool {
16124    let mut all_insertions = true;
16125    let mut all_deletions = true;
16126
16127    for (range, new_text) in edits.iter() {
16128        let range_is_empty = range.to_offset(&snapshot).is_empty();
16129        let text_is_empty = new_text.is_empty();
16130
16131        if range_is_empty != text_is_empty {
16132            if range_is_empty {
16133                all_deletions = false;
16134            } else {
16135                all_insertions = false;
16136            }
16137        } else {
16138            return false;
16139        }
16140
16141        if !all_insertions && !all_deletions {
16142            return false;
16143        }
16144    }
16145    all_insertions || all_deletions
16146}