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, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size,
   85    Styled, StyledText, Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection,
   86    UnderlineStyle, 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    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  685    gutter_hovered: bool,
  686    hovered_link_state: Option<HoveredLinkState>,
  687    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  688    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  689    active_inline_completion: Option<InlineCompletionState>,
  690    // enable_inline_completions is a switch that Vim can use to disable
  691    // inline completions based on its mode.
  692    enable_inline_completions: bool,
  693    show_inline_completions_override: Option<bool>,
  694    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  695    inlay_hint_cache: InlayHintCache,
  696    next_inlay_id: usize,
  697    _subscriptions: Vec<Subscription>,
  698    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  699    gutter_dimensions: GutterDimensions,
  700    style: Option<EditorStyle>,
  701    text_style_refinement: Option<TextStyleRefinement>,
  702    next_editor_action_id: EditorActionId,
  703    editor_actions:
  704        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  705    use_autoclose: bool,
  706    use_auto_surround: bool,
  707    auto_replace_emoji_shortcode: bool,
  708    show_git_blame_gutter: bool,
  709    show_git_blame_inline: bool,
  710    show_git_blame_inline_delay_task: Option<Task<()>>,
  711    git_blame_inline_enabled: bool,
  712    serialize_dirty_buffers: bool,
  713    show_selection_menu: Option<bool>,
  714    blame: Option<Entity<GitBlame>>,
  715    blame_subscription: Option<Subscription>,
  716    custom_context_menu: Option<
  717        Box<
  718            dyn 'static
  719                + Fn(
  720                    &mut Self,
  721                    DisplayPoint,
  722                    &mut Window,
  723                    &mut Context<Self>,
  724                ) -> Option<Entity<ui::ContextMenu>>,
  725        >,
  726    >,
  727    last_bounds: Option<Bounds<Pixels>>,
  728    expect_bounds_change: Option<Bounds<Pixels>>,
  729    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  730    tasks_update_task: Option<Task<()>>,
  731    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  732    breadcrumb_header: Option<String>,
  733    focused_block: Option<FocusedBlock>,
  734    next_scroll_position: NextScrollCursorCenterTopBottom,
  735    addons: HashMap<TypeId, Box<dyn Addon>>,
  736    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  737    selection_mark_mode: bool,
  738    toggle_fold_multiple_buffers: Task<()>,
  739    _scroll_cursor_center_top_bottom_task: Task<()>,
  740}
  741
  742#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  743enum NextScrollCursorCenterTopBottom {
  744    #[default]
  745    Center,
  746    Top,
  747    Bottom,
  748}
  749
  750impl NextScrollCursorCenterTopBottom {
  751    fn next(&self) -> Self {
  752        match self {
  753            Self::Center => Self::Top,
  754            Self::Top => Self::Bottom,
  755            Self::Bottom => Self::Center,
  756        }
  757    }
  758}
  759
  760#[derive(Clone)]
  761pub struct EditorSnapshot {
  762    pub mode: EditorMode,
  763    show_gutter: bool,
  764    show_line_numbers: Option<bool>,
  765    show_git_diff_gutter: Option<bool>,
  766    show_code_actions: Option<bool>,
  767    show_runnables: Option<bool>,
  768    git_blame_gutter_max_author_length: Option<usize>,
  769    pub display_snapshot: DisplaySnapshot,
  770    pub placeholder_text: Option<Arc<str>>,
  771    is_focused: bool,
  772    scroll_anchor: ScrollAnchor,
  773    ongoing_scroll: OngoingScroll,
  774    current_line_highlight: CurrentLineHighlight,
  775    gutter_hovered: bool,
  776}
  777
  778const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  779
  780#[derive(Default, Debug, Clone, Copy)]
  781pub struct GutterDimensions {
  782    pub left_padding: Pixels,
  783    pub right_padding: Pixels,
  784    pub width: Pixels,
  785    pub margin: Pixels,
  786    pub git_blame_entries_width: Option<Pixels>,
  787}
  788
  789impl GutterDimensions {
  790    /// The full width of the space taken up by the gutter.
  791    pub fn full_width(&self) -> Pixels {
  792        self.margin + self.width
  793    }
  794
  795    /// The width of the space reserved for the fold indicators,
  796    /// use alongside 'justify_end' and `gutter_width` to
  797    /// right align content with the line numbers
  798    pub fn fold_area_width(&self) -> Pixels {
  799        self.margin + self.right_padding
  800    }
  801}
  802
  803#[derive(Debug)]
  804pub struct RemoteSelection {
  805    pub replica_id: ReplicaId,
  806    pub selection: Selection<Anchor>,
  807    pub cursor_shape: CursorShape,
  808    pub peer_id: PeerId,
  809    pub line_mode: bool,
  810    pub participant_index: Option<ParticipantIndex>,
  811    pub user_name: Option<SharedString>,
  812}
  813
  814#[derive(Clone, Debug)]
  815struct SelectionHistoryEntry {
  816    selections: Arc<[Selection<Anchor>]>,
  817    select_next_state: Option<SelectNextState>,
  818    select_prev_state: Option<SelectNextState>,
  819    add_selections_state: Option<AddSelectionsState>,
  820}
  821
  822enum SelectionHistoryMode {
  823    Normal,
  824    Undoing,
  825    Redoing,
  826}
  827
  828#[derive(Clone, PartialEq, Eq, Hash)]
  829struct HoveredCursor {
  830    replica_id: u16,
  831    selection_id: usize,
  832}
  833
  834impl Default for SelectionHistoryMode {
  835    fn default() -> Self {
  836        Self::Normal
  837    }
  838}
  839
  840#[derive(Default)]
  841struct SelectionHistory {
  842    #[allow(clippy::type_complexity)]
  843    selections_by_transaction:
  844        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  845    mode: SelectionHistoryMode,
  846    undo_stack: VecDeque<SelectionHistoryEntry>,
  847    redo_stack: VecDeque<SelectionHistoryEntry>,
  848}
  849
  850impl SelectionHistory {
  851    fn insert_transaction(
  852        &mut self,
  853        transaction_id: TransactionId,
  854        selections: Arc<[Selection<Anchor>]>,
  855    ) {
  856        self.selections_by_transaction
  857            .insert(transaction_id, (selections, None));
  858    }
  859
  860    #[allow(clippy::type_complexity)]
  861    fn transaction(
  862        &self,
  863        transaction_id: TransactionId,
  864    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  865        self.selections_by_transaction.get(&transaction_id)
  866    }
  867
  868    #[allow(clippy::type_complexity)]
  869    fn transaction_mut(
  870        &mut self,
  871        transaction_id: TransactionId,
  872    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  873        self.selections_by_transaction.get_mut(&transaction_id)
  874    }
  875
  876    fn push(&mut self, entry: SelectionHistoryEntry) {
  877        if !entry.selections.is_empty() {
  878            match self.mode {
  879                SelectionHistoryMode::Normal => {
  880                    self.push_undo(entry);
  881                    self.redo_stack.clear();
  882                }
  883                SelectionHistoryMode::Undoing => self.push_redo(entry),
  884                SelectionHistoryMode::Redoing => self.push_undo(entry),
  885            }
  886        }
  887    }
  888
  889    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  890        if self
  891            .undo_stack
  892            .back()
  893            .map_or(true, |e| e.selections != entry.selections)
  894        {
  895            self.undo_stack.push_back(entry);
  896            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  897                self.undo_stack.pop_front();
  898            }
  899        }
  900    }
  901
  902    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  903        if self
  904            .redo_stack
  905            .back()
  906            .map_or(true, |e| e.selections != entry.selections)
  907        {
  908            self.redo_stack.push_back(entry);
  909            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  910                self.redo_stack.pop_front();
  911            }
  912        }
  913    }
  914}
  915
  916struct RowHighlight {
  917    index: usize,
  918    range: Range<Anchor>,
  919    color: Hsla,
  920    should_autoscroll: bool,
  921}
  922
  923#[derive(Clone, Debug)]
  924struct AddSelectionsState {
  925    above: bool,
  926    stack: Vec<usize>,
  927}
  928
  929#[derive(Clone)]
  930struct SelectNextState {
  931    query: AhoCorasick,
  932    wordwise: bool,
  933    done: bool,
  934}
  935
  936impl std::fmt::Debug for SelectNextState {
  937    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  938        f.debug_struct(std::any::type_name::<Self>())
  939            .field("wordwise", &self.wordwise)
  940            .field("done", &self.done)
  941            .finish()
  942    }
  943}
  944
  945#[derive(Debug)]
  946struct AutocloseRegion {
  947    selection_id: usize,
  948    range: Range<Anchor>,
  949    pair: BracketPair,
  950}
  951
  952#[derive(Debug)]
  953struct SnippetState {
  954    ranges: Vec<Vec<Range<Anchor>>>,
  955    active_index: usize,
  956    choices: Vec<Option<Vec<String>>>,
  957}
  958
  959#[doc(hidden)]
  960pub struct RenameState {
  961    pub range: Range<Anchor>,
  962    pub old_name: Arc<str>,
  963    pub editor: Entity<Editor>,
  964    block_id: CustomBlockId,
  965}
  966
  967struct InvalidationStack<T>(Vec<T>);
  968
  969struct RegisteredInlineCompletionProvider {
  970    provider: Arc<dyn InlineCompletionProviderHandle>,
  971    _subscription: Subscription,
  972}
  973
  974#[derive(Debug)]
  975struct ActiveDiagnosticGroup {
  976    primary_range: Range<Anchor>,
  977    primary_message: String,
  978    group_id: usize,
  979    blocks: HashMap<CustomBlockId, Diagnostic>,
  980    is_valid: bool,
  981}
  982
  983#[derive(Serialize, Deserialize, Clone, Debug)]
  984pub struct ClipboardSelection {
  985    pub len: usize,
  986    pub is_entire_line: bool,
  987    pub first_line_indent: u32,
  988}
  989
  990#[derive(Debug)]
  991pub(crate) struct NavigationData {
  992    cursor_anchor: Anchor,
  993    cursor_position: Point,
  994    scroll_anchor: ScrollAnchor,
  995    scroll_top_row: u32,
  996}
  997
  998#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  999pub enum GotoDefinitionKind {
 1000    Symbol,
 1001    Declaration,
 1002    Type,
 1003    Implementation,
 1004}
 1005
 1006#[derive(Debug, Clone)]
 1007enum InlayHintRefreshReason {
 1008    Toggle(bool),
 1009    SettingsChange(InlayHintSettings),
 1010    NewLinesShown,
 1011    BufferEdited(HashSet<Arc<Language>>),
 1012    RefreshRequested,
 1013    ExcerptsRemoved(Vec<ExcerptId>),
 1014}
 1015
 1016impl InlayHintRefreshReason {
 1017    fn description(&self) -> &'static str {
 1018        match self {
 1019            Self::Toggle(_) => "toggle",
 1020            Self::SettingsChange(_) => "settings change",
 1021            Self::NewLinesShown => "new lines shown",
 1022            Self::BufferEdited(_) => "buffer edited",
 1023            Self::RefreshRequested => "refresh requested",
 1024            Self::ExcerptsRemoved(_) => "excerpts removed",
 1025        }
 1026    }
 1027}
 1028
 1029pub enum FormatTarget {
 1030    Buffers,
 1031    Ranges(Vec<Range<MultiBufferPoint>>),
 1032}
 1033
 1034pub(crate) struct FocusedBlock {
 1035    id: BlockId,
 1036    focus_handle: WeakFocusHandle,
 1037}
 1038
 1039#[derive(Clone)]
 1040enum JumpData {
 1041    MultiBufferRow {
 1042        row: MultiBufferRow,
 1043        line_offset_from_top: u32,
 1044    },
 1045    MultiBufferPoint {
 1046        excerpt_id: ExcerptId,
 1047        position: Point,
 1048        anchor: text::Anchor,
 1049        line_offset_from_top: u32,
 1050    },
 1051}
 1052
 1053pub enum MultibufferSelectionMode {
 1054    First,
 1055    All,
 1056}
 1057
 1058impl Editor {
 1059    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1060        let buffer = cx.new(|cx| Buffer::local("", cx));
 1061        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1062        Self::new(
 1063            EditorMode::SingleLine { auto_width: false },
 1064            buffer,
 1065            None,
 1066            false,
 1067            window,
 1068            cx,
 1069        )
 1070    }
 1071
 1072    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1073        let buffer = cx.new(|cx| Buffer::local("", cx));
 1074        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1075        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1076    }
 1077
 1078    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1079        let buffer = cx.new(|cx| Buffer::local("", cx));
 1080        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1081        Self::new(
 1082            EditorMode::SingleLine { auto_width: true },
 1083            buffer,
 1084            None,
 1085            false,
 1086            window,
 1087            cx,
 1088        )
 1089    }
 1090
 1091    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1092        let buffer = cx.new(|cx| Buffer::local("", cx));
 1093        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1094        Self::new(
 1095            EditorMode::AutoHeight { max_lines },
 1096            buffer,
 1097            None,
 1098            false,
 1099            window,
 1100            cx,
 1101        )
 1102    }
 1103
 1104    pub fn for_buffer(
 1105        buffer: Entity<Buffer>,
 1106        project: Option<Entity<Project>>,
 1107        window: &mut Window,
 1108        cx: &mut Context<Self>,
 1109    ) -> Self {
 1110        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1111        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1112    }
 1113
 1114    pub fn for_multibuffer(
 1115        buffer: Entity<MultiBuffer>,
 1116        project: Option<Entity<Project>>,
 1117        show_excerpt_controls: bool,
 1118        window: &mut Window,
 1119        cx: &mut Context<Self>,
 1120    ) -> Self {
 1121        Self::new(
 1122            EditorMode::Full,
 1123            buffer,
 1124            project,
 1125            show_excerpt_controls,
 1126            window,
 1127            cx,
 1128        )
 1129    }
 1130
 1131    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1132        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1133        let mut clone = Self::new(
 1134            self.mode,
 1135            self.buffer.clone(),
 1136            self.project.clone(),
 1137            show_excerpt_controls,
 1138            window,
 1139            cx,
 1140        );
 1141        self.display_map.update(cx, |display_map, cx| {
 1142            let snapshot = display_map.snapshot(cx);
 1143            clone.display_map.update(cx, |display_map, cx| {
 1144                display_map.set_state(&snapshot, cx);
 1145            });
 1146        });
 1147        clone.selections.clone_state(&self.selections);
 1148        clone.scroll_manager.clone_state(&self.scroll_manager);
 1149        clone.searchable = self.searchable;
 1150        clone
 1151    }
 1152
 1153    pub fn new(
 1154        mode: EditorMode,
 1155        buffer: Entity<MultiBuffer>,
 1156        project: Option<Entity<Project>>,
 1157        show_excerpt_controls: bool,
 1158        window: &mut Window,
 1159        cx: &mut Context<Self>,
 1160    ) -> Self {
 1161        let style = window.text_style();
 1162        let font_size = style.font_size.to_pixels(window.rem_size());
 1163        let editor = cx.entity().downgrade();
 1164        let fold_placeholder = FoldPlaceholder {
 1165            constrain_width: true,
 1166            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1167                let editor = editor.clone();
 1168                div()
 1169                    .id(fold_id)
 1170                    .bg(cx.theme().colors().ghost_element_background)
 1171                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1172                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1173                    .rounded_sm()
 1174                    .size_full()
 1175                    .cursor_pointer()
 1176                    .child("")
 1177                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1178                    .on_click(move |_, _window, cx| {
 1179                        editor
 1180                            .update(cx, |editor, cx| {
 1181                                editor.unfold_ranges(
 1182                                    &[fold_range.start..fold_range.end],
 1183                                    true,
 1184                                    false,
 1185                                    cx,
 1186                                );
 1187                                cx.stop_propagation();
 1188                            })
 1189                            .ok();
 1190                    })
 1191                    .into_any()
 1192            }),
 1193            merge_adjacent: true,
 1194            ..Default::default()
 1195        };
 1196        let display_map = cx.new(|cx| {
 1197            DisplayMap::new(
 1198                buffer.clone(),
 1199                style.font(),
 1200                font_size,
 1201                None,
 1202                show_excerpt_controls,
 1203                FILE_HEADER_HEIGHT,
 1204                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1205                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1206                fold_placeholder,
 1207                cx,
 1208            )
 1209        });
 1210
 1211        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1212
 1213        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1214
 1215        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1216            .then(|| language_settings::SoftWrap::None);
 1217
 1218        let mut project_subscriptions = Vec::new();
 1219        if mode == EditorMode::Full {
 1220            if let Some(project) = project.as_ref() {
 1221                if buffer.read(cx).is_singleton() {
 1222                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1223                        cx.emit(EditorEvent::TitleChanged);
 1224                    }));
 1225                }
 1226                project_subscriptions.push(cx.subscribe_in(
 1227                    project,
 1228                    window,
 1229                    |editor, _, event, window, cx| {
 1230                        if let project::Event::RefreshInlayHints = event {
 1231                            editor
 1232                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1233                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1234                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1235                                let focus_handle = editor.focus_handle(cx);
 1236                                if focus_handle.is_focused(window) {
 1237                                    let snapshot = buffer.read(cx).snapshot();
 1238                                    for (range, snippet) in snippet_edits {
 1239                                        let editor_range =
 1240                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1241                                        editor
 1242                                            .insert_snippet(
 1243                                                &[editor_range],
 1244                                                snippet.clone(),
 1245                                                window,
 1246                                                cx,
 1247                                            )
 1248                                            .ok();
 1249                                    }
 1250                                }
 1251                            }
 1252                        }
 1253                    },
 1254                ));
 1255                if let Some(task_inventory) = project
 1256                    .read(cx)
 1257                    .task_store()
 1258                    .read(cx)
 1259                    .task_inventory()
 1260                    .cloned()
 1261                {
 1262                    project_subscriptions.push(cx.observe_in(
 1263                        &task_inventory,
 1264                        window,
 1265                        |editor, _, window, cx| {
 1266                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1267                        },
 1268                    ));
 1269                }
 1270            }
 1271        }
 1272
 1273        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1274
 1275        let inlay_hint_settings =
 1276            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1277        let focus_handle = cx.focus_handle();
 1278        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1279            .detach();
 1280        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1281            .detach();
 1282        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1283            .detach();
 1284        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1285            .detach();
 1286
 1287        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1288            Some(false)
 1289        } else {
 1290            None
 1291        };
 1292
 1293        let mut code_action_providers = Vec::new();
 1294        if let Some(project) = project.clone() {
 1295            get_unstaged_changes_for_buffers(
 1296                &project,
 1297                buffer.read(cx).all_buffers(),
 1298                buffer.clone(),
 1299                cx,
 1300            );
 1301            code_action_providers.push(Rc::new(project) as Rc<_>);
 1302        }
 1303
 1304        let mut this = Self {
 1305            focus_handle,
 1306            show_cursor_when_unfocused: false,
 1307            last_focused_descendant: None,
 1308            buffer: buffer.clone(),
 1309            display_map: display_map.clone(),
 1310            selections,
 1311            scroll_manager: ScrollManager::new(cx),
 1312            columnar_selection_tail: None,
 1313            add_selections_state: None,
 1314            select_next_state: None,
 1315            select_prev_state: None,
 1316            selection_history: Default::default(),
 1317            autoclose_regions: Default::default(),
 1318            snippet_stack: Default::default(),
 1319            select_larger_syntax_node_stack: Vec::new(),
 1320            ime_transaction: Default::default(),
 1321            active_diagnostics: None,
 1322            soft_wrap_mode_override,
 1323            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1324            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1325            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1326            project,
 1327            blink_manager: blink_manager.clone(),
 1328            show_local_selections: true,
 1329            show_scrollbars: true,
 1330            mode,
 1331            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1332            show_gutter: mode == EditorMode::Full,
 1333            show_line_numbers: None,
 1334            use_relative_line_numbers: None,
 1335            show_git_diff_gutter: None,
 1336            show_code_actions: None,
 1337            show_runnables: None,
 1338            show_wrap_guides: None,
 1339            show_indent_guides,
 1340            placeholder_text: None,
 1341            highlight_order: 0,
 1342            highlighted_rows: HashMap::default(),
 1343            background_highlights: Default::default(),
 1344            gutter_highlights: TreeMap::default(),
 1345            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1346            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1347            nav_history: None,
 1348            context_menu: RefCell::new(None),
 1349            mouse_context_menu: None,
 1350            completion_tasks: Default::default(),
 1351            signature_help_state: SignatureHelpState::default(),
 1352            auto_signature_help: None,
 1353            find_all_references_task_sources: Vec::new(),
 1354            next_completion_id: 0,
 1355            next_inlay_id: 0,
 1356            code_action_providers,
 1357            available_code_actions: Default::default(),
 1358            code_actions_task: Default::default(),
 1359            document_highlights_task: Default::default(),
 1360            linked_editing_range_task: Default::default(),
 1361            pending_rename: Default::default(),
 1362            searchable: true,
 1363            cursor_shape: EditorSettings::get_global(cx)
 1364                .cursor_shape
 1365                .unwrap_or_default(),
 1366            current_line_highlight: None,
 1367            autoindent_mode: Some(AutoindentMode::EachLine),
 1368            collapse_matches: false,
 1369            workspace: None,
 1370            input_enabled: true,
 1371            use_modal_editing: mode == EditorMode::Full,
 1372            read_only: false,
 1373            use_autoclose: true,
 1374            use_auto_surround: true,
 1375            auto_replace_emoji_shortcode: false,
 1376            leader_peer_id: None,
 1377            remote_id: None,
 1378            hover_state: Default::default(),
 1379            pending_mouse_down: None,
 1380            hovered_link_state: Default::default(),
 1381            inline_completion_provider: None,
 1382            active_inline_completion: None,
 1383            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1384
 1385            gutter_hovered: false,
 1386            pixel_position_of_newest_cursor: None,
 1387            last_bounds: None,
 1388            expect_bounds_change: None,
 1389            gutter_dimensions: GutterDimensions::default(),
 1390            style: None,
 1391            show_cursor_names: false,
 1392            hovered_cursors: Default::default(),
 1393            next_editor_action_id: EditorActionId::default(),
 1394            editor_actions: Rc::default(),
 1395            show_inline_completions_override: None,
 1396            enable_inline_completions: true,
 1397            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1398            custom_context_menu: None,
 1399            show_git_blame_gutter: false,
 1400            show_git_blame_inline: false,
 1401            show_selection_menu: None,
 1402            show_git_blame_inline_delay_task: None,
 1403            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1404            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1405                .session
 1406                .restore_unsaved_buffers,
 1407            blame: None,
 1408            blame_subscription: None,
 1409            tasks: Default::default(),
 1410            _subscriptions: vec![
 1411                cx.observe(&buffer, Self::on_buffer_changed),
 1412                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1413                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1414                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1415                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1416                cx.observe_window_activation(window, |editor, window, cx| {
 1417                    let active = window.is_window_active();
 1418                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1419                        if active {
 1420                            blink_manager.enable(cx);
 1421                        } else {
 1422                            blink_manager.disable(cx);
 1423                        }
 1424                    });
 1425                }),
 1426            ],
 1427            tasks_update_task: None,
 1428            linked_edit_ranges: Default::default(),
 1429            previous_search_ranges: None,
 1430            breadcrumb_header: None,
 1431            focused_block: None,
 1432            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1433            addons: HashMap::default(),
 1434            registered_buffers: HashMap::default(),
 1435            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1436            selection_mark_mode: false,
 1437            toggle_fold_multiple_buffers: Task::ready(()),
 1438            text_style_refinement: None,
 1439        };
 1440        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1441        this._subscriptions.extend(project_subscriptions);
 1442
 1443        this.end_selection(window, cx);
 1444        this.scroll_manager.show_scrollbar(window, cx);
 1445
 1446        if mode == EditorMode::Full {
 1447            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1448            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1449
 1450            if this.git_blame_inline_enabled {
 1451                this.git_blame_inline_enabled = true;
 1452                this.start_git_blame_inline(false, window, cx);
 1453            }
 1454
 1455            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1456                if let Some(project) = this.project.as_ref() {
 1457                    let lsp_store = project.read(cx).lsp_store();
 1458                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1459                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1460                    });
 1461                    this.registered_buffers
 1462                        .insert(buffer.read(cx).remote_id(), handle);
 1463                }
 1464            }
 1465        }
 1466
 1467        this.report_editor_event("Editor Opened", None, cx);
 1468        this
 1469    }
 1470
 1471    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1472        self.mouse_context_menu
 1473            .as_ref()
 1474            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1475    }
 1476
 1477    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1478        let mut key_context = KeyContext::new_with_defaults();
 1479        key_context.add("Editor");
 1480        let mode = match self.mode {
 1481            EditorMode::SingleLine { .. } => "single_line",
 1482            EditorMode::AutoHeight { .. } => "auto_height",
 1483            EditorMode::Full => "full",
 1484        };
 1485
 1486        if EditorSettings::jupyter_enabled(cx) {
 1487            key_context.add("jupyter");
 1488        }
 1489
 1490        key_context.set("mode", mode);
 1491        if self.pending_rename.is_some() {
 1492            key_context.add("renaming");
 1493        }
 1494        match self.context_menu.borrow().as_ref() {
 1495            Some(CodeContextMenu::Completions(_)) => {
 1496                key_context.add("menu");
 1497                key_context.add("showing_completions")
 1498            }
 1499            Some(CodeContextMenu::CodeActions(_)) => {
 1500                key_context.add("menu");
 1501                key_context.add("showing_code_actions")
 1502            }
 1503            None => {}
 1504        }
 1505
 1506        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1507        if !self.focus_handle(cx).contains_focused(window, cx)
 1508            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1509        {
 1510            for addon in self.addons.values() {
 1511                addon.extend_key_context(&mut key_context, cx)
 1512            }
 1513        }
 1514
 1515        if let Some(extension) = self
 1516            .buffer
 1517            .read(cx)
 1518            .as_singleton()
 1519            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1520        {
 1521            key_context.set("extension", extension.to_string());
 1522        }
 1523
 1524        if self.has_active_inline_completion() {
 1525            key_context.add("copilot_suggestion");
 1526            key_context.add("inline_completion");
 1527        }
 1528
 1529        if self.selection_mark_mode {
 1530            key_context.add("selection_mode");
 1531        }
 1532
 1533        key_context
 1534    }
 1535
 1536    pub fn new_file(
 1537        workspace: &mut Workspace,
 1538        _: &workspace::NewFile,
 1539        window: &mut Window,
 1540        cx: &mut Context<Workspace>,
 1541    ) {
 1542        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1543            "Failed to create buffer",
 1544            window,
 1545            cx,
 1546            |e, _, _| match e.error_code() {
 1547                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1548                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1549                e.error_tag("required").unwrap_or("the latest version")
 1550            )),
 1551                _ => None,
 1552            },
 1553        );
 1554    }
 1555
 1556    pub fn new_in_workspace(
 1557        workspace: &mut Workspace,
 1558        window: &mut Window,
 1559        cx: &mut Context<Workspace>,
 1560    ) -> Task<Result<Entity<Editor>>> {
 1561        let project = workspace.project().clone();
 1562        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1563
 1564        cx.spawn_in(window, |workspace, mut cx| async move {
 1565            let buffer = create.await?;
 1566            workspace.update_in(&mut cx, |workspace, window, cx| {
 1567                let editor =
 1568                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1569                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1570                editor
 1571            })
 1572        })
 1573    }
 1574
 1575    fn new_file_vertical(
 1576        workspace: &mut Workspace,
 1577        _: &workspace::NewFileSplitVertical,
 1578        window: &mut Window,
 1579        cx: &mut Context<Workspace>,
 1580    ) {
 1581        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1582    }
 1583
 1584    fn new_file_horizontal(
 1585        workspace: &mut Workspace,
 1586        _: &workspace::NewFileSplitHorizontal,
 1587        window: &mut Window,
 1588        cx: &mut Context<Workspace>,
 1589    ) {
 1590        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1591    }
 1592
 1593    fn new_file_in_direction(
 1594        workspace: &mut Workspace,
 1595        direction: SplitDirection,
 1596        window: &mut Window,
 1597        cx: &mut Context<Workspace>,
 1598    ) {
 1599        let project = workspace.project().clone();
 1600        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1601
 1602        cx.spawn_in(window, |workspace, mut cx| async move {
 1603            let buffer = create.await?;
 1604            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1605                workspace.split_item(
 1606                    direction,
 1607                    Box::new(
 1608                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1609                    ),
 1610                    window,
 1611                    cx,
 1612                )
 1613            })?;
 1614            anyhow::Ok(())
 1615        })
 1616        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1617            match e.error_code() {
 1618                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1619                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1620                e.error_tag("required").unwrap_or("the latest version")
 1621            )),
 1622                _ => None,
 1623            }
 1624        });
 1625    }
 1626
 1627    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1628        self.leader_peer_id
 1629    }
 1630
 1631    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1632        &self.buffer
 1633    }
 1634
 1635    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1636        self.workspace.as_ref()?.0.upgrade()
 1637    }
 1638
 1639    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1640        self.buffer().read(cx).title(cx)
 1641    }
 1642
 1643    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1644        let git_blame_gutter_max_author_length = self
 1645            .render_git_blame_gutter(cx)
 1646            .then(|| {
 1647                if let Some(blame) = self.blame.as_ref() {
 1648                    let max_author_length =
 1649                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1650                    Some(max_author_length)
 1651                } else {
 1652                    None
 1653                }
 1654            })
 1655            .flatten();
 1656
 1657        EditorSnapshot {
 1658            mode: self.mode,
 1659            show_gutter: self.show_gutter,
 1660            show_line_numbers: self.show_line_numbers,
 1661            show_git_diff_gutter: self.show_git_diff_gutter,
 1662            show_code_actions: self.show_code_actions,
 1663            show_runnables: self.show_runnables,
 1664            git_blame_gutter_max_author_length,
 1665            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1666            scroll_anchor: self.scroll_manager.anchor(),
 1667            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1668            placeholder_text: self.placeholder_text.clone(),
 1669            is_focused: self.focus_handle.is_focused(window),
 1670            current_line_highlight: self
 1671                .current_line_highlight
 1672                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1673            gutter_hovered: self.gutter_hovered,
 1674        }
 1675    }
 1676
 1677    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1678        self.buffer.read(cx).language_at(point, cx)
 1679    }
 1680
 1681    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1682        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1683    }
 1684
 1685    pub fn active_excerpt(
 1686        &self,
 1687        cx: &App,
 1688    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1689        self.buffer
 1690            .read(cx)
 1691            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1692    }
 1693
 1694    pub fn mode(&self) -> EditorMode {
 1695        self.mode
 1696    }
 1697
 1698    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1699        self.collaboration_hub.as_deref()
 1700    }
 1701
 1702    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1703        self.collaboration_hub = Some(hub);
 1704    }
 1705
 1706    pub fn set_custom_context_menu(
 1707        &mut self,
 1708        f: impl 'static
 1709            + Fn(
 1710                &mut Self,
 1711                DisplayPoint,
 1712                &mut Window,
 1713                &mut Context<Self>,
 1714            ) -> Option<Entity<ui::ContextMenu>>,
 1715    ) {
 1716        self.custom_context_menu = Some(Box::new(f))
 1717    }
 1718
 1719    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1720        self.completion_provider = provider;
 1721    }
 1722
 1723    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1724        self.semantics_provider.clone()
 1725    }
 1726
 1727    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1728        self.semantics_provider = provider;
 1729    }
 1730
 1731    pub fn set_inline_completion_provider<T>(
 1732        &mut self,
 1733        provider: Option<Entity<T>>,
 1734        window: &mut Window,
 1735        cx: &mut Context<Self>,
 1736    ) where
 1737        T: InlineCompletionProvider,
 1738    {
 1739        self.inline_completion_provider =
 1740            provider.map(|provider| RegisteredInlineCompletionProvider {
 1741                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1742                    if this.focus_handle.is_focused(window) {
 1743                        this.update_visible_inline_completion(window, cx);
 1744                    }
 1745                }),
 1746                provider: Arc::new(provider),
 1747            });
 1748        self.refresh_inline_completion(false, false, window, cx);
 1749    }
 1750
 1751    pub fn placeholder_text(&self) -> Option<&str> {
 1752        self.placeholder_text.as_deref()
 1753    }
 1754
 1755    pub fn set_placeholder_text(
 1756        &mut self,
 1757        placeholder_text: impl Into<Arc<str>>,
 1758        cx: &mut Context<Self>,
 1759    ) {
 1760        let placeholder_text = Some(placeholder_text.into());
 1761        if self.placeholder_text != placeholder_text {
 1762            self.placeholder_text = placeholder_text;
 1763            cx.notify();
 1764        }
 1765    }
 1766
 1767    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1768        self.cursor_shape = cursor_shape;
 1769
 1770        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1771        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1772
 1773        cx.notify();
 1774    }
 1775
 1776    pub fn set_current_line_highlight(
 1777        &mut self,
 1778        current_line_highlight: Option<CurrentLineHighlight>,
 1779    ) {
 1780        self.current_line_highlight = current_line_highlight;
 1781    }
 1782
 1783    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1784        self.collapse_matches = collapse_matches;
 1785    }
 1786
 1787    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1788        let buffers = self.buffer.read(cx).all_buffers();
 1789        let Some(lsp_store) = self.lsp_store(cx) else {
 1790            return;
 1791        };
 1792        lsp_store.update(cx, |lsp_store, cx| {
 1793            for buffer in buffers {
 1794                self.registered_buffers
 1795                    .entry(buffer.read(cx).remote_id())
 1796                    .or_insert_with(|| {
 1797                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1798                    });
 1799            }
 1800        })
 1801    }
 1802
 1803    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1804        if self.collapse_matches {
 1805            return range.start..range.start;
 1806        }
 1807        range.clone()
 1808    }
 1809
 1810    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1811        if self.display_map.read(cx).clip_at_line_ends != clip {
 1812            self.display_map
 1813                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1814        }
 1815    }
 1816
 1817    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1818        self.input_enabled = input_enabled;
 1819    }
 1820
 1821    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1822        self.enable_inline_completions = enabled;
 1823        if !self.enable_inline_completions {
 1824            self.take_active_inline_completion(cx);
 1825            cx.notify();
 1826        }
 1827    }
 1828
 1829    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1830        self.menu_inline_completions_policy = value;
 1831    }
 1832
 1833    pub fn set_autoindent(&mut self, autoindent: bool) {
 1834        if autoindent {
 1835            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1836        } else {
 1837            self.autoindent_mode = None;
 1838        }
 1839    }
 1840
 1841    pub fn read_only(&self, cx: &App) -> bool {
 1842        self.read_only || self.buffer.read(cx).read_only()
 1843    }
 1844
 1845    pub fn set_read_only(&mut self, read_only: bool) {
 1846        self.read_only = read_only;
 1847    }
 1848
 1849    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1850        self.use_autoclose = autoclose;
 1851    }
 1852
 1853    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1854        self.use_auto_surround = auto_surround;
 1855    }
 1856
 1857    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1858        self.auto_replace_emoji_shortcode = auto_replace;
 1859    }
 1860
 1861    pub fn toggle_inline_completions(
 1862        &mut self,
 1863        _: &ToggleInlineCompletions,
 1864        window: &mut Window,
 1865        cx: &mut Context<Self>,
 1866    ) {
 1867        if self.show_inline_completions_override.is_some() {
 1868            self.set_show_inline_completions(None, window, cx);
 1869        } else {
 1870            let cursor = self.selections.newest_anchor().head();
 1871            if let Some((buffer, cursor_buffer_position)) =
 1872                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1873            {
 1874                let show_inline_completions =
 1875                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1876                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1877            }
 1878        }
 1879    }
 1880
 1881    pub fn set_show_inline_completions(
 1882        &mut self,
 1883        show_inline_completions: Option<bool>,
 1884        window: &mut Window,
 1885        cx: &mut Context<Self>,
 1886    ) {
 1887        self.show_inline_completions_override = show_inline_completions;
 1888        self.refresh_inline_completion(false, true, window, cx);
 1889    }
 1890
 1891    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 1892        let cursor = self.selections.newest_anchor().head();
 1893        if let Some((buffer, buffer_position)) =
 1894            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1895        {
 1896            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1897        } else {
 1898            false
 1899        }
 1900    }
 1901
 1902    fn should_show_inline_completions(
 1903        &self,
 1904        buffer: &Entity<Buffer>,
 1905        buffer_position: language::Anchor,
 1906        cx: &App,
 1907    ) -> bool {
 1908        if !self.snippet_stack.is_empty() {
 1909            return false;
 1910        }
 1911
 1912        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1913            return false;
 1914        }
 1915
 1916        if let Some(provider) = self.inline_completion_provider() {
 1917            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1918                show_inline_completions
 1919            } else {
 1920                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1921            }
 1922        } else {
 1923            false
 1924        }
 1925    }
 1926
 1927    fn inline_completions_disabled_in_scope(
 1928        &self,
 1929        buffer: &Entity<Buffer>,
 1930        buffer_position: language::Anchor,
 1931        cx: &App,
 1932    ) -> bool {
 1933        let snapshot = buffer.read(cx).snapshot();
 1934        let settings = snapshot.settings_at(buffer_position, cx);
 1935
 1936        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1937            return false;
 1938        };
 1939
 1940        scope.override_name().map_or(false, |scope_name| {
 1941            settings
 1942                .inline_completions_disabled_in
 1943                .iter()
 1944                .any(|s| s == scope_name)
 1945        })
 1946    }
 1947
 1948    pub fn set_use_modal_editing(&mut self, to: bool) {
 1949        self.use_modal_editing = to;
 1950    }
 1951
 1952    pub fn use_modal_editing(&self) -> bool {
 1953        self.use_modal_editing
 1954    }
 1955
 1956    fn selections_did_change(
 1957        &mut self,
 1958        local: bool,
 1959        old_cursor_position: &Anchor,
 1960        show_completions: bool,
 1961        window: &mut Window,
 1962        cx: &mut Context<Self>,
 1963    ) {
 1964        window.invalidate_character_coordinates();
 1965
 1966        // Copy selections to primary selection buffer
 1967        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1968        if local {
 1969            let selections = self.selections.all::<usize>(cx);
 1970            let buffer_handle = self.buffer.read(cx).read(cx);
 1971
 1972            let mut text = String::new();
 1973            for (index, selection) in selections.iter().enumerate() {
 1974                let text_for_selection = buffer_handle
 1975                    .text_for_range(selection.start..selection.end)
 1976                    .collect::<String>();
 1977
 1978                text.push_str(&text_for_selection);
 1979                if index != selections.len() - 1 {
 1980                    text.push('\n');
 1981                }
 1982            }
 1983
 1984            if !text.is_empty() {
 1985                cx.write_to_primary(ClipboardItem::new_string(text));
 1986            }
 1987        }
 1988
 1989        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1990            self.buffer.update(cx, |buffer, cx| {
 1991                buffer.set_active_selections(
 1992                    &self.selections.disjoint_anchors(),
 1993                    self.selections.line_mode,
 1994                    self.cursor_shape,
 1995                    cx,
 1996                )
 1997            });
 1998        }
 1999        let display_map = self
 2000            .display_map
 2001            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2002        let buffer = &display_map.buffer_snapshot;
 2003        self.add_selections_state = None;
 2004        self.select_next_state = None;
 2005        self.select_prev_state = None;
 2006        self.select_larger_syntax_node_stack.clear();
 2007        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2008        self.snippet_stack
 2009            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2010        self.take_rename(false, window, cx);
 2011
 2012        let new_cursor_position = self.selections.newest_anchor().head();
 2013
 2014        self.push_to_nav_history(
 2015            *old_cursor_position,
 2016            Some(new_cursor_position.to_point(buffer)),
 2017            cx,
 2018        );
 2019
 2020        if local {
 2021            let new_cursor_position = self.selections.newest_anchor().head();
 2022            let mut context_menu = self.context_menu.borrow_mut();
 2023            let completion_menu = match context_menu.as_ref() {
 2024                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2025                _ => {
 2026                    *context_menu = None;
 2027                    None
 2028                }
 2029            };
 2030
 2031            if let Some(completion_menu) = completion_menu {
 2032                let cursor_position = new_cursor_position.to_offset(buffer);
 2033                let (word_range, kind) =
 2034                    buffer.surrounding_word(completion_menu.initial_position, true);
 2035                if kind == Some(CharKind::Word)
 2036                    && word_range.to_inclusive().contains(&cursor_position)
 2037                {
 2038                    let mut completion_menu = completion_menu.clone();
 2039                    drop(context_menu);
 2040
 2041                    let query = Self::completion_query(buffer, cursor_position);
 2042                    cx.spawn(move |this, mut cx| async move {
 2043                        completion_menu
 2044                            .filter(query.as_deref(), cx.background_executor().clone())
 2045                            .await;
 2046
 2047                        this.update(&mut cx, |this, cx| {
 2048                            let mut context_menu = this.context_menu.borrow_mut();
 2049                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2050                            else {
 2051                                return;
 2052                            };
 2053
 2054                            if menu.id > completion_menu.id {
 2055                                return;
 2056                            }
 2057
 2058                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2059                            drop(context_menu);
 2060                            cx.notify();
 2061                        })
 2062                    })
 2063                    .detach();
 2064
 2065                    if show_completions {
 2066                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2067                    }
 2068                } else {
 2069                    drop(context_menu);
 2070                    self.hide_context_menu(window, cx);
 2071                }
 2072            } else {
 2073                drop(context_menu);
 2074            }
 2075
 2076            hide_hover(self, cx);
 2077
 2078            if old_cursor_position.to_display_point(&display_map).row()
 2079                != new_cursor_position.to_display_point(&display_map).row()
 2080            {
 2081                self.available_code_actions.take();
 2082            }
 2083            self.refresh_code_actions(window, cx);
 2084            self.refresh_document_highlights(cx);
 2085            refresh_matching_bracket_highlights(self, window, cx);
 2086            self.update_visible_inline_completion(window, cx);
 2087            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2088            if self.git_blame_inline_enabled {
 2089                self.start_inline_blame_timer(window, cx);
 2090            }
 2091        }
 2092
 2093        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2094        cx.emit(EditorEvent::SelectionsChanged { local });
 2095
 2096        if self.selections.disjoint_anchors().len() == 1 {
 2097            cx.emit(SearchEvent::ActiveMatchChanged)
 2098        }
 2099        cx.notify();
 2100    }
 2101
 2102    pub fn change_selections<R>(
 2103        &mut self,
 2104        autoscroll: Option<Autoscroll>,
 2105        window: &mut Window,
 2106        cx: &mut Context<Self>,
 2107        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2108    ) -> R {
 2109        self.change_selections_inner(autoscroll, true, window, cx, change)
 2110    }
 2111
 2112    pub fn change_selections_inner<R>(
 2113        &mut self,
 2114        autoscroll: Option<Autoscroll>,
 2115        request_completions: bool,
 2116        window: &mut Window,
 2117        cx: &mut Context<Self>,
 2118        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2119    ) -> R {
 2120        let old_cursor_position = self.selections.newest_anchor().head();
 2121        self.push_to_selection_history();
 2122
 2123        let (changed, result) = self.selections.change_with(cx, change);
 2124
 2125        if changed {
 2126            if let Some(autoscroll) = autoscroll {
 2127                self.request_autoscroll(autoscroll, cx);
 2128            }
 2129            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2130
 2131            if self.should_open_signature_help_automatically(
 2132                &old_cursor_position,
 2133                self.signature_help_state.backspace_pressed(),
 2134                cx,
 2135            ) {
 2136                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2137            }
 2138            self.signature_help_state.set_backspace_pressed(false);
 2139        }
 2140
 2141        result
 2142    }
 2143
 2144    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2145    where
 2146        I: IntoIterator<Item = (Range<S>, T)>,
 2147        S: ToOffset,
 2148        T: Into<Arc<str>>,
 2149    {
 2150        if self.read_only(cx) {
 2151            return;
 2152        }
 2153
 2154        self.buffer
 2155            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2156    }
 2157
 2158    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2159    where
 2160        I: IntoIterator<Item = (Range<S>, T)>,
 2161        S: ToOffset,
 2162        T: Into<Arc<str>>,
 2163    {
 2164        if self.read_only(cx) {
 2165            return;
 2166        }
 2167
 2168        self.buffer.update(cx, |buffer, cx| {
 2169            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2170        });
 2171    }
 2172
 2173    pub fn edit_with_block_indent<I, S, T>(
 2174        &mut self,
 2175        edits: I,
 2176        original_indent_columns: Vec<u32>,
 2177        cx: &mut Context<Self>,
 2178    ) where
 2179        I: IntoIterator<Item = (Range<S>, T)>,
 2180        S: ToOffset,
 2181        T: Into<Arc<str>>,
 2182    {
 2183        if self.read_only(cx) {
 2184            return;
 2185        }
 2186
 2187        self.buffer.update(cx, |buffer, cx| {
 2188            buffer.edit(
 2189                edits,
 2190                Some(AutoindentMode::Block {
 2191                    original_indent_columns,
 2192                }),
 2193                cx,
 2194            )
 2195        });
 2196    }
 2197
 2198    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2199        self.hide_context_menu(window, cx);
 2200
 2201        match phase {
 2202            SelectPhase::Begin {
 2203                position,
 2204                add,
 2205                click_count,
 2206            } => self.begin_selection(position, add, click_count, window, cx),
 2207            SelectPhase::BeginColumnar {
 2208                position,
 2209                goal_column,
 2210                reset,
 2211            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2212            SelectPhase::Extend {
 2213                position,
 2214                click_count,
 2215            } => self.extend_selection(position, click_count, window, cx),
 2216            SelectPhase::Update {
 2217                position,
 2218                goal_column,
 2219                scroll_delta,
 2220            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2221            SelectPhase::End => self.end_selection(window, cx),
 2222        }
 2223    }
 2224
 2225    fn extend_selection(
 2226        &mut self,
 2227        position: DisplayPoint,
 2228        click_count: usize,
 2229        window: &mut Window,
 2230        cx: &mut Context<Self>,
 2231    ) {
 2232        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2233        let tail = self.selections.newest::<usize>(cx).tail();
 2234        self.begin_selection(position, false, click_count, window, cx);
 2235
 2236        let position = position.to_offset(&display_map, Bias::Left);
 2237        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2238
 2239        let mut pending_selection = self
 2240            .selections
 2241            .pending_anchor()
 2242            .expect("extend_selection not called with pending selection");
 2243        if position >= tail {
 2244            pending_selection.start = tail_anchor;
 2245        } else {
 2246            pending_selection.end = tail_anchor;
 2247            pending_selection.reversed = true;
 2248        }
 2249
 2250        let mut pending_mode = self.selections.pending_mode().unwrap();
 2251        match &mut pending_mode {
 2252            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2253            _ => {}
 2254        }
 2255
 2256        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2257            s.set_pending(pending_selection, pending_mode)
 2258        });
 2259    }
 2260
 2261    fn begin_selection(
 2262        &mut self,
 2263        position: DisplayPoint,
 2264        add: bool,
 2265        click_count: usize,
 2266        window: &mut Window,
 2267        cx: &mut Context<Self>,
 2268    ) {
 2269        if !self.focus_handle.is_focused(window) {
 2270            self.last_focused_descendant = None;
 2271            window.focus(&self.focus_handle);
 2272        }
 2273
 2274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2275        let buffer = &display_map.buffer_snapshot;
 2276        let newest_selection = self.selections.newest_anchor().clone();
 2277        let position = display_map.clip_point(position, Bias::Left);
 2278
 2279        let start;
 2280        let end;
 2281        let mode;
 2282        let mut auto_scroll;
 2283        match click_count {
 2284            1 => {
 2285                start = buffer.anchor_before(position.to_point(&display_map));
 2286                end = start;
 2287                mode = SelectMode::Character;
 2288                auto_scroll = true;
 2289            }
 2290            2 => {
 2291                let range = movement::surrounding_word(&display_map, position);
 2292                start = buffer.anchor_before(range.start.to_point(&display_map));
 2293                end = buffer.anchor_before(range.end.to_point(&display_map));
 2294                mode = SelectMode::Word(start..end);
 2295                auto_scroll = true;
 2296            }
 2297            3 => {
 2298                let position = display_map
 2299                    .clip_point(position, Bias::Left)
 2300                    .to_point(&display_map);
 2301                let line_start = display_map.prev_line_boundary(position).0;
 2302                let next_line_start = buffer.clip_point(
 2303                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2304                    Bias::Left,
 2305                );
 2306                start = buffer.anchor_before(line_start);
 2307                end = buffer.anchor_before(next_line_start);
 2308                mode = SelectMode::Line(start..end);
 2309                auto_scroll = true;
 2310            }
 2311            _ => {
 2312                start = buffer.anchor_before(0);
 2313                end = buffer.anchor_before(buffer.len());
 2314                mode = SelectMode::All;
 2315                auto_scroll = false;
 2316            }
 2317        }
 2318        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2319
 2320        let point_to_delete: Option<usize> = {
 2321            let selected_points: Vec<Selection<Point>> =
 2322                self.selections.disjoint_in_range(start..end, cx);
 2323
 2324            if !add || click_count > 1 {
 2325                None
 2326            } else if !selected_points.is_empty() {
 2327                Some(selected_points[0].id)
 2328            } else {
 2329                let clicked_point_already_selected =
 2330                    self.selections.disjoint.iter().find(|selection| {
 2331                        selection.start.to_point(buffer) == start.to_point(buffer)
 2332                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2333                    });
 2334
 2335                clicked_point_already_selected.map(|selection| selection.id)
 2336            }
 2337        };
 2338
 2339        let selections_count = self.selections.count();
 2340
 2341        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2342            if let Some(point_to_delete) = point_to_delete {
 2343                s.delete(point_to_delete);
 2344
 2345                if selections_count == 1 {
 2346                    s.set_pending_anchor_range(start..end, mode);
 2347                }
 2348            } else {
 2349                if !add {
 2350                    s.clear_disjoint();
 2351                } else if click_count > 1 {
 2352                    s.delete(newest_selection.id)
 2353                }
 2354
 2355                s.set_pending_anchor_range(start..end, mode);
 2356            }
 2357        });
 2358    }
 2359
 2360    fn begin_columnar_selection(
 2361        &mut self,
 2362        position: DisplayPoint,
 2363        goal_column: u32,
 2364        reset: bool,
 2365        window: &mut Window,
 2366        cx: &mut Context<Self>,
 2367    ) {
 2368        if !self.focus_handle.is_focused(window) {
 2369            self.last_focused_descendant = None;
 2370            window.focus(&self.focus_handle);
 2371        }
 2372
 2373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2374
 2375        if reset {
 2376            let pointer_position = display_map
 2377                .buffer_snapshot
 2378                .anchor_before(position.to_point(&display_map));
 2379
 2380            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2381                s.clear_disjoint();
 2382                s.set_pending_anchor_range(
 2383                    pointer_position..pointer_position,
 2384                    SelectMode::Character,
 2385                );
 2386            });
 2387        }
 2388
 2389        let tail = self.selections.newest::<Point>(cx).tail();
 2390        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2391
 2392        if !reset {
 2393            self.select_columns(
 2394                tail.to_display_point(&display_map),
 2395                position,
 2396                goal_column,
 2397                &display_map,
 2398                window,
 2399                cx,
 2400            );
 2401        }
 2402    }
 2403
 2404    fn update_selection(
 2405        &mut self,
 2406        position: DisplayPoint,
 2407        goal_column: u32,
 2408        scroll_delta: gpui::Point<f32>,
 2409        window: &mut Window,
 2410        cx: &mut Context<Self>,
 2411    ) {
 2412        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2413
 2414        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2415            let tail = tail.to_display_point(&display_map);
 2416            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2417        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2418            let buffer = self.buffer.read(cx).snapshot(cx);
 2419            let head;
 2420            let tail;
 2421            let mode = self.selections.pending_mode().unwrap();
 2422            match &mode {
 2423                SelectMode::Character => {
 2424                    head = position.to_point(&display_map);
 2425                    tail = pending.tail().to_point(&buffer);
 2426                }
 2427                SelectMode::Word(original_range) => {
 2428                    let original_display_range = original_range.start.to_display_point(&display_map)
 2429                        ..original_range.end.to_display_point(&display_map);
 2430                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2431                        ..original_display_range.end.to_point(&display_map);
 2432                    if movement::is_inside_word(&display_map, position)
 2433                        || original_display_range.contains(&position)
 2434                    {
 2435                        let word_range = movement::surrounding_word(&display_map, position);
 2436                        if word_range.start < original_display_range.start {
 2437                            head = word_range.start.to_point(&display_map);
 2438                        } else {
 2439                            head = word_range.end.to_point(&display_map);
 2440                        }
 2441                    } else {
 2442                        head = position.to_point(&display_map);
 2443                    }
 2444
 2445                    if head <= original_buffer_range.start {
 2446                        tail = original_buffer_range.end;
 2447                    } else {
 2448                        tail = original_buffer_range.start;
 2449                    }
 2450                }
 2451                SelectMode::Line(original_range) => {
 2452                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2453
 2454                    let position = display_map
 2455                        .clip_point(position, Bias::Left)
 2456                        .to_point(&display_map);
 2457                    let line_start = display_map.prev_line_boundary(position).0;
 2458                    let next_line_start = buffer.clip_point(
 2459                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2460                        Bias::Left,
 2461                    );
 2462
 2463                    if line_start < original_range.start {
 2464                        head = line_start
 2465                    } else {
 2466                        head = next_line_start
 2467                    }
 2468
 2469                    if head <= original_range.start {
 2470                        tail = original_range.end;
 2471                    } else {
 2472                        tail = original_range.start;
 2473                    }
 2474                }
 2475                SelectMode::All => {
 2476                    return;
 2477                }
 2478            };
 2479
 2480            if head < tail {
 2481                pending.start = buffer.anchor_before(head);
 2482                pending.end = buffer.anchor_before(tail);
 2483                pending.reversed = true;
 2484            } else {
 2485                pending.start = buffer.anchor_before(tail);
 2486                pending.end = buffer.anchor_before(head);
 2487                pending.reversed = false;
 2488            }
 2489
 2490            self.change_selections(None, window, cx, |s| {
 2491                s.set_pending(pending, mode);
 2492            });
 2493        } else {
 2494            log::error!("update_selection dispatched with no pending selection");
 2495            return;
 2496        }
 2497
 2498        self.apply_scroll_delta(scroll_delta, window, cx);
 2499        cx.notify();
 2500    }
 2501
 2502    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2503        self.columnar_selection_tail.take();
 2504        if self.selections.pending_anchor().is_some() {
 2505            let selections = self.selections.all::<usize>(cx);
 2506            self.change_selections(None, window, cx, |s| {
 2507                s.select(selections);
 2508                s.clear_pending();
 2509            });
 2510        }
 2511    }
 2512
 2513    fn select_columns(
 2514        &mut self,
 2515        tail: DisplayPoint,
 2516        head: DisplayPoint,
 2517        goal_column: u32,
 2518        display_map: &DisplaySnapshot,
 2519        window: &mut Window,
 2520        cx: &mut Context<Self>,
 2521    ) {
 2522        let start_row = cmp::min(tail.row(), head.row());
 2523        let end_row = cmp::max(tail.row(), head.row());
 2524        let start_column = cmp::min(tail.column(), goal_column);
 2525        let end_column = cmp::max(tail.column(), goal_column);
 2526        let reversed = start_column < tail.column();
 2527
 2528        let selection_ranges = (start_row.0..=end_row.0)
 2529            .map(DisplayRow)
 2530            .filter_map(|row| {
 2531                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2532                    let start = display_map
 2533                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2534                        .to_point(display_map);
 2535                    let end = display_map
 2536                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2537                        .to_point(display_map);
 2538                    if reversed {
 2539                        Some(end..start)
 2540                    } else {
 2541                        Some(start..end)
 2542                    }
 2543                } else {
 2544                    None
 2545                }
 2546            })
 2547            .collect::<Vec<_>>();
 2548
 2549        self.change_selections(None, window, cx, |s| {
 2550            s.select_ranges(selection_ranges);
 2551        });
 2552        cx.notify();
 2553    }
 2554
 2555    pub fn has_pending_nonempty_selection(&self) -> bool {
 2556        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2557            Some(Selection { start, end, .. }) => start != end,
 2558            None => false,
 2559        };
 2560
 2561        pending_nonempty_selection
 2562            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2563    }
 2564
 2565    pub fn has_pending_selection(&self) -> bool {
 2566        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2567    }
 2568
 2569    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2570        self.selection_mark_mode = false;
 2571
 2572        if self.clear_expanded_diff_hunks(cx) {
 2573            cx.notify();
 2574            return;
 2575        }
 2576        if self.dismiss_menus_and_popups(true, window, cx) {
 2577            return;
 2578        }
 2579
 2580        if self.mode == EditorMode::Full
 2581            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2582        {
 2583            return;
 2584        }
 2585
 2586        cx.propagate();
 2587    }
 2588
 2589    pub fn dismiss_menus_and_popups(
 2590        &mut self,
 2591        should_report_inline_completion_event: bool,
 2592        window: &mut Window,
 2593        cx: &mut Context<Self>,
 2594    ) -> bool {
 2595        if self.take_rename(false, window, cx).is_some() {
 2596            return true;
 2597        }
 2598
 2599        if hide_hover(self, cx) {
 2600            return true;
 2601        }
 2602
 2603        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2604            return true;
 2605        }
 2606
 2607        if self.hide_context_menu(window, cx).is_some() {
 2608            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2609                self.update_visible_inline_completion(window, cx);
 2610            }
 2611            return true;
 2612        }
 2613
 2614        if self.mouse_context_menu.take().is_some() {
 2615            return true;
 2616        }
 2617
 2618        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2619            return true;
 2620        }
 2621
 2622        if self.snippet_stack.pop().is_some() {
 2623            return true;
 2624        }
 2625
 2626        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2627            self.dismiss_diagnostics(cx);
 2628            return true;
 2629        }
 2630
 2631        false
 2632    }
 2633
 2634    fn linked_editing_ranges_for(
 2635        &self,
 2636        selection: Range<text::Anchor>,
 2637        cx: &App,
 2638    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2639        if self.linked_edit_ranges.is_empty() {
 2640            return None;
 2641        }
 2642        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2643            selection.end.buffer_id.and_then(|end_buffer_id| {
 2644                if selection.start.buffer_id != Some(end_buffer_id) {
 2645                    return None;
 2646                }
 2647                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2648                let snapshot = buffer.read(cx).snapshot();
 2649                self.linked_edit_ranges
 2650                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2651                    .map(|ranges| (ranges, snapshot, buffer))
 2652            })?;
 2653        use text::ToOffset as TO;
 2654        // find offset from the start of current range to current cursor position
 2655        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2656
 2657        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2658        let start_difference = start_offset - start_byte_offset;
 2659        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2660        let end_difference = end_offset - start_byte_offset;
 2661        // Current range has associated linked ranges.
 2662        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2663        for range in linked_ranges.iter() {
 2664            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2665            let end_offset = start_offset + end_difference;
 2666            let start_offset = start_offset + start_difference;
 2667            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2668                continue;
 2669            }
 2670            if self.selections.disjoint_anchor_ranges().any(|s| {
 2671                if s.start.buffer_id != selection.start.buffer_id
 2672                    || s.end.buffer_id != selection.end.buffer_id
 2673                {
 2674                    return false;
 2675                }
 2676                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2677                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2678            }) {
 2679                continue;
 2680            }
 2681            let start = buffer_snapshot.anchor_after(start_offset);
 2682            let end = buffer_snapshot.anchor_after(end_offset);
 2683            linked_edits
 2684                .entry(buffer.clone())
 2685                .or_default()
 2686                .push(start..end);
 2687        }
 2688        Some(linked_edits)
 2689    }
 2690
 2691    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2692        let text: Arc<str> = text.into();
 2693
 2694        if self.read_only(cx) {
 2695            return;
 2696        }
 2697
 2698        let selections = self.selections.all_adjusted(cx);
 2699        let mut bracket_inserted = false;
 2700        let mut edits = Vec::new();
 2701        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2702        let mut new_selections = Vec::with_capacity(selections.len());
 2703        let mut new_autoclose_regions = Vec::new();
 2704        let snapshot = self.buffer.read(cx).read(cx);
 2705
 2706        for (selection, autoclose_region) in
 2707            self.selections_with_autoclose_regions(selections, &snapshot)
 2708        {
 2709            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2710                // Determine if the inserted text matches the opening or closing
 2711                // bracket of any of this language's bracket pairs.
 2712                let mut bracket_pair = None;
 2713                let mut is_bracket_pair_start = false;
 2714                let mut is_bracket_pair_end = false;
 2715                if !text.is_empty() {
 2716                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2717                    //  and they are removing the character that triggered IME popup.
 2718                    for (pair, enabled) in scope.brackets() {
 2719                        if !pair.close && !pair.surround {
 2720                            continue;
 2721                        }
 2722
 2723                        if enabled && pair.start.ends_with(text.as_ref()) {
 2724                            let prefix_len = pair.start.len() - text.len();
 2725                            let preceding_text_matches_prefix = prefix_len == 0
 2726                                || (selection.start.column >= (prefix_len as u32)
 2727                                    && snapshot.contains_str_at(
 2728                                        Point::new(
 2729                                            selection.start.row,
 2730                                            selection.start.column - (prefix_len as u32),
 2731                                        ),
 2732                                        &pair.start[..prefix_len],
 2733                                    ));
 2734                            if preceding_text_matches_prefix {
 2735                                bracket_pair = Some(pair.clone());
 2736                                is_bracket_pair_start = true;
 2737                                break;
 2738                            }
 2739                        }
 2740                        if pair.end.as_str() == text.as_ref() {
 2741                            bracket_pair = Some(pair.clone());
 2742                            is_bracket_pair_end = true;
 2743                            break;
 2744                        }
 2745                    }
 2746                }
 2747
 2748                if let Some(bracket_pair) = bracket_pair {
 2749                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2750                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2751                    let auto_surround =
 2752                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2753                    if selection.is_empty() {
 2754                        if is_bracket_pair_start {
 2755                            // If the inserted text is a suffix of an opening bracket and the
 2756                            // selection is preceded by the rest of the opening bracket, then
 2757                            // insert the closing bracket.
 2758                            let following_text_allows_autoclose = snapshot
 2759                                .chars_at(selection.start)
 2760                                .next()
 2761                                .map_or(true, |c| scope.should_autoclose_before(c));
 2762
 2763                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2764                                && bracket_pair.start.len() == 1
 2765                            {
 2766                                let target = bracket_pair.start.chars().next().unwrap();
 2767                                let current_line_count = snapshot
 2768                                    .reversed_chars_at(selection.start)
 2769                                    .take_while(|&c| c != '\n')
 2770                                    .filter(|&c| c == target)
 2771                                    .count();
 2772                                current_line_count % 2 == 1
 2773                            } else {
 2774                                false
 2775                            };
 2776
 2777                            if autoclose
 2778                                && bracket_pair.close
 2779                                && following_text_allows_autoclose
 2780                                && !is_closing_quote
 2781                            {
 2782                                let anchor = snapshot.anchor_before(selection.end);
 2783                                new_selections.push((selection.map(|_| anchor), text.len()));
 2784                                new_autoclose_regions.push((
 2785                                    anchor,
 2786                                    text.len(),
 2787                                    selection.id,
 2788                                    bracket_pair.clone(),
 2789                                ));
 2790                                edits.push((
 2791                                    selection.range(),
 2792                                    format!("{}{}", text, bracket_pair.end).into(),
 2793                                ));
 2794                                bracket_inserted = true;
 2795                                continue;
 2796                            }
 2797                        }
 2798
 2799                        if let Some(region) = autoclose_region {
 2800                            // If the selection is followed by an auto-inserted closing bracket,
 2801                            // then don't insert that closing bracket again; just move the selection
 2802                            // past the closing bracket.
 2803                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2804                                && text.as_ref() == region.pair.end.as_str();
 2805                            if should_skip {
 2806                                let anchor = snapshot.anchor_after(selection.end);
 2807                                new_selections
 2808                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2809                                continue;
 2810                            }
 2811                        }
 2812
 2813                        let always_treat_brackets_as_autoclosed = snapshot
 2814                            .settings_at(selection.start, cx)
 2815                            .always_treat_brackets_as_autoclosed;
 2816                        if always_treat_brackets_as_autoclosed
 2817                            && is_bracket_pair_end
 2818                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2819                        {
 2820                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2821                            // and the inserted text is a closing bracket and the selection is followed
 2822                            // by the closing bracket then move the selection past the closing bracket.
 2823                            let anchor = snapshot.anchor_after(selection.end);
 2824                            new_selections.push((selection.map(|_| anchor), text.len()));
 2825                            continue;
 2826                        }
 2827                    }
 2828                    // If an opening bracket is 1 character long and is typed while
 2829                    // text is selected, then surround that text with the bracket pair.
 2830                    else if auto_surround
 2831                        && bracket_pair.surround
 2832                        && is_bracket_pair_start
 2833                        && bracket_pair.start.chars().count() == 1
 2834                    {
 2835                        edits.push((selection.start..selection.start, text.clone()));
 2836                        edits.push((
 2837                            selection.end..selection.end,
 2838                            bracket_pair.end.as_str().into(),
 2839                        ));
 2840                        bracket_inserted = true;
 2841                        new_selections.push((
 2842                            Selection {
 2843                                id: selection.id,
 2844                                start: snapshot.anchor_after(selection.start),
 2845                                end: snapshot.anchor_before(selection.end),
 2846                                reversed: selection.reversed,
 2847                                goal: selection.goal,
 2848                            },
 2849                            0,
 2850                        ));
 2851                        continue;
 2852                    }
 2853                }
 2854            }
 2855
 2856            if self.auto_replace_emoji_shortcode
 2857                && selection.is_empty()
 2858                && text.as_ref().ends_with(':')
 2859            {
 2860                if let Some(possible_emoji_short_code) =
 2861                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2862                {
 2863                    if !possible_emoji_short_code.is_empty() {
 2864                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2865                            let emoji_shortcode_start = Point::new(
 2866                                selection.start.row,
 2867                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2868                            );
 2869
 2870                            // Remove shortcode from buffer
 2871                            edits.push((
 2872                                emoji_shortcode_start..selection.start,
 2873                                "".to_string().into(),
 2874                            ));
 2875                            new_selections.push((
 2876                                Selection {
 2877                                    id: selection.id,
 2878                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2879                                    end: snapshot.anchor_before(selection.start),
 2880                                    reversed: selection.reversed,
 2881                                    goal: selection.goal,
 2882                                },
 2883                                0,
 2884                            ));
 2885
 2886                            // Insert emoji
 2887                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2888                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2889                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2890
 2891                            continue;
 2892                        }
 2893                    }
 2894                }
 2895            }
 2896
 2897            // If not handling any auto-close operation, then just replace the selected
 2898            // text with the given input and move the selection to the end of the
 2899            // newly inserted text.
 2900            let anchor = snapshot.anchor_after(selection.end);
 2901            if !self.linked_edit_ranges.is_empty() {
 2902                let start_anchor = snapshot.anchor_before(selection.start);
 2903
 2904                let is_word_char = text.chars().next().map_or(true, |char| {
 2905                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2906                    classifier.is_word(char)
 2907                });
 2908
 2909                if is_word_char {
 2910                    if let Some(ranges) = self
 2911                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2912                    {
 2913                        for (buffer, edits) in ranges {
 2914                            linked_edits
 2915                                .entry(buffer.clone())
 2916                                .or_default()
 2917                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2918                        }
 2919                    }
 2920                }
 2921            }
 2922
 2923            new_selections.push((selection.map(|_| anchor), 0));
 2924            edits.push((selection.start..selection.end, text.clone()));
 2925        }
 2926
 2927        drop(snapshot);
 2928
 2929        self.transact(window, cx, |this, window, cx| {
 2930            this.buffer.update(cx, |buffer, cx| {
 2931                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2932            });
 2933            for (buffer, edits) in linked_edits {
 2934                buffer.update(cx, |buffer, cx| {
 2935                    let snapshot = buffer.snapshot();
 2936                    let edits = edits
 2937                        .into_iter()
 2938                        .map(|(range, text)| {
 2939                            use text::ToPoint as TP;
 2940                            let end_point = TP::to_point(&range.end, &snapshot);
 2941                            let start_point = TP::to_point(&range.start, &snapshot);
 2942                            (start_point..end_point, text)
 2943                        })
 2944                        .sorted_by_key(|(range, _)| range.start)
 2945                        .collect::<Vec<_>>();
 2946                    buffer.edit(edits, None, cx);
 2947                })
 2948            }
 2949            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2950            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2951            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2952            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2953                .zip(new_selection_deltas)
 2954                .map(|(selection, delta)| Selection {
 2955                    id: selection.id,
 2956                    start: selection.start + delta,
 2957                    end: selection.end + delta,
 2958                    reversed: selection.reversed,
 2959                    goal: SelectionGoal::None,
 2960                })
 2961                .collect::<Vec<_>>();
 2962
 2963            let mut i = 0;
 2964            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2965                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2966                let start = map.buffer_snapshot.anchor_before(position);
 2967                let end = map.buffer_snapshot.anchor_after(position);
 2968                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2969                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2970                        Ordering::Less => i += 1,
 2971                        Ordering::Greater => break,
 2972                        Ordering::Equal => {
 2973                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2974                                Ordering::Less => i += 1,
 2975                                Ordering::Equal => break,
 2976                                Ordering::Greater => break,
 2977                            }
 2978                        }
 2979                    }
 2980                }
 2981                this.autoclose_regions.insert(
 2982                    i,
 2983                    AutocloseRegion {
 2984                        selection_id,
 2985                        range: start..end,
 2986                        pair,
 2987                    },
 2988                );
 2989            }
 2990
 2991            let had_active_inline_completion = this.has_active_inline_completion();
 2992            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2993                s.select(new_selections)
 2994            });
 2995
 2996            if !bracket_inserted {
 2997                if let Some(on_type_format_task) =
 2998                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2999                {
 3000                    on_type_format_task.detach_and_log_err(cx);
 3001                }
 3002            }
 3003
 3004            let editor_settings = EditorSettings::get_global(cx);
 3005            if bracket_inserted
 3006                && (editor_settings.auto_signature_help
 3007                    || editor_settings.show_signature_help_after_edits)
 3008            {
 3009                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3010            }
 3011
 3012            let trigger_in_words =
 3013                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 3014            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3015            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3016            this.refresh_inline_completion(true, false, window, cx);
 3017        });
 3018    }
 3019
 3020    fn find_possible_emoji_shortcode_at_position(
 3021        snapshot: &MultiBufferSnapshot,
 3022        position: Point,
 3023    ) -> Option<String> {
 3024        let mut chars = Vec::new();
 3025        let mut found_colon = false;
 3026        for char in snapshot.reversed_chars_at(position).take(100) {
 3027            // Found a possible emoji shortcode in the middle of the buffer
 3028            if found_colon {
 3029                if char.is_whitespace() {
 3030                    chars.reverse();
 3031                    return Some(chars.iter().collect());
 3032                }
 3033                // If the previous character is not a whitespace, we are in the middle of a word
 3034                // and we only want to complete the shortcode if the word is made up of other emojis
 3035                let mut containing_word = String::new();
 3036                for ch in snapshot
 3037                    .reversed_chars_at(position)
 3038                    .skip(chars.len() + 1)
 3039                    .take(100)
 3040                {
 3041                    if ch.is_whitespace() {
 3042                        break;
 3043                    }
 3044                    containing_word.push(ch);
 3045                }
 3046                let containing_word = containing_word.chars().rev().collect::<String>();
 3047                if util::word_consists_of_emojis(containing_word.as_str()) {
 3048                    chars.reverse();
 3049                    return Some(chars.iter().collect());
 3050                }
 3051            }
 3052
 3053            if char.is_whitespace() || !char.is_ascii() {
 3054                return None;
 3055            }
 3056            if char == ':' {
 3057                found_colon = true;
 3058            } else {
 3059                chars.push(char);
 3060            }
 3061        }
 3062        // Found a possible emoji shortcode at the beginning of the buffer
 3063        chars.reverse();
 3064        Some(chars.iter().collect())
 3065    }
 3066
 3067    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3068        self.transact(window, cx, |this, window, cx| {
 3069            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3070                let selections = this.selections.all::<usize>(cx);
 3071                let multi_buffer = this.buffer.read(cx);
 3072                let buffer = multi_buffer.snapshot(cx);
 3073                selections
 3074                    .iter()
 3075                    .map(|selection| {
 3076                        let start_point = selection.start.to_point(&buffer);
 3077                        let mut indent =
 3078                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3079                        indent.len = cmp::min(indent.len, start_point.column);
 3080                        let start = selection.start;
 3081                        let end = selection.end;
 3082                        let selection_is_empty = start == end;
 3083                        let language_scope = buffer.language_scope_at(start);
 3084                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3085                            &language_scope
 3086                        {
 3087                            let leading_whitespace_len = buffer
 3088                                .reversed_chars_at(start)
 3089                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3090                                .map(|c| c.len_utf8())
 3091                                .sum::<usize>();
 3092
 3093                            let trailing_whitespace_len = buffer
 3094                                .chars_at(end)
 3095                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3096                                .map(|c| c.len_utf8())
 3097                                .sum::<usize>();
 3098
 3099                            let insert_extra_newline =
 3100                                language.brackets().any(|(pair, enabled)| {
 3101                                    let pair_start = pair.start.trim_end();
 3102                                    let pair_end = pair.end.trim_start();
 3103
 3104                                    enabled
 3105                                        && pair.newline
 3106                                        && buffer.contains_str_at(
 3107                                            end + trailing_whitespace_len,
 3108                                            pair_end,
 3109                                        )
 3110                                        && buffer.contains_str_at(
 3111                                            (start - leading_whitespace_len)
 3112                                                .saturating_sub(pair_start.len()),
 3113                                            pair_start,
 3114                                        )
 3115                                });
 3116
 3117                            // Comment extension on newline is allowed only for cursor selections
 3118                            let comment_delimiter = maybe!({
 3119                                if !selection_is_empty {
 3120                                    return None;
 3121                                }
 3122
 3123                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3124                                    return None;
 3125                                }
 3126
 3127                                let delimiters = language.line_comment_prefixes();
 3128                                let max_len_of_delimiter =
 3129                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3130                                let (snapshot, range) =
 3131                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3132
 3133                                let mut index_of_first_non_whitespace = 0;
 3134                                let comment_candidate = snapshot
 3135                                    .chars_for_range(range)
 3136                                    .skip_while(|c| {
 3137                                        let should_skip = c.is_whitespace();
 3138                                        if should_skip {
 3139                                            index_of_first_non_whitespace += 1;
 3140                                        }
 3141                                        should_skip
 3142                                    })
 3143                                    .take(max_len_of_delimiter)
 3144                                    .collect::<String>();
 3145                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3146                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3147                                })?;
 3148                                let cursor_is_placed_after_comment_marker =
 3149                                    index_of_first_non_whitespace + comment_prefix.len()
 3150                                        <= start_point.column as usize;
 3151                                if cursor_is_placed_after_comment_marker {
 3152                                    Some(comment_prefix.clone())
 3153                                } else {
 3154                                    None
 3155                                }
 3156                            });
 3157                            (comment_delimiter, insert_extra_newline)
 3158                        } else {
 3159                            (None, false)
 3160                        };
 3161
 3162                        let capacity_for_delimiter = comment_delimiter
 3163                            .as_deref()
 3164                            .map(str::len)
 3165                            .unwrap_or_default();
 3166                        let mut new_text =
 3167                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3168                        new_text.push('\n');
 3169                        new_text.extend(indent.chars());
 3170                        if let Some(delimiter) = &comment_delimiter {
 3171                            new_text.push_str(delimiter);
 3172                        }
 3173                        if insert_extra_newline {
 3174                            new_text = new_text.repeat(2);
 3175                        }
 3176
 3177                        let anchor = buffer.anchor_after(end);
 3178                        let new_selection = selection.map(|_| anchor);
 3179                        (
 3180                            (start..end, new_text),
 3181                            (insert_extra_newline, new_selection),
 3182                        )
 3183                    })
 3184                    .unzip()
 3185            };
 3186
 3187            this.edit_with_autoindent(edits, cx);
 3188            let buffer = this.buffer.read(cx).snapshot(cx);
 3189            let new_selections = selection_fixup_info
 3190                .into_iter()
 3191                .map(|(extra_newline_inserted, new_selection)| {
 3192                    let mut cursor = new_selection.end.to_point(&buffer);
 3193                    if extra_newline_inserted {
 3194                        cursor.row -= 1;
 3195                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3196                    }
 3197                    new_selection.map(|_| cursor)
 3198                })
 3199                .collect();
 3200
 3201            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3202                s.select(new_selections)
 3203            });
 3204            this.refresh_inline_completion(true, false, window, cx);
 3205        });
 3206    }
 3207
 3208    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3209        let buffer = self.buffer.read(cx);
 3210        let snapshot = buffer.snapshot(cx);
 3211
 3212        let mut edits = Vec::new();
 3213        let mut rows = Vec::new();
 3214
 3215        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3216            let cursor = selection.head();
 3217            let row = cursor.row;
 3218
 3219            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3220
 3221            let newline = "\n".to_string();
 3222            edits.push((start_of_line..start_of_line, newline));
 3223
 3224            rows.push(row + rows_inserted as u32);
 3225        }
 3226
 3227        self.transact(window, cx, |editor, window, cx| {
 3228            editor.edit(edits, cx);
 3229
 3230            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3231                let mut index = 0;
 3232                s.move_cursors_with(|map, _, _| {
 3233                    let row = rows[index];
 3234                    index += 1;
 3235
 3236                    let point = Point::new(row, 0);
 3237                    let boundary = map.next_line_boundary(point).1;
 3238                    let clipped = map.clip_point(boundary, Bias::Left);
 3239
 3240                    (clipped, SelectionGoal::None)
 3241                });
 3242            });
 3243
 3244            let mut indent_edits = Vec::new();
 3245            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3246            for row in rows {
 3247                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3248                for (row, indent) in indents {
 3249                    if indent.len == 0 {
 3250                        continue;
 3251                    }
 3252
 3253                    let text = match indent.kind {
 3254                        IndentKind::Space => " ".repeat(indent.len as usize),
 3255                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3256                    };
 3257                    let point = Point::new(row.0, 0);
 3258                    indent_edits.push((point..point, text));
 3259                }
 3260            }
 3261            editor.edit(indent_edits, cx);
 3262        });
 3263    }
 3264
 3265    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3266        let buffer = self.buffer.read(cx);
 3267        let snapshot = buffer.snapshot(cx);
 3268
 3269        let mut edits = Vec::new();
 3270        let mut rows = Vec::new();
 3271        let mut rows_inserted = 0;
 3272
 3273        for selection in self.selections.all_adjusted(cx) {
 3274            let cursor = selection.head();
 3275            let row = cursor.row;
 3276
 3277            let point = Point::new(row + 1, 0);
 3278            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3279
 3280            let newline = "\n".to_string();
 3281            edits.push((start_of_line..start_of_line, newline));
 3282
 3283            rows_inserted += 1;
 3284            rows.push(row + rows_inserted);
 3285        }
 3286
 3287        self.transact(window, cx, |editor, window, cx| {
 3288            editor.edit(edits, cx);
 3289
 3290            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3291                let mut index = 0;
 3292                s.move_cursors_with(|map, _, _| {
 3293                    let row = rows[index];
 3294                    index += 1;
 3295
 3296                    let point = Point::new(row, 0);
 3297                    let boundary = map.next_line_boundary(point).1;
 3298                    let clipped = map.clip_point(boundary, Bias::Left);
 3299
 3300                    (clipped, SelectionGoal::None)
 3301                });
 3302            });
 3303
 3304            let mut indent_edits = Vec::new();
 3305            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3306            for row in rows {
 3307                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3308                for (row, indent) in indents {
 3309                    if indent.len == 0 {
 3310                        continue;
 3311                    }
 3312
 3313                    let text = match indent.kind {
 3314                        IndentKind::Space => " ".repeat(indent.len as usize),
 3315                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3316                    };
 3317                    let point = Point::new(row.0, 0);
 3318                    indent_edits.push((point..point, text));
 3319                }
 3320            }
 3321            editor.edit(indent_edits, cx);
 3322        });
 3323    }
 3324
 3325    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3326        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3327            original_indent_columns: Vec::new(),
 3328        });
 3329        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3330    }
 3331
 3332    fn insert_with_autoindent_mode(
 3333        &mut self,
 3334        text: &str,
 3335        autoindent_mode: Option<AutoindentMode>,
 3336        window: &mut Window,
 3337        cx: &mut Context<Self>,
 3338    ) {
 3339        if self.read_only(cx) {
 3340            return;
 3341        }
 3342
 3343        let text: Arc<str> = text.into();
 3344        self.transact(window, cx, |this, window, cx| {
 3345            let old_selections = this.selections.all_adjusted(cx);
 3346            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3347                let anchors = {
 3348                    let snapshot = buffer.read(cx);
 3349                    old_selections
 3350                        .iter()
 3351                        .map(|s| {
 3352                            let anchor = snapshot.anchor_after(s.head());
 3353                            s.map(|_| anchor)
 3354                        })
 3355                        .collect::<Vec<_>>()
 3356                };
 3357                buffer.edit(
 3358                    old_selections
 3359                        .iter()
 3360                        .map(|s| (s.start..s.end, text.clone())),
 3361                    autoindent_mode,
 3362                    cx,
 3363                );
 3364                anchors
 3365            });
 3366
 3367            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3368                s.select_anchors(selection_anchors);
 3369            });
 3370
 3371            cx.notify();
 3372        });
 3373    }
 3374
 3375    fn trigger_completion_on_input(
 3376        &mut self,
 3377        text: &str,
 3378        trigger_in_words: bool,
 3379        window: &mut Window,
 3380        cx: &mut Context<Self>,
 3381    ) {
 3382        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3383            self.show_completions(
 3384                &ShowCompletions {
 3385                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3386                },
 3387                window,
 3388                cx,
 3389            );
 3390        } else {
 3391            self.hide_context_menu(window, cx);
 3392        }
 3393    }
 3394
 3395    fn is_completion_trigger(
 3396        &self,
 3397        text: &str,
 3398        trigger_in_words: bool,
 3399        cx: &mut Context<Self>,
 3400    ) -> bool {
 3401        let position = self.selections.newest_anchor().head();
 3402        let multibuffer = self.buffer.read(cx);
 3403        let Some(buffer) = position
 3404            .buffer_id
 3405            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3406        else {
 3407            return false;
 3408        };
 3409
 3410        if let Some(completion_provider) = &self.completion_provider {
 3411            completion_provider.is_completion_trigger(
 3412                &buffer,
 3413                position.text_anchor,
 3414                text,
 3415                trigger_in_words,
 3416                cx,
 3417            )
 3418        } else {
 3419            false
 3420        }
 3421    }
 3422
 3423    /// If any empty selections is touching the start of its innermost containing autoclose
 3424    /// region, expand it to select the brackets.
 3425    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3426        let selections = self.selections.all::<usize>(cx);
 3427        let buffer = self.buffer.read(cx).read(cx);
 3428        let new_selections = self
 3429            .selections_with_autoclose_regions(selections, &buffer)
 3430            .map(|(mut selection, region)| {
 3431                if !selection.is_empty() {
 3432                    return selection;
 3433                }
 3434
 3435                if let Some(region) = region {
 3436                    let mut range = region.range.to_offset(&buffer);
 3437                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3438                        range.start -= region.pair.start.len();
 3439                        if buffer.contains_str_at(range.start, &region.pair.start)
 3440                            && buffer.contains_str_at(range.end, &region.pair.end)
 3441                        {
 3442                            range.end += region.pair.end.len();
 3443                            selection.start = range.start;
 3444                            selection.end = range.end;
 3445
 3446                            return selection;
 3447                        }
 3448                    }
 3449                }
 3450
 3451                let always_treat_brackets_as_autoclosed = buffer
 3452                    .settings_at(selection.start, cx)
 3453                    .always_treat_brackets_as_autoclosed;
 3454
 3455                if !always_treat_brackets_as_autoclosed {
 3456                    return selection;
 3457                }
 3458
 3459                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3460                    for (pair, enabled) in scope.brackets() {
 3461                        if !enabled || !pair.close {
 3462                            continue;
 3463                        }
 3464
 3465                        if buffer.contains_str_at(selection.start, &pair.end) {
 3466                            let pair_start_len = pair.start.len();
 3467                            if buffer.contains_str_at(
 3468                                selection.start.saturating_sub(pair_start_len),
 3469                                &pair.start,
 3470                            ) {
 3471                                selection.start -= pair_start_len;
 3472                                selection.end += pair.end.len();
 3473
 3474                                return selection;
 3475                            }
 3476                        }
 3477                    }
 3478                }
 3479
 3480                selection
 3481            })
 3482            .collect();
 3483
 3484        drop(buffer);
 3485        self.change_selections(None, window, cx, |selections| {
 3486            selections.select(new_selections)
 3487        });
 3488    }
 3489
 3490    /// Iterate the given selections, and for each one, find the smallest surrounding
 3491    /// autoclose region. This uses the ordering of the selections and the autoclose
 3492    /// regions to avoid repeated comparisons.
 3493    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3494        &'a self,
 3495        selections: impl IntoIterator<Item = Selection<D>>,
 3496        buffer: &'a MultiBufferSnapshot,
 3497    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3498        let mut i = 0;
 3499        let mut regions = self.autoclose_regions.as_slice();
 3500        selections.into_iter().map(move |selection| {
 3501            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3502
 3503            let mut enclosing = None;
 3504            while let Some(pair_state) = regions.get(i) {
 3505                if pair_state.range.end.to_offset(buffer) < range.start {
 3506                    regions = &regions[i + 1..];
 3507                    i = 0;
 3508                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3509                    break;
 3510                } else {
 3511                    if pair_state.selection_id == selection.id {
 3512                        enclosing = Some(pair_state);
 3513                    }
 3514                    i += 1;
 3515                }
 3516            }
 3517
 3518            (selection, enclosing)
 3519        })
 3520    }
 3521
 3522    /// Remove any autoclose regions that no longer contain their selection.
 3523    fn invalidate_autoclose_regions(
 3524        &mut self,
 3525        mut selections: &[Selection<Anchor>],
 3526        buffer: &MultiBufferSnapshot,
 3527    ) {
 3528        self.autoclose_regions.retain(|state| {
 3529            let mut i = 0;
 3530            while let Some(selection) = selections.get(i) {
 3531                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3532                    selections = &selections[1..];
 3533                    continue;
 3534                }
 3535                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3536                    break;
 3537                }
 3538                if selection.id == state.selection_id {
 3539                    return true;
 3540                } else {
 3541                    i += 1;
 3542                }
 3543            }
 3544            false
 3545        });
 3546    }
 3547
 3548    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3549        let offset = position.to_offset(buffer);
 3550        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3551        if offset > word_range.start && kind == Some(CharKind::Word) {
 3552            Some(
 3553                buffer
 3554                    .text_for_range(word_range.start..offset)
 3555                    .collect::<String>(),
 3556            )
 3557        } else {
 3558            None
 3559        }
 3560    }
 3561
 3562    pub fn toggle_inlay_hints(
 3563        &mut self,
 3564        _: &ToggleInlayHints,
 3565        _: &mut Window,
 3566        cx: &mut Context<Self>,
 3567    ) {
 3568        self.refresh_inlay_hints(
 3569            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3570            cx,
 3571        );
 3572    }
 3573
 3574    pub fn inlay_hints_enabled(&self) -> bool {
 3575        self.inlay_hint_cache.enabled
 3576    }
 3577
 3578    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3579        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3580            return;
 3581        }
 3582
 3583        let reason_description = reason.description();
 3584        let ignore_debounce = matches!(
 3585            reason,
 3586            InlayHintRefreshReason::SettingsChange(_)
 3587                | InlayHintRefreshReason::Toggle(_)
 3588                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3589        );
 3590        let (invalidate_cache, required_languages) = match reason {
 3591            InlayHintRefreshReason::Toggle(enabled) => {
 3592                self.inlay_hint_cache.enabled = enabled;
 3593                if enabled {
 3594                    (InvalidationStrategy::RefreshRequested, None)
 3595                } else {
 3596                    self.inlay_hint_cache.clear();
 3597                    self.splice_inlays(
 3598                        self.visible_inlay_hints(cx)
 3599                            .iter()
 3600                            .map(|inlay| inlay.id)
 3601                            .collect(),
 3602                        Vec::new(),
 3603                        cx,
 3604                    );
 3605                    return;
 3606                }
 3607            }
 3608            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3609                match self.inlay_hint_cache.update_settings(
 3610                    &self.buffer,
 3611                    new_settings,
 3612                    self.visible_inlay_hints(cx),
 3613                    cx,
 3614                ) {
 3615                    ControlFlow::Break(Some(InlaySplice {
 3616                        to_remove,
 3617                        to_insert,
 3618                    })) => {
 3619                        self.splice_inlays(to_remove, to_insert, cx);
 3620                        return;
 3621                    }
 3622                    ControlFlow::Break(None) => return,
 3623                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3624                }
 3625            }
 3626            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3627                if let Some(InlaySplice {
 3628                    to_remove,
 3629                    to_insert,
 3630                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3631                {
 3632                    self.splice_inlays(to_remove, to_insert, cx);
 3633                }
 3634                return;
 3635            }
 3636            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3637            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3638                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3639            }
 3640            InlayHintRefreshReason::RefreshRequested => {
 3641                (InvalidationStrategy::RefreshRequested, None)
 3642            }
 3643        };
 3644
 3645        if let Some(InlaySplice {
 3646            to_remove,
 3647            to_insert,
 3648        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3649            reason_description,
 3650            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3651            invalidate_cache,
 3652            ignore_debounce,
 3653            cx,
 3654        ) {
 3655            self.splice_inlays(to_remove, to_insert, cx);
 3656        }
 3657    }
 3658
 3659    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3660        self.display_map
 3661            .read(cx)
 3662            .current_inlays()
 3663            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3664            .cloned()
 3665            .collect()
 3666    }
 3667
 3668    pub fn excerpts_for_inlay_hints_query(
 3669        &self,
 3670        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3671        cx: &mut Context<Editor>,
 3672    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3673        let Some(project) = self.project.as_ref() else {
 3674            return HashMap::default();
 3675        };
 3676        let project = project.read(cx);
 3677        let multi_buffer = self.buffer().read(cx);
 3678        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3679        let multi_buffer_visible_start = self
 3680            .scroll_manager
 3681            .anchor()
 3682            .anchor
 3683            .to_point(&multi_buffer_snapshot);
 3684        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3685            multi_buffer_visible_start
 3686                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3687            Bias::Left,
 3688        );
 3689        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3690        multi_buffer_snapshot
 3691            .range_to_buffer_ranges(multi_buffer_visible_range)
 3692            .into_iter()
 3693            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3694            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3695                let buffer_file = project::File::from_dyn(buffer.file())?;
 3696                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3697                let worktree_entry = buffer_worktree
 3698                    .read(cx)
 3699                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3700                if worktree_entry.is_ignored {
 3701                    return None;
 3702                }
 3703
 3704                let language = buffer.language()?;
 3705                if let Some(restrict_to_languages) = restrict_to_languages {
 3706                    if !restrict_to_languages.contains(language) {
 3707                        return None;
 3708                    }
 3709                }
 3710                Some((
 3711                    excerpt_id,
 3712                    (
 3713                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3714                        buffer.version().clone(),
 3715                        excerpt_visible_range,
 3716                    ),
 3717                ))
 3718            })
 3719            .collect()
 3720    }
 3721
 3722    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3723        TextLayoutDetails {
 3724            text_system: window.text_system().clone(),
 3725            editor_style: self.style.clone().unwrap(),
 3726            rem_size: window.rem_size(),
 3727            scroll_anchor: self.scroll_manager.anchor(),
 3728            visible_rows: self.visible_line_count(),
 3729            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3730        }
 3731    }
 3732
 3733    pub fn splice_inlays(
 3734        &self,
 3735        to_remove: Vec<InlayId>,
 3736        to_insert: Vec<Inlay>,
 3737        cx: &mut Context<Self>,
 3738    ) {
 3739        self.display_map.update(cx, |display_map, cx| {
 3740            display_map.splice_inlays(to_remove, to_insert, cx)
 3741        });
 3742        cx.notify();
 3743    }
 3744
 3745    fn trigger_on_type_formatting(
 3746        &self,
 3747        input: String,
 3748        window: &mut Window,
 3749        cx: &mut Context<Self>,
 3750    ) -> Option<Task<Result<()>>> {
 3751        if input.len() != 1 {
 3752            return None;
 3753        }
 3754
 3755        let project = self.project.as_ref()?;
 3756        let position = self.selections.newest_anchor().head();
 3757        let (buffer, buffer_position) = self
 3758            .buffer
 3759            .read(cx)
 3760            .text_anchor_for_position(position, cx)?;
 3761
 3762        let settings = language_settings::language_settings(
 3763            buffer
 3764                .read(cx)
 3765                .language_at(buffer_position)
 3766                .map(|l| l.name()),
 3767            buffer.read(cx).file(),
 3768            cx,
 3769        );
 3770        if !settings.use_on_type_format {
 3771            return None;
 3772        }
 3773
 3774        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3775        // hence we do LSP request & edit on host side only — add formats to host's history.
 3776        let push_to_lsp_host_history = true;
 3777        // If this is not the host, append its history with new edits.
 3778        let push_to_client_history = project.read(cx).is_via_collab();
 3779
 3780        let on_type_formatting = project.update(cx, |project, cx| {
 3781            project.on_type_format(
 3782                buffer.clone(),
 3783                buffer_position,
 3784                input,
 3785                push_to_lsp_host_history,
 3786                cx,
 3787            )
 3788        });
 3789        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3790            if let Some(transaction) = on_type_formatting.await? {
 3791                if push_to_client_history {
 3792                    buffer
 3793                        .update(&mut cx, |buffer, _| {
 3794                            buffer.push_transaction(transaction, Instant::now());
 3795                        })
 3796                        .ok();
 3797                }
 3798                editor.update(&mut cx, |editor, cx| {
 3799                    editor.refresh_document_highlights(cx);
 3800                })?;
 3801            }
 3802            Ok(())
 3803        }))
 3804    }
 3805
 3806    pub fn show_completions(
 3807        &mut self,
 3808        options: &ShowCompletions,
 3809        window: &mut Window,
 3810        cx: &mut Context<Self>,
 3811    ) {
 3812        if self.pending_rename.is_some() {
 3813            return;
 3814        }
 3815
 3816        let Some(provider) = self.completion_provider.as_ref() else {
 3817            return;
 3818        };
 3819
 3820        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3821            return;
 3822        }
 3823
 3824        let position = self.selections.newest_anchor().head();
 3825        if position.diff_base_anchor.is_some() {
 3826            return;
 3827        }
 3828        let (buffer, buffer_position) =
 3829            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3830                output
 3831            } else {
 3832                return;
 3833            };
 3834        let show_completion_documentation = buffer
 3835            .read(cx)
 3836            .snapshot()
 3837            .settings_at(buffer_position, cx)
 3838            .show_completion_documentation;
 3839
 3840        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3841
 3842        let trigger_kind = match &options.trigger {
 3843            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3844                CompletionTriggerKind::TRIGGER_CHARACTER
 3845            }
 3846            _ => CompletionTriggerKind::INVOKED,
 3847        };
 3848        let completion_context = CompletionContext {
 3849            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3850                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3851                    Some(String::from(trigger))
 3852                } else {
 3853                    None
 3854                }
 3855            }),
 3856            trigger_kind,
 3857        };
 3858        let completions =
 3859            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3860        let sort_completions = provider.sort_completions();
 3861
 3862        let id = post_inc(&mut self.next_completion_id);
 3863        let task = cx.spawn_in(window, |editor, mut cx| {
 3864            async move {
 3865                editor.update(&mut cx, |this, _| {
 3866                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3867                })?;
 3868                let completions = completions.await.log_err();
 3869                let menu = if let Some(completions) = completions {
 3870                    let mut menu = CompletionsMenu::new(
 3871                        id,
 3872                        sort_completions,
 3873                        show_completion_documentation,
 3874                        position,
 3875                        buffer.clone(),
 3876                        completions.into(),
 3877                    );
 3878
 3879                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3880                        .await;
 3881
 3882                    menu.visible().then_some(menu)
 3883                } else {
 3884                    None
 3885                };
 3886
 3887                editor.update_in(&mut cx, |editor, window, cx| {
 3888                    match editor.context_menu.borrow().as_ref() {
 3889                        None => {}
 3890                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3891                            if prev_menu.id > id {
 3892                                return;
 3893                            }
 3894                        }
 3895                        _ => return,
 3896                    }
 3897
 3898                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3899                        let mut menu = menu.unwrap();
 3900                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3901
 3902                        if editor.show_inline_completions_in_menu(cx) {
 3903                            if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
 3904                                menu.show_inline_completion_hint(hint);
 3905                            }
 3906                        } else {
 3907                            editor.discard_inline_completion(false, cx);
 3908                        }
 3909
 3910                        *editor.context_menu.borrow_mut() =
 3911                            Some(CodeContextMenu::Completions(menu));
 3912
 3913                        cx.notify();
 3914                    } else if editor.completion_tasks.len() <= 1 {
 3915                        // If there are no more completion tasks and the last menu was
 3916                        // empty, we should hide it.
 3917                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3918                        // If it was already hidden and we don't show inline
 3919                        // completions in the menu, we should also show the
 3920                        // inline-completion when available.
 3921                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3922                            editor.update_visible_inline_completion(window, cx);
 3923                        }
 3924                    }
 3925                })?;
 3926
 3927                Ok::<_, anyhow::Error>(())
 3928            }
 3929            .log_err()
 3930        });
 3931
 3932        self.completion_tasks.push((id, task));
 3933    }
 3934
 3935    pub fn confirm_completion(
 3936        &mut self,
 3937        action: &ConfirmCompletion,
 3938        window: &mut Window,
 3939        cx: &mut Context<Self>,
 3940    ) -> Option<Task<Result<()>>> {
 3941        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3942    }
 3943
 3944    pub fn compose_completion(
 3945        &mut self,
 3946        action: &ComposeCompletion,
 3947        window: &mut Window,
 3948        cx: &mut Context<Self>,
 3949    ) -> Option<Task<Result<()>>> {
 3950        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3951    }
 3952
 3953    fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3954        let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
 3955            return;
 3956        };
 3957
 3958        let project = project.read(cx);
 3959
 3960        ZedPredictModal::toggle(
 3961            workspace,
 3962            project.user_store().clone(),
 3963            project.client().clone(),
 3964            project.fs().clone(),
 3965            window,
 3966            cx,
 3967        );
 3968    }
 3969
 3970    fn do_completion(
 3971        &mut self,
 3972        item_ix: Option<usize>,
 3973        intent: CompletionIntent,
 3974        window: &mut Window,
 3975        cx: &mut Context<Editor>,
 3976    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3977        use language::ToOffset as _;
 3978
 3979        {
 3980            let context_menu = self.context_menu.borrow();
 3981            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3982                let entries = menu.entries.borrow();
 3983                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3984                match entry {
 3985                    Some(CompletionEntry::InlineCompletionHint(
 3986                        InlineCompletionMenuHint::Loading,
 3987                    )) => return Some(Task::ready(Ok(()))),
 3988                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3989                        drop(entries);
 3990                        drop(context_menu);
 3991                        self.context_menu_next(&Default::default(), window, cx);
 3992                        return Some(Task::ready(Ok(())));
 3993                    }
 3994                    Some(CompletionEntry::InlineCompletionHint(
 3995                        InlineCompletionMenuHint::PendingTermsAcceptance,
 3996                    )) => {
 3997                        drop(entries);
 3998                        drop(context_menu);
 3999                        self.toggle_zed_predict_onboarding(window, cx);
 4000                        return Some(Task::ready(Ok(())));
 4001                    }
 4002                    _ => {}
 4003                }
 4004            }
 4005        }
 4006
 4007        let completions_menu =
 4008            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4009                menu
 4010            } else {
 4011                return None;
 4012            };
 4013
 4014        let entries = completions_menu.entries.borrow();
 4015        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4016        let mat = match mat {
 4017            CompletionEntry::InlineCompletionHint(_) => {
 4018                self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
 4019                cx.stop_propagation();
 4020                return Some(Task::ready(Ok(())));
 4021            }
 4022            CompletionEntry::Match(mat) => {
 4023                if self.show_inline_completions_in_menu(cx) {
 4024                    self.discard_inline_completion(true, cx);
 4025                }
 4026                mat
 4027            }
 4028        };
 4029        let candidate_id = mat.candidate_id;
 4030        drop(entries);
 4031
 4032        let buffer_handle = completions_menu.buffer;
 4033        let completion = completions_menu
 4034            .completions
 4035            .borrow()
 4036            .get(candidate_id)?
 4037            .clone();
 4038        cx.stop_propagation();
 4039
 4040        let snippet;
 4041        let text;
 4042
 4043        if completion.is_snippet() {
 4044            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4045            text = snippet.as_ref().unwrap().text.clone();
 4046        } else {
 4047            snippet = None;
 4048            text = completion.new_text.clone();
 4049        };
 4050        let selections = self.selections.all::<usize>(cx);
 4051        let buffer = buffer_handle.read(cx);
 4052        let old_range = completion.old_range.to_offset(buffer);
 4053        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4054
 4055        let newest_selection = self.selections.newest_anchor();
 4056        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4057            return None;
 4058        }
 4059
 4060        let lookbehind = newest_selection
 4061            .start
 4062            .text_anchor
 4063            .to_offset(buffer)
 4064            .saturating_sub(old_range.start);
 4065        let lookahead = old_range
 4066            .end
 4067            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4068        let mut common_prefix_len = old_text
 4069            .bytes()
 4070            .zip(text.bytes())
 4071            .take_while(|(a, b)| a == b)
 4072            .count();
 4073
 4074        let snapshot = self.buffer.read(cx).snapshot(cx);
 4075        let mut range_to_replace: Option<Range<isize>> = None;
 4076        let mut ranges = Vec::new();
 4077        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4078        for selection in &selections {
 4079            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4080                let start = selection.start.saturating_sub(lookbehind);
 4081                let end = selection.end + lookahead;
 4082                if selection.id == newest_selection.id {
 4083                    range_to_replace = Some(
 4084                        ((start + common_prefix_len) as isize - selection.start as isize)
 4085                            ..(end as isize - selection.start as isize),
 4086                    );
 4087                }
 4088                ranges.push(start + common_prefix_len..end);
 4089            } else {
 4090                common_prefix_len = 0;
 4091                ranges.clear();
 4092                ranges.extend(selections.iter().map(|s| {
 4093                    if s.id == newest_selection.id {
 4094                        range_to_replace = Some(
 4095                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4096                                - selection.start as isize
 4097                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4098                                    - selection.start as isize,
 4099                        );
 4100                        old_range.clone()
 4101                    } else {
 4102                        s.start..s.end
 4103                    }
 4104                }));
 4105                break;
 4106            }
 4107            if !self.linked_edit_ranges.is_empty() {
 4108                let start_anchor = snapshot.anchor_before(selection.head());
 4109                let end_anchor = snapshot.anchor_after(selection.tail());
 4110                if let Some(ranges) = self
 4111                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4112                {
 4113                    for (buffer, edits) in ranges {
 4114                        linked_edits.entry(buffer.clone()).or_default().extend(
 4115                            edits
 4116                                .into_iter()
 4117                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4118                        );
 4119                    }
 4120                }
 4121            }
 4122        }
 4123        let text = &text[common_prefix_len..];
 4124
 4125        cx.emit(EditorEvent::InputHandled {
 4126            utf16_range_to_replace: range_to_replace,
 4127            text: text.into(),
 4128        });
 4129
 4130        self.transact(window, cx, |this, window, cx| {
 4131            if let Some(mut snippet) = snippet {
 4132                snippet.text = text.to_string();
 4133                for tabstop in snippet
 4134                    .tabstops
 4135                    .iter_mut()
 4136                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4137                {
 4138                    tabstop.start -= common_prefix_len as isize;
 4139                    tabstop.end -= common_prefix_len as isize;
 4140                }
 4141
 4142                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4143            } else {
 4144                this.buffer.update(cx, |buffer, cx| {
 4145                    buffer.edit(
 4146                        ranges.iter().map(|range| (range.clone(), text)),
 4147                        this.autoindent_mode.clone(),
 4148                        cx,
 4149                    );
 4150                });
 4151            }
 4152            for (buffer, edits) in linked_edits {
 4153                buffer.update(cx, |buffer, cx| {
 4154                    let snapshot = buffer.snapshot();
 4155                    let edits = edits
 4156                        .into_iter()
 4157                        .map(|(range, text)| {
 4158                            use text::ToPoint as TP;
 4159                            let end_point = TP::to_point(&range.end, &snapshot);
 4160                            let start_point = TP::to_point(&range.start, &snapshot);
 4161                            (start_point..end_point, text)
 4162                        })
 4163                        .sorted_by_key(|(range, _)| range.start)
 4164                        .collect::<Vec<_>>();
 4165                    buffer.edit(edits, None, cx);
 4166                })
 4167            }
 4168
 4169            this.refresh_inline_completion(true, false, window, cx);
 4170        });
 4171
 4172        let show_new_completions_on_confirm = completion
 4173            .confirm
 4174            .as_ref()
 4175            .map_or(false, |confirm| confirm(intent, window, cx));
 4176        if show_new_completions_on_confirm {
 4177            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4178        }
 4179
 4180        let provider = self.completion_provider.as_ref()?;
 4181        drop(completion);
 4182        let apply_edits = provider.apply_additional_edits_for_completion(
 4183            buffer_handle,
 4184            completions_menu.completions.clone(),
 4185            candidate_id,
 4186            true,
 4187            cx,
 4188        );
 4189
 4190        let editor_settings = EditorSettings::get_global(cx);
 4191        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4192            // After the code completion is finished, users often want to know what signatures are needed.
 4193            // so we should automatically call signature_help
 4194            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4195        }
 4196
 4197        Some(cx.foreground_executor().spawn(async move {
 4198            apply_edits.await?;
 4199            Ok(())
 4200        }))
 4201    }
 4202
 4203    pub fn toggle_code_actions(
 4204        &mut self,
 4205        action: &ToggleCodeActions,
 4206        window: &mut Window,
 4207        cx: &mut Context<Self>,
 4208    ) {
 4209        let mut context_menu = self.context_menu.borrow_mut();
 4210        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4211            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4212                // Toggle if we're selecting the same one
 4213                *context_menu = None;
 4214                cx.notify();
 4215                return;
 4216            } else {
 4217                // Otherwise, clear it and start a new one
 4218                *context_menu = None;
 4219                cx.notify();
 4220            }
 4221        }
 4222        drop(context_menu);
 4223        let snapshot = self.snapshot(window, cx);
 4224        let deployed_from_indicator = action.deployed_from_indicator;
 4225        let mut task = self.code_actions_task.take();
 4226        let action = action.clone();
 4227        cx.spawn_in(window, |editor, mut cx| async move {
 4228            while let Some(prev_task) = task {
 4229                prev_task.await.log_err();
 4230                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4231            }
 4232
 4233            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4234                if editor.focus_handle.is_focused(window) {
 4235                    let multibuffer_point = action
 4236                        .deployed_from_indicator
 4237                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4238                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4239                    let (buffer, buffer_row) = snapshot
 4240                        .buffer_snapshot
 4241                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4242                        .and_then(|(buffer_snapshot, range)| {
 4243                            editor
 4244                                .buffer
 4245                                .read(cx)
 4246                                .buffer(buffer_snapshot.remote_id())
 4247                                .map(|buffer| (buffer, range.start.row))
 4248                        })?;
 4249                    let (_, code_actions) = editor
 4250                        .available_code_actions
 4251                        .clone()
 4252                        .and_then(|(location, code_actions)| {
 4253                            let snapshot = location.buffer.read(cx).snapshot();
 4254                            let point_range = location.range.to_point(&snapshot);
 4255                            let point_range = point_range.start.row..=point_range.end.row;
 4256                            if point_range.contains(&buffer_row) {
 4257                                Some((location, code_actions))
 4258                            } else {
 4259                                None
 4260                            }
 4261                        })
 4262                        .unzip();
 4263                    let buffer_id = buffer.read(cx).remote_id();
 4264                    let tasks = editor
 4265                        .tasks
 4266                        .get(&(buffer_id, buffer_row))
 4267                        .map(|t| Arc::new(t.to_owned()));
 4268                    if tasks.is_none() && code_actions.is_none() {
 4269                        return None;
 4270                    }
 4271
 4272                    editor.completion_tasks.clear();
 4273                    editor.discard_inline_completion(false, cx);
 4274                    let task_context =
 4275                        tasks
 4276                            .as_ref()
 4277                            .zip(editor.project.clone())
 4278                            .map(|(tasks, project)| {
 4279                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4280                            });
 4281
 4282                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4283                        let task_context = match task_context {
 4284                            Some(task_context) => task_context.await,
 4285                            None => None,
 4286                        };
 4287                        let resolved_tasks =
 4288                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4289                                Rc::new(ResolvedTasks {
 4290                                    templates: tasks.resolve(&task_context).collect(),
 4291                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4292                                        multibuffer_point.row,
 4293                                        tasks.column,
 4294                                    )),
 4295                                })
 4296                            });
 4297                        let spawn_straight_away = resolved_tasks
 4298                            .as_ref()
 4299                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4300                            && code_actions
 4301                                .as_ref()
 4302                                .map_or(true, |actions| actions.is_empty());
 4303                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4304                            *editor.context_menu.borrow_mut() =
 4305                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4306                                    buffer,
 4307                                    actions: CodeActionContents {
 4308                                        tasks: resolved_tasks,
 4309                                        actions: code_actions,
 4310                                    },
 4311                                    selected_item: Default::default(),
 4312                                    scroll_handle: UniformListScrollHandle::default(),
 4313                                    deployed_from_indicator,
 4314                                }));
 4315                            if spawn_straight_away {
 4316                                if let Some(task) = editor.confirm_code_action(
 4317                                    &ConfirmCodeAction { item_ix: Some(0) },
 4318                                    window,
 4319                                    cx,
 4320                                ) {
 4321                                    cx.notify();
 4322                                    return task;
 4323                                }
 4324                            }
 4325                            cx.notify();
 4326                            Task::ready(Ok(()))
 4327                        }) {
 4328                            task.await
 4329                        } else {
 4330                            Ok(())
 4331                        }
 4332                    }))
 4333                } else {
 4334                    Some(Task::ready(Ok(())))
 4335                }
 4336            })?;
 4337            if let Some(task) = spawned_test_task {
 4338                task.await?;
 4339            }
 4340
 4341            Ok::<_, anyhow::Error>(())
 4342        })
 4343        .detach_and_log_err(cx);
 4344    }
 4345
 4346    pub fn confirm_code_action(
 4347        &mut self,
 4348        action: &ConfirmCodeAction,
 4349        window: &mut Window,
 4350        cx: &mut Context<Self>,
 4351    ) -> Option<Task<Result<()>>> {
 4352        let actions_menu =
 4353            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4354                menu
 4355            } else {
 4356                return None;
 4357            };
 4358        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4359        let action = actions_menu.actions.get(action_ix)?;
 4360        let title = action.label();
 4361        let buffer = actions_menu.buffer;
 4362        let workspace = self.workspace()?;
 4363
 4364        match action {
 4365            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4366                workspace.update(cx, |workspace, cx| {
 4367                    workspace::tasks::schedule_resolved_task(
 4368                        workspace,
 4369                        task_source_kind,
 4370                        resolved_task,
 4371                        false,
 4372                        cx,
 4373                    );
 4374
 4375                    Some(Task::ready(Ok(())))
 4376                })
 4377            }
 4378            CodeActionsItem::CodeAction {
 4379                excerpt_id,
 4380                action,
 4381                provider,
 4382            } => {
 4383                let apply_code_action =
 4384                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4385                let workspace = workspace.downgrade();
 4386                Some(cx.spawn_in(window, |editor, cx| async move {
 4387                    let project_transaction = apply_code_action.await?;
 4388                    Self::open_project_transaction(
 4389                        &editor,
 4390                        workspace,
 4391                        project_transaction,
 4392                        title,
 4393                        cx,
 4394                    )
 4395                    .await
 4396                }))
 4397            }
 4398        }
 4399    }
 4400
 4401    pub async fn open_project_transaction(
 4402        this: &WeakEntity<Editor>,
 4403        workspace: WeakEntity<Workspace>,
 4404        transaction: ProjectTransaction,
 4405        title: String,
 4406        mut cx: AsyncWindowContext,
 4407    ) -> Result<()> {
 4408        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4409        cx.update(|_, cx| {
 4410            entries.sort_unstable_by_key(|(buffer, _)| {
 4411                buffer.read(cx).file().map(|f| f.path().clone())
 4412            });
 4413        })?;
 4414
 4415        // If the project transaction's edits are all contained within this editor, then
 4416        // avoid opening a new editor to display them.
 4417
 4418        if let Some((buffer, transaction)) = entries.first() {
 4419            if entries.len() == 1 {
 4420                let excerpt = this.update(&mut cx, |editor, cx| {
 4421                    editor
 4422                        .buffer()
 4423                        .read(cx)
 4424                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4425                })?;
 4426                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4427                    if excerpted_buffer == *buffer {
 4428                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4429                            let excerpt_range = excerpt_range.to_offset(buffer);
 4430                            buffer
 4431                                .edited_ranges_for_transaction::<usize>(transaction)
 4432                                .all(|range| {
 4433                                    excerpt_range.start <= range.start
 4434                                        && excerpt_range.end >= range.end
 4435                                })
 4436                        })?;
 4437
 4438                        if all_edits_within_excerpt {
 4439                            return Ok(());
 4440                        }
 4441                    }
 4442                }
 4443            }
 4444        } else {
 4445            return Ok(());
 4446        }
 4447
 4448        let mut ranges_to_highlight = Vec::new();
 4449        let excerpt_buffer = cx.new(|cx| {
 4450            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4451            for (buffer_handle, transaction) in &entries {
 4452                let buffer = buffer_handle.read(cx);
 4453                ranges_to_highlight.extend(
 4454                    multibuffer.push_excerpts_with_context_lines(
 4455                        buffer_handle.clone(),
 4456                        buffer
 4457                            .edited_ranges_for_transaction::<usize>(transaction)
 4458                            .collect(),
 4459                        DEFAULT_MULTIBUFFER_CONTEXT,
 4460                        cx,
 4461                    ),
 4462                );
 4463            }
 4464            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4465            multibuffer
 4466        })?;
 4467
 4468        workspace.update_in(&mut cx, |workspace, window, cx| {
 4469            let project = workspace.project().clone();
 4470            let editor = cx
 4471                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4472            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4473            editor.update(cx, |editor, cx| {
 4474                editor.highlight_background::<Self>(
 4475                    &ranges_to_highlight,
 4476                    |theme| theme.editor_highlighted_line_background,
 4477                    cx,
 4478                );
 4479            });
 4480        })?;
 4481
 4482        Ok(())
 4483    }
 4484
 4485    pub fn clear_code_action_providers(&mut self) {
 4486        self.code_action_providers.clear();
 4487        self.available_code_actions.take();
 4488    }
 4489
 4490    pub fn add_code_action_provider(
 4491        &mut self,
 4492        provider: Rc<dyn CodeActionProvider>,
 4493        window: &mut Window,
 4494        cx: &mut Context<Self>,
 4495    ) {
 4496        if self
 4497            .code_action_providers
 4498            .iter()
 4499            .any(|existing_provider| existing_provider.id() == provider.id())
 4500        {
 4501            return;
 4502        }
 4503
 4504        self.code_action_providers.push(provider);
 4505        self.refresh_code_actions(window, cx);
 4506    }
 4507
 4508    pub fn remove_code_action_provider(
 4509        &mut self,
 4510        id: Arc<str>,
 4511        window: &mut Window,
 4512        cx: &mut Context<Self>,
 4513    ) {
 4514        self.code_action_providers
 4515            .retain(|provider| provider.id() != id);
 4516        self.refresh_code_actions(window, cx);
 4517    }
 4518
 4519    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4520        let buffer = self.buffer.read(cx);
 4521        let newest_selection = self.selections.newest_anchor().clone();
 4522        if newest_selection.head().diff_base_anchor.is_some() {
 4523            return None;
 4524        }
 4525        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4526        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4527        if start_buffer != end_buffer {
 4528            return None;
 4529        }
 4530
 4531        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4532            cx.background_executor()
 4533                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4534                .await;
 4535
 4536            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4537                let providers = this.code_action_providers.clone();
 4538                let tasks = this
 4539                    .code_action_providers
 4540                    .iter()
 4541                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4542                    .collect::<Vec<_>>();
 4543                (providers, tasks)
 4544            })?;
 4545
 4546            let mut actions = Vec::new();
 4547            for (provider, provider_actions) in
 4548                providers.into_iter().zip(future::join_all(tasks).await)
 4549            {
 4550                if let Some(provider_actions) = provider_actions.log_err() {
 4551                    actions.extend(provider_actions.into_iter().map(|action| {
 4552                        AvailableCodeAction {
 4553                            excerpt_id: newest_selection.start.excerpt_id,
 4554                            action,
 4555                            provider: provider.clone(),
 4556                        }
 4557                    }));
 4558                }
 4559            }
 4560
 4561            this.update(&mut cx, |this, cx| {
 4562                this.available_code_actions = if actions.is_empty() {
 4563                    None
 4564                } else {
 4565                    Some((
 4566                        Location {
 4567                            buffer: start_buffer,
 4568                            range: start..end,
 4569                        },
 4570                        actions.into(),
 4571                    ))
 4572                };
 4573                cx.notify();
 4574            })
 4575        }));
 4576        None
 4577    }
 4578
 4579    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4580        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4581            self.show_git_blame_inline = false;
 4582
 4583            self.show_git_blame_inline_delay_task =
 4584                Some(cx.spawn_in(window, |this, mut cx| async move {
 4585                    cx.background_executor().timer(delay).await;
 4586
 4587                    this.update(&mut cx, |this, cx| {
 4588                        this.show_git_blame_inline = true;
 4589                        cx.notify();
 4590                    })
 4591                    .log_err();
 4592                }));
 4593        }
 4594    }
 4595
 4596    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4597        if self.pending_rename.is_some() {
 4598            return None;
 4599        }
 4600
 4601        let provider = self.semantics_provider.clone()?;
 4602        let buffer = self.buffer.read(cx);
 4603        let newest_selection = self.selections.newest_anchor().clone();
 4604        let cursor_position = newest_selection.head();
 4605        let (cursor_buffer, cursor_buffer_position) =
 4606            buffer.text_anchor_for_position(cursor_position, cx)?;
 4607        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4608        if cursor_buffer != tail_buffer {
 4609            return None;
 4610        }
 4611        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4612        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4613            cx.background_executor()
 4614                .timer(Duration::from_millis(debounce))
 4615                .await;
 4616
 4617            let highlights = if let Some(highlights) = cx
 4618                .update(|cx| {
 4619                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4620                })
 4621                .ok()
 4622                .flatten()
 4623            {
 4624                highlights.await.log_err()
 4625            } else {
 4626                None
 4627            };
 4628
 4629            if let Some(highlights) = highlights {
 4630                this.update(&mut cx, |this, cx| {
 4631                    if this.pending_rename.is_some() {
 4632                        return;
 4633                    }
 4634
 4635                    let buffer_id = cursor_position.buffer_id;
 4636                    let buffer = this.buffer.read(cx);
 4637                    if !buffer
 4638                        .text_anchor_for_position(cursor_position, cx)
 4639                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4640                    {
 4641                        return;
 4642                    }
 4643
 4644                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4645                    let mut write_ranges = Vec::new();
 4646                    let mut read_ranges = Vec::new();
 4647                    for highlight in highlights {
 4648                        for (excerpt_id, excerpt_range) in
 4649                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4650                        {
 4651                            let start = highlight
 4652                                .range
 4653                                .start
 4654                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4655                            let end = highlight
 4656                                .range
 4657                                .end
 4658                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4659                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4660                                continue;
 4661                            }
 4662
 4663                            let range = Anchor {
 4664                                buffer_id,
 4665                                excerpt_id,
 4666                                text_anchor: start,
 4667                                diff_base_anchor: None,
 4668                            }..Anchor {
 4669                                buffer_id,
 4670                                excerpt_id,
 4671                                text_anchor: end,
 4672                                diff_base_anchor: None,
 4673                            };
 4674                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4675                                write_ranges.push(range);
 4676                            } else {
 4677                                read_ranges.push(range);
 4678                            }
 4679                        }
 4680                    }
 4681
 4682                    this.highlight_background::<DocumentHighlightRead>(
 4683                        &read_ranges,
 4684                        |theme| theme.editor_document_highlight_read_background,
 4685                        cx,
 4686                    );
 4687                    this.highlight_background::<DocumentHighlightWrite>(
 4688                        &write_ranges,
 4689                        |theme| theme.editor_document_highlight_write_background,
 4690                        cx,
 4691                    );
 4692                    cx.notify();
 4693                })
 4694                .log_err();
 4695            }
 4696        }));
 4697        None
 4698    }
 4699
 4700    pub fn refresh_inline_completion(
 4701        &mut self,
 4702        debounce: bool,
 4703        user_requested: bool,
 4704        window: &mut Window,
 4705        cx: &mut Context<Self>,
 4706    ) -> Option<()> {
 4707        let provider = self.inline_completion_provider()?;
 4708        let cursor = self.selections.newest_anchor().head();
 4709        let (buffer, cursor_buffer_position) =
 4710            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4711
 4712        if !user_requested
 4713            && (!self.enable_inline_completions
 4714                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4715                || !self.is_focused(window)
 4716                || buffer.read(cx).is_empty())
 4717        {
 4718            self.discard_inline_completion(false, cx);
 4719            return None;
 4720        }
 4721
 4722        self.update_visible_inline_completion(window, cx);
 4723        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4724        Some(())
 4725    }
 4726
 4727    fn cycle_inline_completion(
 4728        &mut self,
 4729        direction: Direction,
 4730        window: &mut Window,
 4731        cx: &mut Context<Self>,
 4732    ) -> Option<()> {
 4733        let provider = self.inline_completion_provider()?;
 4734        let cursor = self.selections.newest_anchor().head();
 4735        let (buffer, cursor_buffer_position) =
 4736            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4737        if !self.enable_inline_completions
 4738            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4739        {
 4740            return None;
 4741        }
 4742
 4743        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4744        self.update_visible_inline_completion(window, cx);
 4745
 4746        Some(())
 4747    }
 4748
 4749    pub fn show_inline_completion(
 4750        &mut self,
 4751        _: &ShowInlineCompletion,
 4752        window: &mut Window,
 4753        cx: &mut Context<Self>,
 4754    ) {
 4755        if !self.has_active_inline_completion() {
 4756            self.refresh_inline_completion(false, true, window, cx);
 4757            return;
 4758        }
 4759
 4760        self.update_visible_inline_completion(window, cx);
 4761    }
 4762
 4763    pub fn display_cursor_names(
 4764        &mut self,
 4765        _: &DisplayCursorNames,
 4766        window: &mut Window,
 4767        cx: &mut Context<Self>,
 4768    ) {
 4769        self.show_cursor_names(window, cx);
 4770    }
 4771
 4772    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4773        self.show_cursor_names = true;
 4774        cx.notify();
 4775        cx.spawn_in(window, |this, mut cx| async move {
 4776            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4777            this.update(&mut cx, |this, cx| {
 4778                this.show_cursor_names = false;
 4779                cx.notify()
 4780            })
 4781            .ok()
 4782        })
 4783        .detach();
 4784    }
 4785
 4786    pub fn next_inline_completion(
 4787        &mut self,
 4788        _: &NextInlineCompletion,
 4789        window: &mut Window,
 4790        cx: &mut Context<Self>,
 4791    ) {
 4792        if self.has_active_inline_completion() {
 4793            self.cycle_inline_completion(Direction::Next, window, cx);
 4794        } else {
 4795            let is_copilot_disabled = self
 4796                .refresh_inline_completion(false, true, window, cx)
 4797                .is_none();
 4798            if is_copilot_disabled {
 4799                cx.propagate();
 4800            }
 4801        }
 4802    }
 4803
 4804    pub fn previous_inline_completion(
 4805        &mut self,
 4806        _: &PreviousInlineCompletion,
 4807        window: &mut Window,
 4808        cx: &mut Context<Self>,
 4809    ) {
 4810        if self.has_active_inline_completion() {
 4811            self.cycle_inline_completion(Direction::Prev, window, cx);
 4812        } else {
 4813            let is_copilot_disabled = self
 4814                .refresh_inline_completion(false, true, window, cx)
 4815                .is_none();
 4816            if is_copilot_disabled {
 4817                cx.propagate();
 4818            }
 4819        }
 4820    }
 4821
 4822    pub fn accept_inline_completion(
 4823        &mut self,
 4824        _: &AcceptInlineCompletion,
 4825        window: &mut Window,
 4826        cx: &mut Context<Self>,
 4827    ) {
 4828        let buffer = self.buffer.read(cx);
 4829        let snapshot = buffer.snapshot(cx);
 4830        let selection = self.selections.newest_adjusted(cx);
 4831        let cursor = selection.head();
 4832        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4833        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4834        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4835        {
 4836            if cursor.column < suggested_indent.len
 4837                && cursor.column <= current_indent.len
 4838                && current_indent.len <= suggested_indent.len
 4839            {
 4840                self.tab(&Default::default(), window, cx);
 4841                return;
 4842            }
 4843        }
 4844
 4845        if self.show_inline_completions_in_menu(cx) {
 4846            self.hide_context_menu(window, cx);
 4847        }
 4848
 4849        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4850            return;
 4851        };
 4852
 4853        self.report_inline_completion_event(true, cx);
 4854
 4855        match &active_inline_completion.completion {
 4856            InlineCompletion::Move(position) => {
 4857                let position = *position;
 4858                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4859                    selections.select_anchor_ranges([position..position]);
 4860                });
 4861            }
 4862            InlineCompletion::Edit { edits, .. } => {
 4863                if let Some(provider) = self.inline_completion_provider() {
 4864                    provider.accept(cx);
 4865                }
 4866
 4867                let snapshot = self.buffer.read(cx).snapshot(cx);
 4868                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4869
 4870                self.buffer.update(cx, |buffer, cx| {
 4871                    buffer.edit(edits.iter().cloned(), None, cx)
 4872                });
 4873
 4874                self.change_selections(None, window, cx, |s| {
 4875                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4876                });
 4877
 4878                self.update_visible_inline_completion(window, cx);
 4879                if self.active_inline_completion.is_none() {
 4880                    self.refresh_inline_completion(true, true, window, cx);
 4881                }
 4882
 4883                cx.notify();
 4884            }
 4885        }
 4886    }
 4887
 4888    pub fn accept_partial_inline_completion(
 4889        &mut self,
 4890        _: &AcceptPartialInlineCompletion,
 4891        window: &mut Window,
 4892        cx: &mut Context<Self>,
 4893    ) {
 4894        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4895            return;
 4896        };
 4897        if self.selections.count() != 1 {
 4898            return;
 4899        }
 4900
 4901        self.report_inline_completion_event(true, cx);
 4902
 4903        match &active_inline_completion.completion {
 4904            InlineCompletion::Move(position) => {
 4905                let position = *position;
 4906                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4907                    selections.select_anchor_ranges([position..position]);
 4908                });
 4909            }
 4910            InlineCompletion::Edit { edits, .. } => {
 4911                // Find an insertion that starts at the cursor position.
 4912                let snapshot = self.buffer.read(cx).snapshot(cx);
 4913                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4914                let insertion = edits.iter().find_map(|(range, text)| {
 4915                    let range = range.to_offset(&snapshot);
 4916                    if range.is_empty() && range.start == cursor_offset {
 4917                        Some(text)
 4918                    } else {
 4919                        None
 4920                    }
 4921                });
 4922
 4923                if let Some(text) = insertion {
 4924                    let mut partial_completion = text
 4925                        .chars()
 4926                        .by_ref()
 4927                        .take_while(|c| c.is_alphabetic())
 4928                        .collect::<String>();
 4929                    if partial_completion.is_empty() {
 4930                        partial_completion = text
 4931                            .chars()
 4932                            .by_ref()
 4933                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4934                            .collect::<String>();
 4935                    }
 4936
 4937                    cx.emit(EditorEvent::InputHandled {
 4938                        utf16_range_to_replace: None,
 4939                        text: partial_completion.clone().into(),
 4940                    });
 4941
 4942                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4943
 4944                    self.refresh_inline_completion(true, true, window, cx);
 4945                    cx.notify();
 4946                } else {
 4947                    self.accept_inline_completion(&Default::default(), window, cx);
 4948                }
 4949            }
 4950        }
 4951    }
 4952
 4953    fn discard_inline_completion(
 4954        &mut self,
 4955        should_report_inline_completion_event: bool,
 4956        cx: &mut Context<Self>,
 4957    ) -> bool {
 4958        if should_report_inline_completion_event {
 4959            self.report_inline_completion_event(false, cx);
 4960        }
 4961
 4962        if let Some(provider) = self.inline_completion_provider() {
 4963            provider.discard(cx);
 4964        }
 4965
 4966        self.take_active_inline_completion(cx).is_some()
 4967    }
 4968
 4969    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4970        let Some(provider) = self.inline_completion_provider() else {
 4971            return;
 4972        };
 4973
 4974        let Some((_, buffer, _)) = self
 4975            .buffer
 4976            .read(cx)
 4977            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4978        else {
 4979            return;
 4980        };
 4981
 4982        let extension = buffer
 4983            .read(cx)
 4984            .file()
 4985            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4986
 4987        let event_type = match accepted {
 4988            true => "Inline Completion Accepted",
 4989            false => "Inline Completion Discarded",
 4990        };
 4991        telemetry::event!(
 4992            event_type,
 4993            provider = provider.name(),
 4994            suggestion_accepted = accepted,
 4995            file_extension = extension,
 4996        );
 4997    }
 4998
 4999    pub fn has_active_inline_completion(&self) -> bool {
 5000        self.active_inline_completion.is_some()
 5001    }
 5002
 5003    fn take_active_inline_completion(
 5004        &mut self,
 5005        cx: &mut Context<Self>,
 5006    ) -> Option<InlineCompletion> {
 5007        let active_inline_completion = self.active_inline_completion.take()?;
 5008        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 5009        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5010        Some(active_inline_completion.completion)
 5011    }
 5012
 5013    fn update_visible_inline_completion(
 5014        &mut self,
 5015        window: &mut Window,
 5016        cx: &mut Context<Self>,
 5017    ) -> Option<()> {
 5018        let selection = self.selections.newest_anchor();
 5019        let cursor = selection.head();
 5020        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5021        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5022        let excerpt_id = cursor.excerpt_id;
 5023
 5024        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 5025            && (self.context_menu.borrow().is_some()
 5026                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5027        if completions_menu_has_precedence
 5028            || !offset_selection.is_empty()
 5029            || !self.enable_inline_completions
 5030            || self
 5031                .active_inline_completion
 5032                .as_ref()
 5033                .map_or(false, |completion| {
 5034                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5035                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5036                    !invalidation_range.contains(&offset_selection.head())
 5037                })
 5038        {
 5039            self.discard_inline_completion(false, cx);
 5040            return None;
 5041        }
 5042
 5043        self.take_active_inline_completion(cx);
 5044        let provider = self.inline_completion_provider()?;
 5045
 5046        let (buffer, cursor_buffer_position) =
 5047            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5048
 5049        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5050        let edits = inline_completion
 5051            .edits
 5052            .into_iter()
 5053            .flat_map(|(range, new_text)| {
 5054                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5055                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5056                Some((start..end, new_text))
 5057            })
 5058            .collect::<Vec<_>>();
 5059        if edits.is_empty() {
 5060            return None;
 5061        }
 5062
 5063        let first_edit_start = edits.first().unwrap().0.start;
 5064        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5065        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5066
 5067        let last_edit_end = edits.last().unwrap().0.end;
 5068        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5069        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5070
 5071        let cursor_row = cursor.to_point(&multibuffer).row;
 5072
 5073        let mut inlay_ids = Vec::new();
 5074        let invalidation_row_range;
 5075        let completion = if cursor_row < edit_start_row {
 5076            invalidation_row_range = cursor_row..edit_end_row;
 5077            InlineCompletion::Move(first_edit_start)
 5078        } else if cursor_row > edit_end_row {
 5079            invalidation_row_range = edit_start_row..cursor_row;
 5080            InlineCompletion::Move(first_edit_start)
 5081        } else {
 5082            if edits
 5083                .iter()
 5084                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5085            {
 5086                let mut inlays = Vec::new();
 5087                for (range, new_text) in &edits {
 5088                    let inlay = Inlay::inline_completion(
 5089                        post_inc(&mut self.next_inlay_id),
 5090                        range.start,
 5091                        new_text.as_str(),
 5092                    );
 5093                    inlay_ids.push(inlay.id);
 5094                    inlays.push(inlay);
 5095                }
 5096
 5097                self.splice_inlays(vec![], inlays, cx);
 5098            } else {
 5099                let background_color = cx.theme().status().deleted_background;
 5100                self.highlight_text::<InlineCompletionHighlight>(
 5101                    edits.iter().map(|(range, _)| range.clone()).collect(),
 5102                    HighlightStyle {
 5103                        background_color: Some(background_color),
 5104                        ..Default::default()
 5105                    },
 5106                    cx,
 5107                );
 5108            }
 5109
 5110            invalidation_row_range = edit_start_row..edit_end_row;
 5111
 5112            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5113                if provider.show_tab_accept_marker()
 5114                    && first_edit_start_point.row == last_edit_end_point.row
 5115                    && !edits.iter().any(|(_, edit)| edit.contains('\n'))
 5116                {
 5117                    EditDisplayMode::TabAccept
 5118                } else {
 5119                    EditDisplayMode::Inline
 5120                }
 5121            } else {
 5122                EditDisplayMode::DiffPopover
 5123            };
 5124
 5125            let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5126
 5127            InlineCompletion::Edit {
 5128                edits,
 5129                edit_preview: inline_completion.edit_preview,
 5130                display_mode,
 5131                snapshot,
 5132            }
 5133        };
 5134
 5135        let invalidation_range = multibuffer
 5136            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5137            ..multibuffer.anchor_after(Point::new(
 5138                invalidation_row_range.end,
 5139                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5140            ));
 5141
 5142        self.active_inline_completion = Some(InlineCompletionState {
 5143            inlay_ids,
 5144            completion,
 5145            invalidation_range,
 5146        });
 5147
 5148        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 5149            if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
 5150                match self.context_menu.borrow_mut().as_mut() {
 5151                    Some(CodeContextMenu::Completions(menu)) => {
 5152                        menu.show_inline_completion_hint(hint);
 5153                    }
 5154                    _ => {}
 5155                }
 5156            }
 5157        }
 5158
 5159        cx.notify();
 5160
 5161        Some(())
 5162    }
 5163
 5164    fn inline_completion_menu_hint(
 5165        &self,
 5166        window: &mut Window,
 5167        cx: &mut Context<Self>,
 5168    ) -> Option<InlineCompletionMenuHint> {
 5169        let provider = self.inline_completion_provider()?;
 5170        if self.has_active_inline_completion() {
 5171            let editor_snapshot = self.snapshot(window, cx);
 5172
 5173            let text = match &self.active_inline_completion.as_ref()?.completion {
 5174                InlineCompletion::Edit {
 5175                    edits,
 5176                    edit_preview,
 5177                    display_mode: _,
 5178                    snapshot,
 5179                } => edit_preview
 5180                    .as_ref()
 5181                    .and_then(|edit_preview| {
 5182                        inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
 5183                    })
 5184                    .map(InlineCompletionText::Edit),
 5185                InlineCompletion::Move(target) => {
 5186                    let target_point =
 5187                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 5188                    let target_line = target_point.row + 1;
 5189                    Some(InlineCompletionText::Move(
 5190                        format!("Jump to edit in line {}", target_line).into(),
 5191                    ))
 5192                }
 5193            };
 5194
 5195            Some(InlineCompletionMenuHint::Loaded { text: text? })
 5196        } else if provider.is_refreshing(cx) {
 5197            Some(InlineCompletionMenuHint::Loading)
 5198        } else if provider.needs_terms_acceptance(cx) {
 5199            Some(InlineCompletionMenuHint::PendingTermsAcceptance)
 5200        } else {
 5201            Some(InlineCompletionMenuHint::None)
 5202        }
 5203    }
 5204
 5205    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5206        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5207    }
 5208
 5209    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5210        let by_provider = matches!(
 5211            self.menu_inline_completions_policy,
 5212            MenuInlineCompletionsPolicy::ByProvider
 5213        );
 5214
 5215        by_provider
 5216            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5217            && self
 5218                .inline_completion_provider()
 5219                .map_or(false, |provider| provider.show_completions_in_menu())
 5220    }
 5221
 5222    fn render_code_actions_indicator(
 5223        &self,
 5224        _style: &EditorStyle,
 5225        row: DisplayRow,
 5226        is_active: bool,
 5227        cx: &mut Context<Self>,
 5228    ) -> Option<IconButton> {
 5229        if self.available_code_actions.is_some() {
 5230            Some(
 5231                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5232                    .shape(ui::IconButtonShape::Square)
 5233                    .icon_size(IconSize::XSmall)
 5234                    .icon_color(Color::Muted)
 5235                    .toggle_state(is_active)
 5236                    .tooltip({
 5237                        let focus_handle = self.focus_handle.clone();
 5238                        move |window, cx| {
 5239                            Tooltip::for_action_in(
 5240                                "Toggle Code Actions",
 5241                                &ToggleCodeActions {
 5242                                    deployed_from_indicator: None,
 5243                                },
 5244                                &focus_handle,
 5245                                window,
 5246                                cx,
 5247                            )
 5248                        }
 5249                    })
 5250                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5251                        window.focus(&editor.focus_handle(cx));
 5252                        editor.toggle_code_actions(
 5253                            &ToggleCodeActions {
 5254                                deployed_from_indicator: Some(row),
 5255                            },
 5256                            window,
 5257                            cx,
 5258                        );
 5259                    })),
 5260            )
 5261        } else {
 5262            None
 5263        }
 5264    }
 5265
 5266    fn clear_tasks(&mut self) {
 5267        self.tasks.clear()
 5268    }
 5269
 5270    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5271        if self.tasks.insert(key, value).is_some() {
 5272            // This case should hopefully be rare, but just in case...
 5273            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5274        }
 5275    }
 5276
 5277    fn build_tasks_context(
 5278        project: &Entity<Project>,
 5279        buffer: &Entity<Buffer>,
 5280        buffer_row: u32,
 5281        tasks: &Arc<RunnableTasks>,
 5282        cx: &mut Context<Self>,
 5283    ) -> Task<Option<task::TaskContext>> {
 5284        let position = Point::new(buffer_row, tasks.column);
 5285        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5286        let location = Location {
 5287            buffer: buffer.clone(),
 5288            range: range_start..range_start,
 5289        };
 5290        // Fill in the environmental variables from the tree-sitter captures
 5291        let mut captured_task_variables = TaskVariables::default();
 5292        for (capture_name, value) in tasks.extra_variables.clone() {
 5293            captured_task_variables.insert(
 5294                task::VariableName::Custom(capture_name.into()),
 5295                value.clone(),
 5296            );
 5297        }
 5298        project.update(cx, |project, cx| {
 5299            project.task_store().update(cx, |task_store, cx| {
 5300                task_store.task_context_for_location(captured_task_variables, location, cx)
 5301            })
 5302        })
 5303    }
 5304
 5305    pub fn spawn_nearest_task(
 5306        &mut self,
 5307        action: &SpawnNearestTask,
 5308        window: &mut Window,
 5309        cx: &mut Context<Self>,
 5310    ) {
 5311        let Some((workspace, _)) = self.workspace.clone() else {
 5312            return;
 5313        };
 5314        let Some(project) = self.project.clone() else {
 5315            return;
 5316        };
 5317
 5318        // Try to find a closest, enclosing node using tree-sitter that has a
 5319        // task
 5320        let Some((buffer, buffer_row, tasks)) = self
 5321            .find_enclosing_node_task(cx)
 5322            // Or find the task that's closest in row-distance.
 5323            .or_else(|| self.find_closest_task(cx))
 5324        else {
 5325            return;
 5326        };
 5327
 5328        let reveal_strategy = action.reveal;
 5329        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5330        cx.spawn_in(window, |_, mut cx| async move {
 5331            let context = task_context.await?;
 5332            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5333
 5334            let resolved = resolved_task.resolved.as_mut()?;
 5335            resolved.reveal = reveal_strategy;
 5336
 5337            workspace
 5338                .update(&mut cx, |workspace, cx| {
 5339                    workspace::tasks::schedule_resolved_task(
 5340                        workspace,
 5341                        task_source_kind,
 5342                        resolved_task,
 5343                        false,
 5344                        cx,
 5345                    );
 5346                })
 5347                .ok()
 5348        })
 5349        .detach();
 5350    }
 5351
 5352    fn find_closest_task(
 5353        &mut self,
 5354        cx: &mut Context<Self>,
 5355    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5356        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5357
 5358        let ((buffer_id, row), tasks) = self
 5359            .tasks
 5360            .iter()
 5361            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5362
 5363        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5364        let tasks = Arc::new(tasks.to_owned());
 5365        Some((buffer, *row, tasks))
 5366    }
 5367
 5368    fn find_enclosing_node_task(
 5369        &mut self,
 5370        cx: &mut Context<Self>,
 5371    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5372        let snapshot = self.buffer.read(cx).snapshot(cx);
 5373        let offset = self.selections.newest::<usize>(cx).head();
 5374        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5375        let buffer_id = excerpt.buffer().remote_id();
 5376
 5377        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5378        let mut cursor = layer.node().walk();
 5379
 5380        while cursor.goto_first_child_for_byte(offset).is_some() {
 5381            if cursor.node().end_byte() == offset {
 5382                cursor.goto_next_sibling();
 5383            }
 5384        }
 5385
 5386        // Ascend to the smallest ancestor that contains the range and has a task.
 5387        loop {
 5388            let node = cursor.node();
 5389            let node_range = node.byte_range();
 5390            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5391
 5392            // Check if this node contains our offset
 5393            if node_range.start <= offset && node_range.end >= offset {
 5394                // If it contains offset, check for task
 5395                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5396                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5397                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5398                }
 5399            }
 5400
 5401            if !cursor.goto_parent() {
 5402                break;
 5403            }
 5404        }
 5405        None
 5406    }
 5407
 5408    fn render_run_indicator(
 5409        &self,
 5410        _style: &EditorStyle,
 5411        is_active: bool,
 5412        row: DisplayRow,
 5413        cx: &mut Context<Self>,
 5414    ) -> IconButton {
 5415        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5416            .shape(ui::IconButtonShape::Square)
 5417            .icon_size(IconSize::XSmall)
 5418            .icon_color(Color::Muted)
 5419            .toggle_state(is_active)
 5420            .on_click(cx.listener(move |editor, _e, window, cx| {
 5421                window.focus(&editor.focus_handle(cx));
 5422                editor.toggle_code_actions(
 5423                    &ToggleCodeActions {
 5424                        deployed_from_indicator: Some(row),
 5425                    },
 5426                    window,
 5427                    cx,
 5428                );
 5429            }))
 5430    }
 5431
 5432    #[cfg(any(test, feature = "test-support"))]
 5433    pub fn context_menu_visible(&self) -> bool {
 5434        self.context_menu
 5435            .borrow()
 5436            .as_ref()
 5437            .map_or(false, |menu| menu.visible())
 5438    }
 5439
 5440    #[cfg(feature = "test-support")]
 5441    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5442        self.context_menu
 5443            .borrow()
 5444            .as_ref()
 5445            .map_or(false, |menu| match menu {
 5446                CodeContextMenu::Completions(menu) => {
 5447                    menu.entries.borrow().first().map_or(false, |entry| {
 5448                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5449                    })
 5450                }
 5451                CodeContextMenu::CodeActions(_) => false,
 5452            })
 5453    }
 5454
 5455    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5456        self.context_menu
 5457            .borrow()
 5458            .as_ref()
 5459            .map(|menu| menu.origin(cursor_position))
 5460    }
 5461
 5462    fn render_context_menu(
 5463        &self,
 5464        style: &EditorStyle,
 5465        max_height_in_lines: u32,
 5466        y_flipped: bool,
 5467        window: &mut Window,
 5468        cx: &mut Context<Editor>,
 5469    ) -> Option<AnyElement> {
 5470        self.context_menu.borrow().as_ref().and_then(|menu| {
 5471            if menu.visible() {
 5472                Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5473            } else {
 5474                None
 5475            }
 5476        })
 5477    }
 5478
 5479    fn render_context_menu_aside(
 5480        &self,
 5481        style: &EditorStyle,
 5482        max_size: Size<Pixels>,
 5483        cx: &mut Context<Editor>,
 5484    ) -> Option<AnyElement> {
 5485        self.context_menu.borrow().as_ref().and_then(|menu| {
 5486            if menu.visible() {
 5487                menu.render_aside(
 5488                    style,
 5489                    max_size,
 5490                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5491                    cx,
 5492                )
 5493            } else {
 5494                None
 5495            }
 5496        })
 5497    }
 5498
 5499    fn hide_context_menu(
 5500        &mut self,
 5501        window: &mut Window,
 5502        cx: &mut Context<Self>,
 5503    ) -> Option<CodeContextMenu> {
 5504        cx.notify();
 5505        self.completion_tasks.clear();
 5506        let context_menu = self.context_menu.borrow_mut().take();
 5507        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5508            self.update_visible_inline_completion(window, cx);
 5509        }
 5510        context_menu
 5511    }
 5512
 5513    fn show_snippet_choices(
 5514        &mut self,
 5515        choices: &Vec<String>,
 5516        selection: Range<Anchor>,
 5517        cx: &mut Context<Self>,
 5518    ) {
 5519        if selection.start.buffer_id.is_none() {
 5520            return;
 5521        }
 5522        let buffer_id = selection.start.buffer_id.unwrap();
 5523        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5524        let id = post_inc(&mut self.next_completion_id);
 5525
 5526        if let Some(buffer) = buffer {
 5527            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5528                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5529            ));
 5530        }
 5531    }
 5532
 5533    pub fn insert_snippet(
 5534        &mut self,
 5535        insertion_ranges: &[Range<usize>],
 5536        snippet: Snippet,
 5537        window: &mut Window,
 5538        cx: &mut Context<Self>,
 5539    ) -> Result<()> {
 5540        struct Tabstop<T> {
 5541            is_end_tabstop: bool,
 5542            ranges: Vec<Range<T>>,
 5543            choices: Option<Vec<String>>,
 5544        }
 5545
 5546        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5547            let snippet_text: Arc<str> = snippet.text.clone().into();
 5548            buffer.edit(
 5549                insertion_ranges
 5550                    .iter()
 5551                    .cloned()
 5552                    .map(|range| (range, snippet_text.clone())),
 5553                Some(AutoindentMode::EachLine),
 5554                cx,
 5555            );
 5556
 5557            let snapshot = &*buffer.read(cx);
 5558            let snippet = &snippet;
 5559            snippet
 5560                .tabstops
 5561                .iter()
 5562                .map(|tabstop| {
 5563                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5564                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5565                    });
 5566                    let mut tabstop_ranges = tabstop
 5567                        .ranges
 5568                        .iter()
 5569                        .flat_map(|tabstop_range| {
 5570                            let mut delta = 0_isize;
 5571                            insertion_ranges.iter().map(move |insertion_range| {
 5572                                let insertion_start = insertion_range.start as isize + delta;
 5573                                delta +=
 5574                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5575
 5576                                let start = ((insertion_start + tabstop_range.start) as usize)
 5577                                    .min(snapshot.len());
 5578                                let end = ((insertion_start + tabstop_range.end) as usize)
 5579                                    .min(snapshot.len());
 5580                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5581                            })
 5582                        })
 5583                        .collect::<Vec<_>>();
 5584                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5585
 5586                    Tabstop {
 5587                        is_end_tabstop,
 5588                        ranges: tabstop_ranges,
 5589                        choices: tabstop.choices.clone(),
 5590                    }
 5591                })
 5592                .collect::<Vec<_>>()
 5593        });
 5594        if let Some(tabstop) = tabstops.first() {
 5595            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5596                s.select_ranges(tabstop.ranges.iter().cloned());
 5597            });
 5598
 5599            if let Some(choices) = &tabstop.choices {
 5600                if let Some(selection) = tabstop.ranges.first() {
 5601                    self.show_snippet_choices(choices, selection.clone(), cx)
 5602                }
 5603            }
 5604
 5605            // If we're already at the last tabstop and it's at the end of the snippet,
 5606            // we're done, we don't need to keep the state around.
 5607            if !tabstop.is_end_tabstop {
 5608                let choices = tabstops
 5609                    .iter()
 5610                    .map(|tabstop| tabstop.choices.clone())
 5611                    .collect();
 5612
 5613                let ranges = tabstops
 5614                    .into_iter()
 5615                    .map(|tabstop| tabstop.ranges)
 5616                    .collect::<Vec<_>>();
 5617
 5618                self.snippet_stack.push(SnippetState {
 5619                    active_index: 0,
 5620                    ranges,
 5621                    choices,
 5622                });
 5623            }
 5624
 5625            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5626            if self.autoclose_regions.is_empty() {
 5627                let snapshot = self.buffer.read(cx).snapshot(cx);
 5628                for selection in &mut self.selections.all::<Point>(cx) {
 5629                    let selection_head = selection.head();
 5630                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5631                        continue;
 5632                    };
 5633
 5634                    let mut bracket_pair = None;
 5635                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5636                    let prev_chars = snapshot
 5637                        .reversed_chars_at(selection_head)
 5638                        .collect::<String>();
 5639                    for (pair, enabled) in scope.brackets() {
 5640                        if enabled
 5641                            && pair.close
 5642                            && prev_chars.starts_with(pair.start.as_str())
 5643                            && next_chars.starts_with(pair.end.as_str())
 5644                        {
 5645                            bracket_pair = Some(pair.clone());
 5646                            break;
 5647                        }
 5648                    }
 5649                    if let Some(pair) = bracket_pair {
 5650                        let start = snapshot.anchor_after(selection_head);
 5651                        let end = snapshot.anchor_after(selection_head);
 5652                        self.autoclose_regions.push(AutocloseRegion {
 5653                            selection_id: selection.id,
 5654                            range: start..end,
 5655                            pair,
 5656                        });
 5657                    }
 5658                }
 5659            }
 5660        }
 5661        Ok(())
 5662    }
 5663
 5664    pub fn move_to_next_snippet_tabstop(
 5665        &mut self,
 5666        window: &mut Window,
 5667        cx: &mut Context<Self>,
 5668    ) -> bool {
 5669        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 5670    }
 5671
 5672    pub fn move_to_prev_snippet_tabstop(
 5673        &mut self,
 5674        window: &mut Window,
 5675        cx: &mut Context<Self>,
 5676    ) -> bool {
 5677        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 5678    }
 5679
 5680    pub fn move_to_snippet_tabstop(
 5681        &mut self,
 5682        bias: Bias,
 5683        window: &mut Window,
 5684        cx: &mut Context<Self>,
 5685    ) -> bool {
 5686        if let Some(mut snippet) = self.snippet_stack.pop() {
 5687            match bias {
 5688                Bias::Left => {
 5689                    if snippet.active_index > 0 {
 5690                        snippet.active_index -= 1;
 5691                    } else {
 5692                        self.snippet_stack.push(snippet);
 5693                        return false;
 5694                    }
 5695                }
 5696                Bias::Right => {
 5697                    if snippet.active_index + 1 < snippet.ranges.len() {
 5698                        snippet.active_index += 1;
 5699                    } else {
 5700                        self.snippet_stack.push(snippet);
 5701                        return false;
 5702                    }
 5703                }
 5704            }
 5705            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5706                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5707                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5708                });
 5709
 5710                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5711                    if let Some(selection) = current_ranges.first() {
 5712                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5713                    }
 5714                }
 5715
 5716                // If snippet state is not at the last tabstop, push it back on the stack
 5717                if snippet.active_index + 1 < snippet.ranges.len() {
 5718                    self.snippet_stack.push(snippet);
 5719                }
 5720                return true;
 5721            }
 5722        }
 5723
 5724        false
 5725    }
 5726
 5727    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5728        self.transact(window, cx, |this, window, cx| {
 5729            this.select_all(&SelectAll, window, cx);
 5730            this.insert("", window, cx);
 5731        });
 5732    }
 5733
 5734    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 5735        self.transact(window, cx, |this, window, cx| {
 5736            this.select_autoclose_pair(window, cx);
 5737            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5738            if !this.linked_edit_ranges.is_empty() {
 5739                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5740                let snapshot = this.buffer.read(cx).snapshot(cx);
 5741
 5742                for selection in selections.iter() {
 5743                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5744                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5745                    if selection_start.buffer_id != selection_end.buffer_id {
 5746                        continue;
 5747                    }
 5748                    if let Some(ranges) =
 5749                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5750                    {
 5751                        for (buffer, entries) in ranges {
 5752                            linked_ranges.entry(buffer).or_default().extend(entries);
 5753                        }
 5754                    }
 5755                }
 5756            }
 5757
 5758            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5759            if !this.selections.line_mode {
 5760                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5761                for selection in &mut selections {
 5762                    if selection.is_empty() {
 5763                        let old_head = selection.head();
 5764                        let mut new_head =
 5765                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5766                                .to_point(&display_map);
 5767                        if let Some((buffer, line_buffer_range)) = display_map
 5768                            .buffer_snapshot
 5769                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5770                        {
 5771                            let indent_size =
 5772                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5773                            let indent_len = match indent_size.kind {
 5774                                IndentKind::Space => {
 5775                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5776                                }
 5777                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5778                            };
 5779                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5780                                let indent_len = indent_len.get();
 5781                                new_head = cmp::min(
 5782                                    new_head,
 5783                                    MultiBufferPoint::new(
 5784                                        old_head.row,
 5785                                        ((old_head.column - 1) / indent_len) * indent_len,
 5786                                    ),
 5787                                );
 5788                            }
 5789                        }
 5790
 5791                        selection.set_head(new_head, SelectionGoal::None);
 5792                    }
 5793                }
 5794            }
 5795
 5796            this.signature_help_state.set_backspace_pressed(true);
 5797            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5798                s.select(selections)
 5799            });
 5800            this.insert("", window, cx);
 5801            let empty_str: Arc<str> = Arc::from("");
 5802            for (buffer, edits) in linked_ranges {
 5803                let snapshot = buffer.read(cx).snapshot();
 5804                use text::ToPoint as TP;
 5805
 5806                let edits = edits
 5807                    .into_iter()
 5808                    .map(|range| {
 5809                        let end_point = TP::to_point(&range.end, &snapshot);
 5810                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5811
 5812                        if end_point == start_point {
 5813                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5814                                .saturating_sub(1);
 5815                            start_point =
 5816                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5817                        };
 5818
 5819                        (start_point..end_point, empty_str.clone())
 5820                    })
 5821                    .sorted_by_key(|(range, _)| range.start)
 5822                    .collect::<Vec<_>>();
 5823                buffer.update(cx, |this, cx| {
 5824                    this.edit(edits, None, cx);
 5825                })
 5826            }
 5827            this.refresh_inline_completion(true, false, window, cx);
 5828            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 5829        });
 5830    }
 5831
 5832    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 5833        self.transact(window, cx, |this, window, cx| {
 5834            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5835                let line_mode = s.line_mode;
 5836                s.move_with(|map, selection| {
 5837                    if selection.is_empty() && !line_mode {
 5838                        let cursor = movement::right(map, selection.head());
 5839                        selection.end = cursor;
 5840                        selection.reversed = true;
 5841                        selection.goal = SelectionGoal::None;
 5842                    }
 5843                })
 5844            });
 5845            this.insert("", window, cx);
 5846            this.refresh_inline_completion(true, false, window, cx);
 5847        });
 5848    }
 5849
 5850    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 5851        if self.move_to_prev_snippet_tabstop(window, cx) {
 5852            return;
 5853        }
 5854
 5855        self.outdent(&Outdent, window, cx);
 5856    }
 5857
 5858    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 5859        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 5860            return;
 5861        }
 5862
 5863        let mut selections = self.selections.all_adjusted(cx);
 5864        let buffer = self.buffer.read(cx);
 5865        let snapshot = buffer.snapshot(cx);
 5866        let rows_iter = selections.iter().map(|s| s.head().row);
 5867        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5868
 5869        let mut edits = Vec::new();
 5870        let mut prev_edited_row = 0;
 5871        let mut row_delta = 0;
 5872        for selection in &mut selections {
 5873            if selection.start.row != prev_edited_row {
 5874                row_delta = 0;
 5875            }
 5876            prev_edited_row = selection.end.row;
 5877
 5878            // If the selection is non-empty, then increase the indentation of the selected lines.
 5879            if !selection.is_empty() {
 5880                row_delta =
 5881                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5882                continue;
 5883            }
 5884
 5885            // If the selection is empty and the cursor is in the leading whitespace before the
 5886            // suggested indentation, then auto-indent the line.
 5887            let cursor = selection.head();
 5888            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5889            if let Some(suggested_indent) =
 5890                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5891            {
 5892                if cursor.column < suggested_indent.len
 5893                    && cursor.column <= current_indent.len
 5894                    && current_indent.len <= suggested_indent.len
 5895                {
 5896                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5897                    selection.end = selection.start;
 5898                    if row_delta == 0 {
 5899                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5900                            cursor.row,
 5901                            current_indent,
 5902                            suggested_indent,
 5903                        ));
 5904                        row_delta = suggested_indent.len - current_indent.len;
 5905                    }
 5906                    continue;
 5907                }
 5908            }
 5909
 5910            // Otherwise, insert a hard or soft tab.
 5911            let settings = buffer.settings_at(cursor, cx);
 5912            let tab_size = if settings.hard_tabs {
 5913                IndentSize::tab()
 5914            } else {
 5915                let tab_size = settings.tab_size.get();
 5916                let char_column = snapshot
 5917                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5918                    .flat_map(str::chars)
 5919                    .count()
 5920                    + row_delta as usize;
 5921                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5922                IndentSize::spaces(chars_to_next_tab_stop)
 5923            };
 5924            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5925            selection.end = selection.start;
 5926            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5927            row_delta += tab_size.len;
 5928        }
 5929
 5930        self.transact(window, cx, |this, window, cx| {
 5931            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5932            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5933                s.select(selections)
 5934            });
 5935            this.refresh_inline_completion(true, false, window, cx);
 5936        });
 5937    }
 5938
 5939    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 5940        if self.read_only(cx) {
 5941            return;
 5942        }
 5943        let mut selections = self.selections.all::<Point>(cx);
 5944        let mut prev_edited_row = 0;
 5945        let mut row_delta = 0;
 5946        let mut edits = Vec::new();
 5947        let buffer = self.buffer.read(cx);
 5948        let snapshot = buffer.snapshot(cx);
 5949        for selection in &mut selections {
 5950            if selection.start.row != prev_edited_row {
 5951                row_delta = 0;
 5952            }
 5953            prev_edited_row = selection.end.row;
 5954
 5955            row_delta =
 5956                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5957        }
 5958
 5959        self.transact(window, cx, |this, window, cx| {
 5960            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5961            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5962                s.select(selections)
 5963            });
 5964        });
 5965    }
 5966
 5967    fn indent_selection(
 5968        buffer: &MultiBuffer,
 5969        snapshot: &MultiBufferSnapshot,
 5970        selection: &mut Selection<Point>,
 5971        edits: &mut Vec<(Range<Point>, String)>,
 5972        delta_for_start_row: u32,
 5973        cx: &App,
 5974    ) -> u32 {
 5975        let settings = buffer.settings_at(selection.start, cx);
 5976        let tab_size = settings.tab_size.get();
 5977        let indent_kind = if settings.hard_tabs {
 5978            IndentKind::Tab
 5979        } else {
 5980            IndentKind::Space
 5981        };
 5982        let mut start_row = selection.start.row;
 5983        let mut end_row = selection.end.row + 1;
 5984
 5985        // If a selection ends at the beginning of a line, don't indent
 5986        // that last line.
 5987        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5988            end_row -= 1;
 5989        }
 5990
 5991        // Avoid re-indenting a row that has already been indented by a
 5992        // previous selection, but still update this selection's column
 5993        // to reflect that indentation.
 5994        if delta_for_start_row > 0 {
 5995            start_row += 1;
 5996            selection.start.column += delta_for_start_row;
 5997            if selection.end.row == selection.start.row {
 5998                selection.end.column += delta_for_start_row;
 5999            }
 6000        }
 6001
 6002        let mut delta_for_end_row = 0;
 6003        let has_multiple_rows = start_row + 1 != end_row;
 6004        for row in start_row..end_row {
 6005            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6006            let indent_delta = match (current_indent.kind, indent_kind) {
 6007                (IndentKind::Space, IndentKind::Space) => {
 6008                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6009                    IndentSize::spaces(columns_to_next_tab_stop)
 6010                }
 6011                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6012                (_, IndentKind::Tab) => IndentSize::tab(),
 6013            };
 6014
 6015            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6016                0
 6017            } else {
 6018                selection.start.column
 6019            };
 6020            let row_start = Point::new(row, start);
 6021            edits.push((
 6022                row_start..row_start,
 6023                indent_delta.chars().collect::<String>(),
 6024            ));
 6025
 6026            // Update this selection's endpoints to reflect the indentation.
 6027            if row == selection.start.row {
 6028                selection.start.column += indent_delta.len;
 6029            }
 6030            if row == selection.end.row {
 6031                selection.end.column += indent_delta.len;
 6032                delta_for_end_row = indent_delta.len;
 6033            }
 6034        }
 6035
 6036        if selection.start.row == selection.end.row {
 6037            delta_for_start_row + delta_for_end_row
 6038        } else {
 6039            delta_for_end_row
 6040        }
 6041    }
 6042
 6043    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6044        if self.read_only(cx) {
 6045            return;
 6046        }
 6047        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6048        let selections = self.selections.all::<Point>(cx);
 6049        let mut deletion_ranges = Vec::new();
 6050        let mut last_outdent = None;
 6051        {
 6052            let buffer = self.buffer.read(cx);
 6053            let snapshot = buffer.snapshot(cx);
 6054            for selection in &selections {
 6055                let settings = buffer.settings_at(selection.start, cx);
 6056                let tab_size = settings.tab_size.get();
 6057                let mut rows = selection.spanned_rows(false, &display_map);
 6058
 6059                // Avoid re-outdenting a row that has already been outdented by a
 6060                // previous selection.
 6061                if let Some(last_row) = last_outdent {
 6062                    if last_row == rows.start {
 6063                        rows.start = rows.start.next_row();
 6064                    }
 6065                }
 6066                let has_multiple_rows = rows.len() > 1;
 6067                for row in rows.iter_rows() {
 6068                    let indent_size = snapshot.indent_size_for_line(row);
 6069                    if indent_size.len > 0 {
 6070                        let deletion_len = match indent_size.kind {
 6071                            IndentKind::Space => {
 6072                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6073                                if columns_to_prev_tab_stop == 0 {
 6074                                    tab_size
 6075                                } else {
 6076                                    columns_to_prev_tab_stop
 6077                                }
 6078                            }
 6079                            IndentKind::Tab => 1,
 6080                        };
 6081                        let start = if has_multiple_rows
 6082                            || deletion_len > selection.start.column
 6083                            || indent_size.len < selection.start.column
 6084                        {
 6085                            0
 6086                        } else {
 6087                            selection.start.column - deletion_len
 6088                        };
 6089                        deletion_ranges.push(
 6090                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6091                        );
 6092                        last_outdent = Some(row);
 6093                    }
 6094                }
 6095            }
 6096        }
 6097
 6098        self.transact(window, cx, |this, window, cx| {
 6099            this.buffer.update(cx, |buffer, cx| {
 6100                let empty_str: Arc<str> = Arc::default();
 6101                buffer.edit(
 6102                    deletion_ranges
 6103                        .into_iter()
 6104                        .map(|range| (range, empty_str.clone())),
 6105                    None,
 6106                    cx,
 6107                );
 6108            });
 6109            let selections = this.selections.all::<usize>(cx);
 6110            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6111                s.select(selections)
 6112            });
 6113        });
 6114    }
 6115
 6116    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6117        if self.read_only(cx) {
 6118            return;
 6119        }
 6120        let selections = self
 6121            .selections
 6122            .all::<usize>(cx)
 6123            .into_iter()
 6124            .map(|s| s.range());
 6125
 6126        self.transact(window, cx, |this, window, cx| {
 6127            this.buffer.update(cx, |buffer, cx| {
 6128                buffer.autoindent_ranges(selections, cx);
 6129            });
 6130            let selections = this.selections.all::<usize>(cx);
 6131            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6132                s.select(selections)
 6133            });
 6134        });
 6135    }
 6136
 6137    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6139        let selections = self.selections.all::<Point>(cx);
 6140
 6141        let mut new_cursors = Vec::new();
 6142        let mut edit_ranges = Vec::new();
 6143        let mut selections = selections.iter().peekable();
 6144        while let Some(selection) = selections.next() {
 6145            let mut rows = selection.spanned_rows(false, &display_map);
 6146            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6147
 6148            // Accumulate contiguous regions of rows that we want to delete.
 6149            while let Some(next_selection) = selections.peek() {
 6150                let next_rows = next_selection.spanned_rows(false, &display_map);
 6151                if next_rows.start <= rows.end {
 6152                    rows.end = next_rows.end;
 6153                    selections.next().unwrap();
 6154                } else {
 6155                    break;
 6156                }
 6157            }
 6158
 6159            let buffer = &display_map.buffer_snapshot;
 6160            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6161            let edit_end;
 6162            let cursor_buffer_row;
 6163            if buffer.max_point().row >= rows.end.0 {
 6164                // If there's a line after the range, delete the \n from the end of the row range
 6165                // and position the cursor on the next line.
 6166                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6167                cursor_buffer_row = rows.end;
 6168            } else {
 6169                // If there isn't a line after the range, delete the \n from the line before the
 6170                // start of the row range and position the cursor there.
 6171                edit_start = edit_start.saturating_sub(1);
 6172                edit_end = buffer.len();
 6173                cursor_buffer_row = rows.start.previous_row();
 6174            }
 6175
 6176            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6177            *cursor.column_mut() =
 6178                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6179
 6180            new_cursors.push((
 6181                selection.id,
 6182                buffer.anchor_after(cursor.to_point(&display_map)),
 6183            ));
 6184            edit_ranges.push(edit_start..edit_end);
 6185        }
 6186
 6187        self.transact(window, cx, |this, window, cx| {
 6188            let buffer = this.buffer.update(cx, |buffer, cx| {
 6189                let empty_str: Arc<str> = Arc::default();
 6190                buffer.edit(
 6191                    edit_ranges
 6192                        .into_iter()
 6193                        .map(|range| (range, empty_str.clone())),
 6194                    None,
 6195                    cx,
 6196                );
 6197                buffer.snapshot(cx)
 6198            });
 6199            let new_selections = new_cursors
 6200                .into_iter()
 6201                .map(|(id, cursor)| {
 6202                    let cursor = cursor.to_point(&buffer);
 6203                    Selection {
 6204                        id,
 6205                        start: cursor,
 6206                        end: cursor,
 6207                        reversed: false,
 6208                        goal: SelectionGoal::None,
 6209                    }
 6210                })
 6211                .collect();
 6212
 6213            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6214                s.select(new_selections);
 6215            });
 6216        });
 6217    }
 6218
 6219    pub fn join_lines_impl(
 6220        &mut self,
 6221        insert_whitespace: bool,
 6222        window: &mut Window,
 6223        cx: &mut Context<Self>,
 6224    ) {
 6225        if self.read_only(cx) {
 6226            return;
 6227        }
 6228        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6229        for selection in self.selections.all::<Point>(cx) {
 6230            let start = MultiBufferRow(selection.start.row);
 6231            // Treat single line selections as if they include the next line. Otherwise this action
 6232            // would do nothing for single line selections individual cursors.
 6233            let end = if selection.start.row == selection.end.row {
 6234                MultiBufferRow(selection.start.row + 1)
 6235            } else {
 6236                MultiBufferRow(selection.end.row)
 6237            };
 6238
 6239            if let Some(last_row_range) = row_ranges.last_mut() {
 6240                if start <= last_row_range.end {
 6241                    last_row_range.end = end;
 6242                    continue;
 6243                }
 6244            }
 6245            row_ranges.push(start..end);
 6246        }
 6247
 6248        let snapshot = self.buffer.read(cx).snapshot(cx);
 6249        let mut cursor_positions = Vec::new();
 6250        for row_range in &row_ranges {
 6251            let anchor = snapshot.anchor_before(Point::new(
 6252                row_range.end.previous_row().0,
 6253                snapshot.line_len(row_range.end.previous_row()),
 6254            ));
 6255            cursor_positions.push(anchor..anchor);
 6256        }
 6257
 6258        self.transact(window, cx, |this, window, cx| {
 6259            for row_range in row_ranges.into_iter().rev() {
 6260                for row in row_range.iter_rows().rev() {
 6261                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6262                    let next_line_row = row.next_row();
 6263                    let indent = snapshot.indent_size_for_line(next_line_row);
 6264                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6265
 6266                    let replace =
 6267                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6268                            " "
 6269                        } else {
 6270                            ""
 6271                        };
 6272
 6273                    this.buffer.update(cx, |buffer, cx| {
 6274                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6275                    });
 6276                }
 6277            }
 6278
 6279            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6280                s.select_anchor_ranges(cursor_positions)
 6281            });
 6282        });
 6283    }
 6284
 6285    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6286        self.join_lines_impl(true, window, cx);
 6287    }
 6288
 6289    pub fn sort_lines_case_sensitive(
 6290        &mut self,
 6291        _: &SortLinesCaseSensitive,
 6292        window: &mut Window,
 6293        cx: &mut Context<Self>,
 6294    ) {
 6295        self.manipulate_lines(window, cx, |lines| lines.sort())
 6296    }
 6297
 6298    pub fn sort_lines_case_insensitive(
 6299        &mut self,
 6300        _: &SortLinesCaseInsensitive,
 6301        window: &mut Window,
 6302        cx: &mut Context<Self>,
 6303    ) {
 6304        self.manipulate_lines(window, cx, |lines| {
 6305            lines.sort_by_key(|line| line.to_lowercase())
 6306        })
 6307    }
 6308
 6309    pub fn unique_lines_case_insensitive(
 6310        &mut self,
 6311        _: &UniqueLinesCaseInsensitive,
 6312        window: &mut Window,
 6313        cx: &mut Context<Self>,
 6314    ) {
 6315        self.manipulate_lines(window, cx, |lines| {
 6316            let mut seen = HashSet::default();
 6317            lines.retain(|line| seen.insert(line.to_lowercase()));
 6318        })
 6319    }
 6320
 6321    pub fn unique_lines_case_sensitive(
 6322        &mut self,
 6323        _: &UniqueLinesCaseSensitive,
 6324        window: &mut Window,
 6325        cx: &mut Context<Self>,
 6326    ) {
 6327        self.manipulate_lines(window, cx, |lines| {
 6328            let mut seen = HashSet::default();
 6329            lines.retain(|line| seen.insert(*line));
 6330        })
 6331    }
 6332
 6333    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6334        let mut revert_changes = HashMap::default();
 6335        let snapshot = self.snapshot(window, cx);
 6336        for hunk in snapshot
 6337            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6338        {
 6339            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6340        }
 6341        if !revert_changes.is_empty() {
 6342            self.transact(window, cx, |editor, window, cx| {
 6343                editor.revert(revert_changes, window, cx);
 6344            });
 6345        }
 6346    }
 6347
 6348    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6349        let Some(project) = self.project.clone() else {
 6350            return;
 6351        };
 6352        self.reload(project, window, cx)
 6353            .detach_and_notify_err(window, cx);
 6354    }
 6355
 6356    pub fn revert_selected_hunks(
 6357        &mut self,
 6358        _: &RevertSelectedHunks,
 6359        window: &mut Window,
 6360        cx: &mut Context<Self>,
 6361    ) {
 6362        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6363        self.revert_hunks_in_ranges(selections, window, cx);
 6364    }
 6365
 6366    fn revert_hunks_in_ranges(
 6367        &mut self,
 6368        ranges: impl Iterator<Item = Range<Point>>,
 6369        window: &mut Window,
 6370        cx: &mut Context<Editor>,
 6371    ) {
 6372        let mut revert_changes = HashMap::default();
 6373        let snapshot = self.snapshot(window, cx);
 6374        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6375            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6376        }
 6377        if !revert_changes.is_empty() {
 6378            self.transact(window, cx, |editor, window, cx| {
 6379                editor.revert(revert_changes, window, cx);
 6380            });
 6381        }
 6382    }
 6383
 6384    pub fn open_active_item_in_terminal(
 6385        &mut self,
 6386        _: &OpenInTerminal,
 6387        window: &mut Window,
 6388        cx: &mut Context<Self>,
 6389    ) {
 6390        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6391            let project_path = buffer.read(cx).project_path(cx)?;
 6392            let project = self.project.as_ref()?.read(cx);
 6393            let entry = project.entry_for_path(&project_path, cx)?;
 6394            let parent = match &entry.canonical_path {
 6395                Some(canonical_path) => canonical_path.to_path_buf(),
 6396                None => project.absolute_path(&project_path, cx)?,
 6397            }
 6398            .parent()?
 6399            .to_path_buf();
 6400            Some(parent)
 6401        }) {
 6402            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6403        }
 6404    }
 6405
 6406    pub fn prepare_revert_change(
 6407        &self,
 6408        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6409        hunk: &MultiBufferDiffHunk,
 6410        cx: &mut App,
 6411    ) -> Option<()> {
 6412        let buffer = self.buffer.read(cx);
 6413        let change_set = buffer.change_set_for(hunk.buffer_id)?;
 6414        let buffer = buffer.buffer(hunk.buffer_id)?;
 6415        let buffer = buffer.read(cx);
 6416        let original_text = change_set
 6417            .read(cx)
 6418            .base_text
 6419            .as_ref()?
 6420            .as_rope()
 6421            .slice(hunk.diff_base_byte_range.clone());
 6422        let buffer_snapshot = buffer.snapshot();
 6423        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6424        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6425            probe
 6426                .0
 6427                .start
 6428                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6429                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6430        }) {
 6431            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6432            Some(())
 6433        } else {
 6434            None
 6435        }
 6436    }
 6437
 6438    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6439        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6440    }
 6441
 6442    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6443        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6444    }
 6445
 6446    fn manipulate_lines<Fn>(
 6447        &mut self,
 6448        window: &mut Window,
 6449        cx: &mut Context<Self>,
 6450        mut callback: Fn,
 6451    ) where
 6452        Fn: FnMut(&mut Vec<&str>),
 6453    {
 6454        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6455        let buffer = self.buffer.read(cx).snapshot(cx);
 6456
 6457        let mut edits = Vec::new();
 6458
 6459        let selections = self.selections.all::<Point>(cx);
 6460        let mut selections = selections.iter().peekable();
 6461        let mut contiguous_row_selections = Vec::new();
 6462        let mut new_selections = Vec::new();
 6463        let mut added_lines = 0;
 6464        let mut removed_lines = 0;
 6465
 6466        while let Some(selection) = selections.next() {
 6467            let (start_row, end_row) = consume_contiguous_rows(
 6468                &mut contiguous_row_selections,
 6469                selection,
 6470                &display_map,
 6471                &mut selections,
 6472            );
 6473
 6474            let start_point = Point::new(start_row.0, 0);
 6475            let end_point = Point::new(
 6476                end_row.previous_row().0,
 6477                buffer.line_len(end_row.previous_row()),
 6478            );
 6479            let text = buffer
 6480                .text_for_range(start_point..end_point)
 6481                .collect::<String>();
 6482
 6483            let mut lines = text.split('\n').collect_vec();
 6484
 6485            let lines_before = lines.len();
 6486            callback(&mut lines);
 6487            let lines_after = lines.len();
 6488
 6489            edits.push((start_point..end_point, lines.join("\n")));
 6490
 6491            // Selections must change based on added and removed line count
 6492            let start_row =
 6493                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6494            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6495            new_selections.push(Selection {
 6496                id: selection.id,
 6497                start: start_row,
 6498                end: end_row,
 6499                goal: SelectionGoal::None,
 6500                reversed: selection.reversed,
 6501            });
 6502
 6503            if lines_after > lines_before {
 6504                added_lines += lines_after - lines_before;
 6505            } else if lines_before > lines_after {
 6506                removed_lines += lines_before - lines_after;
 6507            }
 6508        }
 6509
 6510        self.transact(window, cx, |this, window, cx| {
 6511            let buffer = this.buffer.update(cx, |buffer, cx| {
 6512                buffer.edit(edits, None, cx);
 6513                buffer.snapshot(cx)
 6514            });
 6515
 6516            // Recalculate offsets on newly edited buffer
 6517            let new_selections = new_selections
 6518                .iter()
 6519                .map(|s| {
 6520                    let start_point = Point::new(s.start.0, 0);
 6521                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6522                    Selection {
 6523                        id: s.id,
 6524                        start: buffer.point_to_offset(start_point),
 6525                        end: buffer.point_to_offset(end_point),
 6526                        goal: s.goal,
 6527                        reversed: s.reversed,
 6528                    }
 6529                })
 6530                .collect();
 6531
 6532            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6533                s.select(new_selections);
 6534            });
 6535
 6536            this.request_autoscroll(Autoscroll::fit(), cx);
 6537        });
 6538    }
 6539
 6540    pub fn convert_to_upper_case(
 6541        &mut self,
 6542        _: &ConvertToUpperCase,
 6543        window: &mut Window,
 6544        cx: &mut Context<Self>,
 6545    ) {
 6546        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6547    }
 6548
 6549    pub fn convert_to_lower_case(
 6550        &mut self,
 6551        _: &ConvertToLowerCase,
 6552        window: &mut Window,
 6553        cx: &mut Context<Self>,
 6554    ) {
 6555        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6556    }
 6557
 6558    pub fn convert_to_title_case(
 6559        &mut self,
 6560        _: &ConvertToTitleCase,
 6561        window: &mut Window,
 6562        cx: &mut Context<Self>,
 6563    ) {
 6564        self.manipulate_text(window, cx, |text| {
 6565            text.split('\n')
 6566                .map(|line| line.to_case(Case::Title))
 6567                .join("\n")
 6568        })
 6569    }
 6570
 6571    pub fn convert_to_snake_case(
 6572        &mut self,
 6573        _: &ConvertToSnakeCase,
 6574        window: &mut Window,
 6575        cx: &mut Context<Self>,
 6576    ) {
 6577        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6578    }
 6579
 6580    pub fn convert_to_kebab_case(
 6581        &mut self,
 6582        _: &ConvertToKebabCase,
 6583        window: &mut Window,
 6584        cx: &mut Context<Self>,
 6585    ) {
 6586        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6587    }
 6588
 6589    pub fn convert_to_upper_camel_case(
 6590        &mut self,
 6591        _: &ConvertToUpperCamelCase,
 6592        window: &mut Window,
 6593        cx: &mut Context<Self>,
 6594    ) {
 6595        self.manipulate_text(window, cx, |text| {
 6596            text.split('\n')
 6597                .map(|line| line.to_case(Case::UpperCamel))
 6598                .join("\n")
 6599        })
 6600    }
 6601
 6602    pub fn convert_to_lower_camel_case(
 6603        &mut self,
 6604        _: &ConvertToLowerCamelCase,
 6605        window: &mut Window,
 6606        cx: &mut Context<Self>,
 6607    ) {
 6608        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6609    }
 6610
 6611    pub fn convert_to_opposite_case(
 6612        &mut self,
 6613        _: &ConvertToOppositeCase,
 6614        window: &mut Window,
 6615        cx: &mut Context<Self>,
 6616    ) {
 6617        self.manipulate_text(window, cx, |text| {
 6618            text.chars()
 6619                .fold(String::with_capacity(text.len()), |mut t, c| {
 6620                    if c.is_uppercase() {
 6621                        t.extend(c.to_lowercase());
 6622                    } else {
 6623                        t.extend(c.to_uppercase());
 6624                    }
 6625                    t
 6626                })
 6627        })
 6628    }
 6629
 6630    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6631    where
 6632        Fn: FnMut(&str) -> String,
 6633    {
 6634        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6635        let buffer = self.buffer.read(cx).snapshot(cx);
 6636
 6637        let mut new_selections = Vec::new();
 6638        let mut edits = Vec::new();
 6639        let mut selection_adjustment = 0i32;
 6640
 6641        for selection in self.selections.all::<usize>(cx) {
 6642            let selection_is_empty = selection.is_empty();
 6643
 6644            let (start, end) = if selection_is_empty {
 6645                let word_range = movement::surrounding_word(
 6646                    &display_map,
 6647                    selection.start.to_display_point(&display_map),
 6648                );
 6649                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6650                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6651                (start, end)
 6652            } else {
 6653                (selection.start, selection.end)
 6654            };
 6655
 6656            let text = buffer.text_for_range(start..end).collect::<String>();
 6657            let old_length = text.len() as i32;
 6658            let text = callback(&text);
 6659
 6660            new_selections.push(Selection {
 6661                start: (start as i32 - selection_adjustment) as usize,
 6662                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6663                goal: SelectionGoal::None,
 6664                ..selection
 6665            });
 6666
 6667            selection_adjustment += old_length - text.len() as i32;
 6668
 6669            edits.push((start..end, text));
 6670        }
 6671
 6672        self.transact(window, cx, |this, window, cx| {
 6673            this.buffer.update(cx, |buffer, cx| {
 6674                buffer.edit(edits, None, cx);
 6675            });
 6676
 6677            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6678                s.select(new_selections);
 6679            });
 6680
 6681            this.request_autoscroll(Autoscroll::fit(), cx);
 6682        });
 6683    }
 6684
 6685    pub fn duplicate(
 6686        &mut self,
 6687        upwards: bool,
 6688        whole_lines: bool,
 6689        window: &mut Window,
 6690        cx: &mut Context<Self>,
 6691    ) {
 6692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6693        let buffer = &display_map.buffer_snapshot;
 6694        let selections = self.selections.all::<Point>(cx);
 6695
 6696        let mut edits = Vec::new();
 6697        let mut selections_iter = selections.iter().peekable();
 6698        while let Some(selection) = selections_iter.next() {
 6699            let mut rows = selection.spanned_rows(false, &display_map);
 6700            // duplicate line-wise
 6701            if whole_lines || selection.start == selection.end {
 6702                // Avoid duplicating the same lines twice.
 6703                while let Some(next_selection) = selections_iter.peek() {
 6704                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6705                    if next_rows.start < rows.end {
 6706                        rows.end = next_rows.end;
 6707                        selections_iter.next().unwrap();
 6708                    } else {
 6709                        break;
 6710                    }
 6711                }
 6712
 6713                // Copy the text from the selected row region and splice it either at the start
 6714                // or end of the region.
 6715                let start = Point::new(rows.start.0, 0);
 6716                let end = Point::new(
 6717                    rows.end.previous_row().0,
 6718                    buffer.line_len(rows.end.previous_row()),
 6719                );
 6720                let text = buffer
 6721                    .text_for_range(start..end)
 6722                    .chain(Some("\n"))
 6723                    .collect::<String>();
 6724                let insert_location = if upwards {
 6725                    Point::new(rows.end.0, 0)
 6726                } else {
 6727                    start
 6728                };
 6729                edits.push((insert_location..insert_location, text));
 6730            } else {
 6731                // duplicate character-wise
 6732                let start = selection.start;
 6733                let end = selection.end;
 6734                let text = buffer.text_for_range(start..end).collect::<String>();
 6735                edits.push((selection.end..selection.end, text));
 6736            }
 6737        }
 6738
 6739        self.transact(window, cx, |this, _, cx| {
 6740            this.buffer.update(cx, |buffer, cx| {
 6741                buffer.edit(edits, None, cx);
 6742            });
 6743
 6744            this.request_autoscroll(Autoscroll::fit(), cx);
 6745        });
 6746    }
 6747
 6748    pub fn duplicate_line_up(
 6749        &mut self,
 6750        _: &DuplicateLineUp,
 6751        window: &mut Window,
 6752        cx: &mut Context<Self>,
 6753    ) {
 6754        self.duplicate(true, true, window, cx);
 6755    }
 6756
 6757    pub fn duplicate_line_down(
 6758        &mut self,
 6759        _: &DuplicateLineDown,
 6760        window: &mut Window,
 6761        cx: &mut Context<Self>,
 6762    ) {
 6763        self.duplicate(false, true, window, cx);
 6764    }
 6765
 6766    pub fn duplicate_selection(
 6767        &mut self,
 6768        _: &DuplicateSelection,
 6769        window: &mut Window,
 6770        cx: &mut Context<Self>,
 6771    ) {
 6772        self.duplicate(false, false, window, cx);
 6773    }
 6774
 6775    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 6776        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6777        let buffer = self.buffer.read(cx).snapshot(cx);
 6778
 6779        let mut edits = Vec::new();
 6780        let mut unfold_ranges = Vec::new();
 6781        let mut refold_creases = Vec::new();
 6782
 6783        let selections = self.selections.all::<Point>(cx);
 6784        let mut selections = selections.iter().peekable();
 6785        let mut contiguous_row_selections = Vec::new();
 6786        let mut new_selections = Vec::new();
 6787
 6788        while let Some(selection) = selections.next() {
 6789            // Find all the selections that span a contiguous row range
 6790            let (start_row, end_row) = consume_contiguous_rows(
 6791                &mut contiguous_row_selections,
 6792                selection,
 6793                &display_map,
 6794                &mut selections,
 6795            );
 6796
 6797            // Move the text spanned by the row range to be before the line preceding the row range
 6798            if start_row.0 > 0 {
 6799                let range_to_move = Point::new(
 6800                    start_row.previous_row().0,
 6801                    buffer.line_len(start_row.previous_row()),
 6802                )
 6803                    ..Point::new(
 6804                        end_row.previous_row().0,
 6805                        buffer.line_len(end_row.previous_row()),
 6806                    );
 6807                let insertion_point = display_map
 6808                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6809                    .0;
 6810
 6811                // Don't move lines across excerpts
 6812                if buffer
 6813                    .excerpt_containing(insertion_point..range_to_move.end)
 6814                    .is_some()
 6815                {
 6816                    let text = buffer
 6817                        .text_for_range(range_to_move.clone())
 6818                        .flat_map(|s| s.chars())
 6819                        .skip(1)
 6820                        .chain(['\n'])
 6821                        .collect::<String>();
 6822
 6823                    edits.push((
 6824                        buffer.anchor_after(range_to_move.start)
 6825                            ..buffer.anchor_before(range_to_move.end),
 6826                        String::new(),
 6827                    ));
 6828                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6829                    edits.push((insertion_anchor..insertion_anchor, text));
 6830
 6831                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6832
 6833                    // Move selections up
 6834                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6835                        |mut selection| {
 6836                            selection.start.row -= row_delta;
 6837                            selection.end.row -= row_delta;
 6838                            selection
 6839                        },
 6840                    ));
 6841
 6842                    // Move folds up
 6843                    unfold_ranges.push(range_to_move.clone());
 6844                    for fold in display_map.folds_in_range(
 6845                        buffer.anchor_before(range_to_move.start)
 6846                            ..buffer.anchor_after(range_to_move.end),
 6847                    ) {
 6848                        let mut start = fold.range.start.to_point(&buffer);
 6849                        let mut end = fold.range.end.to_point(&buffer);
 6850                        start.row -= row_delta;
 6851                        end.row -= row_delta;
 6852                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6853                    }
 6854                }
 6855            }
 6856
 6857            // If we didn't move line(s), preserve the existing selections
 6858            new_selections.append(&mut contiguous_row_selections);
 6859        }
 6860
 6861        self.transact(window, cx, |this, window, cx| {
 6862            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6863            this.buffer.update(cx, |buffer, cx| {
 6864                for (range, text) in edits {
 6865                    buffer.edit([(range, text)], None, cx);
 6866                }
 6867            });
 6868            this.fold_creases(refold_creases, true, window, cx);
 6869            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6870                s.select(new_selections);
 6871            })
 6872        });
 6873    }
 6874
 6875    pub fn move_line_down(
 6876        &mut self,
 6877        _: &MoveLineDown,
 6878        window: &mut Window,
 6879        cx: &mut Context<Self>,
 6880    ) {
 6881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6882        let buffer = self.buffer.read(cx).snapshot(cx);
 6883
 6884        let mut edits = Vec::new();
 6885        let mut unfold_ranges = Vec::new();
 6886        let mut refold_creases = Vec::new();
 6887
 6888        let selections = self.selections.all::<Point>(cx);
 6889        let mut selections = selections.iter().peekable();
 6890        let mut contiguous_row_selections = Vec::new();
 6891        let mut new_selections = Vec::new();
 6892
 6893        while let Some(selection) = selections.next() {
 6894            // Find all the selections that span a contiguous row range
 6895            let (start_row, end_row) = consume_contiguous_rows(
 6896                &mut contiguous_row_selections,
 6897                selection,
 6898                &display_map,
 6899                &mut selections,
 6900            );
 6901
 6902            // Move the text spanned by the row range to be after the last line of the row range
 6903            if end_row.0 <= buffer.max_point().row {
 6904                let range_to_move =
 6905                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6906                let insertion_point = display_map
 6907                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6908                    .0;
 6909
 6910                // Don't move lines across excerpt boundaries
 6911                if buffer
 6912                    .excerpt_containing(range_to_move.start..insertion_point)
 6913                    .is_some()
 6914                {
 6915                    let mut text = String::from("\n");
 6916                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6917                    text.pop(); // Drop trailing newline
 6918                    edits.push((
 6919                        buffer.anchor_after(range_to_move.start)
 6920                            ..buffer.anchor_before(range_to_move.end),
 6921                        String::new(),
 6922                    ));
 6923                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6924                    edits.push((insertion_anchor..insertion_anchor, text));
 6925
 6926                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6927
 6928                    // Move selections down
 6929                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6930                        |mut selection| {
 6931                            selection.start.row += row_delta;
 6932                            selection.end.row += row_delta;
 6933                            selection
 6934                        },
 6935                    ));
 6936
 6937                    // Move folds down
 6938                    unfold_ranges.push(range_to_move.clone());
 6939                    for fold in display_map.folds_in_range(
 6940                        buffer.anchor_before(range_to_move.start)
 6941                            ..buffer.anchor_after(range_to_move.end),
 6942                    ) {
 6943                        let mut start = fold.range.start.to_point(&buffer);
 6944                        let mut end = fold.range.end.to_point(&buffer);
 6945                        start.row += row_delta;
 6946                        end.row += row_delta;
 6947                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6948                    }
 6949                }
 6950            }
 6951
 6952            // If we didn't move line(s), preserve the existing selections
 6953            new_selections.append(&mut contiguous_row_selections);
 6954        }
 6955
 6956        self.transact(window, cx, |this, window, cx| {
 6957            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6958            this.buffer.update(cx, |buffer, cx| {
 6959                for (range, text) in edits {
 6960                    buffer.edit([(range, text)], None, cx);
 6961                }
 6962            });
 6963            this.fold_creases(refold_creases, true, window, cx);
 6964            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6965                s.select(new_selections)
 6966            });
 6967        });
 6968    }
 6969
 6970    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 6971        let text_layout_details = &self.text_layout_details(window);
 6972        self.transact(window, cx, |this, window, cx| {
 6973            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6974                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6975                let line_mode = s.line_mode;
 6976                s.move_with(|display_map, selection| {
 6977                    if !selection.is_empty() || line_mode {
 6978                        return;
 6979                    }
 6980
 6981                    let mut head = selection.head();
 6982                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6983                    if head.column() == display_map.line_len(head.row()) {
 6984                        transpose_offset = display_map
 6985                            .buffer_snapshot
 6986                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6987                    }
 6988
 6989                    if transpose_offset == 0 {
 6990                        return;
 6991                    }
 6992
 6993                    *head.column_mut() += 1;
 6994                    head = display_map.clip_point(head, Bias::Right);
 6995                    let goal = SelectionGoal::HorizontalPosition(
 6996                        display_map
 6997                            .x_for_display_point(head, text_layout_details)
 6998                            .into(),
 6999                    );
 7000                    selection.collapse_to(head, goal);
 7001
 7002                    let transpose_start = display_map
 7003                        .buffer_snapshot
 7004                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7005                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7006                        let transpose_end = display_map
 7007                            .buffer_snapshot
 7008                            .clip_offset(transpose_offset + 1, Bias::Right);
 7009                        if let Some(ch) =
 7010                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7011                        {
 7012                            edits.push((transpose_start..transpose_offset, String::new()));
 7013                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7014                        }
 7015                    }
 7016                });
 7017                edits
 7018            });
 7019            this.buffer
 7020                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7021            let selections = this.selections.all::<usize>(cx);
 7022            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7023                s.select(selections);
 7024            });
 7025        });
 7026    }
 7027
 7028    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7029        self.rewrap_impl(IsVimMode::No, cx)
 7030    }
 7031
 7032    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7033        let buffer = self.buffer.read(cx).snapshot(cx);
 7034        let selections = self.selections.all::<Point>(cx);
 7035        let mut selections = selections.iter().peekable();
 7036
 7037        let mut edits = Vec::new();
 7038        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7039
 7040        while let Some(selection) = selections.next() {
 7041            let mut start_row = selection.start.row;
 7042            let mut end_row = selection.end.row;
 7043
 7044            // Skip selections that overlap with a range that has already been rewrapped.
 7045            let selection_range = start_row..end_row;
 7046            if rewrapped_row_ranges
 7047                .iter()
 7048                .any(|range| range.overlaps(&selection_range))
 7049            {
 7050                continue;
 7051            }
 7052
 7053            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7054
 7055            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7056                match language_scope.language_name().as_ref() {
 7057                    "Markdown" | "Plain Text" => {
 7058                        should_rewrap = true;
 7059                    }
 7060                    _ => {}
 7061                }
 7062            }
 7063
 7064            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7065
 7066            // Since not all lines in the selection may be at the same indent
 7067            // level, choose the indent size that is the most common between all
 7068            // of the lines.
 7069            //
 7070            // If there is a tie, we use the deepest indent.
 7071            let (indent_size, indent_end) = {
 7072                let mut indent_size_occurrences = HashMap::default();
 7073                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7074
 7075                for row in start_row..=end_row {
 7076                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7077                    rows_by_indent_size.entry(indent).or_default().push(row);
 7078                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7079                }
 7080
 7081                let indent_size = indent_size_occurrences
 7082                    .into_iter()
 7083                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7084                    .map(|(indent, _)| indent)
 7085                    .unwrap_or_default();
 7086                let row = rows_by_indent_size[&indent_size][0];
 7087                let indent_end = Point::new(row, indent_size.len);
 7088
 7089                (indent_size, indent_end)
 7090            };
 7091
 7092            let mut line_prefix = indent_size.chars().collect::<String>();
 7093
 7094            if let Some(comment_prefix) =
 7095                buffer
 7096                    .language_scope_at(selection.head())
 7097                    .and_then(|language| {
 7098                        language
 7099                            .line_comment_prefixes()
 7100                            .iter()
 7101                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7102                            .cloned()
 7103                    })
 7104            {
 7105                line_prefix.push_str(&comment_prefix);
 7106                should_rewrap = true;
 7107            }
 7108
 7109            if !should_rewrap {
 7110                continue;
 7111            }
 7112
 7113            if selection.is_empty() {
 7114                'expand_upwards: while start_row > 0 {
 7115                    let prev_row = start_row - 1;
 7116                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7117                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7118                    {
 7119                        start_row = prev_row;
 7120                    } else {
 7121                        break 'expand_upwards;
 7122                    }
 7123                }
 7124
 7125                'expand_downwards: while end_row < buffer.max_point().row {
 7126                    let next_row = end_row + 1;
 7127                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7128                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7129                    {
 7130                        end_row = next_row;
 7131                    } else {
 7132                        break 'expand_downwards;
 7133                    }
 7134                }
 7135            }
 7136
 7137            let start = Point::new(start_row, 0);
 7138            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7139            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7140            let Some(lines_without_prefixes) = selection_text
 7141                .lines()
 7142                .map(|line| {
 7143                    line.strip_prefix(&line_prefix)
 7144                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7145                        .ok_or_else(|| {
 7146                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7147                        })
 7148                })
 7149                .collect::<Result<Vec<_>, _>>()
 7150                .log_err()
 7151            else {
 7152                continue;
 7153            };
 7154
 7155            let wrap_column = buffer
 7156                .settings_at(Point::new(start_row, 0), cx)
 7157                .preferred_line_length as usize;
 7158            let wrapped_text = wrap_with_prefix(
 7159                line_prefix,
 7160                lines_without_prefixes.join(" "),
 7161                wrap_column,
 7162                tab_size,
 7163            );
 7164
 7165            // TODO: should always use char-based diff while still supporting cursor behavior that
 7166            // matches vim.
 7167            let diff = match is_vim_mode {
 7168                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7169                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7170            };
 7171            let mut offset = start.to_offset(&buffer);
 7172            let mut moved_since_edit = true;
 7173
 7174            for change in diff.iter_all_changes() {
 7175                let value = change.value();
 7176                match change.tag() {
 7177                    ChangeTag::Equal => {
 7178                        offset += value.len();
 7179                        moved_since_edit = true;
 7180                    }
 7181                    ChangeTag::Delete => {
 7182                        let start = buffer.anchor_after(offset);
 7183                        let end = buffer.anchor_before(offset + value.len());
 7184
 7185                        if moved_since_edit {
 7186                            edits.push((start..end, String::new()));
 7187                        } else {
 7188                            edits.last_mut().unwrap().0.end = end;
 7189                        }
 7190
 7191                        offset += value.len();
 7192                        moved_since_edit = false;
 7193                    }
 7194                    ChangeTag::Insert => {
 7195                        if moved_since_edit {
 7196                            let anchor = buffer.anchor_after(offset);
 7197                            edits.push((anchor..anchor, value.to_string()));
 7198                        } else {
 7199                            edits.last_mut().unwrap().1.push_str(value);
 7200                        }
 7201
 7202                        moved_since_edit = false;
 7203                    }
 7204                }
 7205            }
 7206
 7207            rewrapped_row_ranges.push(start_row..=end_row);
 7208        }
 7209
 7210        self.buffer
 7211            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7212    }
 7213
 7214    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7215        let mut text = String::new();
 7216        let buffer = self.buffer.read(cx).snapshot(cx);
 7217        let mut selections = self.selections.all::<Point>(cx);
 7218        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7219        {
 7220            let max_point = buffer.max_point();
 7221            let mut is_first = true;
 7222            for selection in &mut selections {
 7223                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7224                if is_entire_line {
 7225                    selection.start = Point::new(selection.start.row, 0);
 7226                    if !selection.is_empty() && selection.end.column == 0 {
 7227                        selection.end = cmp::min(max_point, selection.end);
 7228                    } else {
 7229                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7230                    }
 7231                    selection.goal = SelectionGoal::None;
 7232                }
 7233                if is_first {
 7234                    is_first = false;
 7235                } else {
 7236                    text += "\n";
 7237                }
 7238                let mut len = 0;
 7239                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7240                    text.push_str(chunk);
 7241                    len += chunk.len();
 7242                }
 7243                clipboard_selections.push(ClipboardSelection {
 7244                    len,
 7245                    is_entire_line,
 7246                    first_line_indent: buffer
 7247                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7248                        .len,
 7249                });
 7250            }
 7251        }
 7252
 7253        self.transact(window, cx, |this, window, cx| {
 7254            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7255                s.select(selections);
 7256            });
 7257            this.insert("", window, cx);
 7258        });
 7259        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7260    }
 7261
 7262    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7263        let item = self.cut_common(window, cx);
 7264        cx.write_to_clipboard(item);
 7265    }
 7266
 7267    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7268        self.change_selections(None, window, cx, |s| {
 7269            s.move_with(|snapshot, sel| {
 7270                if sel.is_empty() {
 7271                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7272                }
 7273            });
 7274        });
 7275        let item = self.cut_common(window, cx);
 7276        cx.set_global(KillRing(item))
 7277    }
 7278
 7279    pub fn kill_ring_yank(
 7280        &mut self,
 7281        _: &KillRingYank,
 7282        window: &mut Window,
 7283        cx: &mut Context<Self>,
 7284    ) {
 7285        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7286            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7287                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7288            } else {
 7289                return;
 7290            }
 7291        } else {
 7292            return;
 7293        };
 7294        self.do_paste(&text, metadata, false, window, cx);
 7295    }
 7296
 7297    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7298        let selections = self.selections.all::<Point>(cx);
 7299        let buffer = self.buffer.read(cx).read(cx);
 7300        let mut text = String::new();
 7301
 7302        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7303        {
 7304            let max_point = buffer.max_point();
 7305            let mut is_first = true;
 7306            for selection in selections.iter() {
 7307                let mut start = selection.start;
 7308                let mut end = selection.end;
 7309                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7310                if is_entire_line {
 7311                    start = Point::new(start.row, 0);
 7312                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7313                }
 7314                if is_first {
 7315                    is_first = false;
 7316                } else {
 7317                    text += "\n";
 7318                }
 7319                let mut len = 0;
 7320                for chunk in buffer.text_for_range(start..end) {
 7321                    text.push_str(chunk);
 7322                    len += chunk.len();
 7323                }
 7324                clipboard_selections.push(ClipboardSelection {
 7325                    len,
 7326                    is_entire_line,
 7327                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7328                });
 7329            }
 7330        }
 7331
 7332        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7333            text,
 7334            clipboard_selections,
 7335        ));
 7336    }
 7337
 7338    pub fn do_paste(
 7339        &mut self,
 7340        text: &String,
 7341        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7342        handle_entire_lines: bool,
 7343        window: &mut Window,
 7344        cx: &mut Context<Self>,
 7345    ) {
 7346        if self.read_only(cx) {
 7347            return;
 7348        }
 7349
 7350        let clipboard_text = Cow::Borrowed(text);
 7351
 7352        self.transact(window, cx, |this, window, cx| {
 7353            if let Some(mut clipboard_selections) = clipboard_selections {
 7354                let old_selections = this.selections.all::<usize>(cx);
 7355                let all_selections_were_entire_line =
 7356                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7357                let first_selection_indent_column =
 7358                    clipboard_selections.first().map(|s| s.first_line_indent);
 7359                if clipboard_selections.len() != old_selections.len() {
 7360                    clipboard_selections.drain(..);
 7361                }
 7362                let cursor_offset = this.selections.last::<usize>(cx).head();
 7363                let mut auto_indent_on_paste = true;
 7364
 7365                this.buffer.update(cx, |buffer, cx| {
 7366                    let snapshot = buffer.read(cx);
 7367                    auto_indent_on_paste =
 7368                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7369
 7370                    let mut start_offset = 0;
 7371                    let mut edits = Vec::new();
 7372                    let mut original_indent_columns = Vec::new();
 7373                    for (ix, selection) in old_selections.iter().enumerate() {
 7374                        let to_insert;
 7375                        let entire_line;
 7376                        let original_indent_column;
 7377                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7378                            let end_offset = start_offset + clipboard_selection.len;
 7379                            to_insert = &clipboard_text[start_offset..end_offset];
 7380                            entire_line = clipboard_selection.is_entire_line;
 7381                            start_offset = end_offset + 1;
 7382                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7383                        } else {
 7384                            to_insert = clipboard_text.as_str();
 7385                            entire_line = all_selections_were_entire_line;
 7386                            original_indent_column = first_selection_indent_column
 7387                        }
 7388
 7389                        // If the corresponding selection was empty when this slice of the
 7390                        // clipboard text was written, then the entire line containing the
 7391                        // selection was copied. If this selection is also currently empty,
 7392                        // then paste the line before the current line of the buffer.
 7393                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7394                            let column = selection.start.to_point(&snapshot).column as usize;
 7395                            let line_start = selection.start - column;
 7396                            line_start..line_start
 7397                        } else {
 7398                            selection.range()
 7399                        };
 7400
 7401                        edits.push((range, to_insert));
 7402                        original_indent_columns.extend(original_indent_column);
 7403                    }
 7404                    drop(snapshot);
 7405
 7406                    buffer.edit(
 7407                        edits,
 7408                        if auto_indent_on_paste {
 7409                            Some(AutoindentMode::Block {
 7410                                original_indent_columns,
 7411                            })
 7412                        } else {
 7413                            None
 7414                        },
 7415                        cx,
 7416                    );
 7417                });
 7418
 7419                let selections = this.selections.all::<usize>(cx);
 7420                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7421                    s.select(selections)
 7422                });
 7423            } else {
 7424                this.insert(&clipboard_text, window, cx);
 7425            }
 7426        });
 7427    }
 7428
 7429    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7430        if let Some(item) = cx.read_from_clipboard() {
 7431            let entries = item.entries();
 7432
 7433            match entries.first() {
 7434                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7435                // of all the pasted entries.
 7436                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7437                    .do_paste(
 7438                        clipboard_string.text(),
 7439                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7440                        true,
 7441                        window,
 7442                        cx,
 7443                    ),
 7444                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7445            }
 7446        }
 7447    }
 7448
 7449    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7450        if self.read_only(cx) {
 7451            return;
 7452        }
 7453
 7454        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7455            if let Some((selections, _)) =
 7456                self.selection_history.transaction(transaction_id).cloned()
 7457            {
 7458                self.change_selections(None, window, cx, |s| {
 7459                    s.select_anchors(selections.to_vec());
 7460                });
 7461            }
 7462            self.request_autoscroll(Autoscroll::fit(), cx);
 7463            self.unmark_text(window, cx);
 7464            self.refresh_inline_completion(true, false, window, cx);
 7465            cx.emit(EditorEvent::Edited { transaction_id });
 7466            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7467        }
 7468    }
 7469
 7470    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7471        if self.read_only(cx) {
 7472            return;
 7473        }
 7474
 7475        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7476            if let Some((_, Some(selections))) =
 7477                self.selection_history.transaction(transaction_id).cloned()
 7478            {
 7479                self.change_selections(None, window, cx, |s| {
 7480                    s.select_anchors(selections.to_vec());
 7481                });
 7482            }
 7483            self.request_autoscroll(Autoscroll::fit(), cx);
 7484            self.unmark_text(window, cx);
 7485            self.refresh_inline_completion(true, false, window, cx);
 7486            cx.emit(EditorEvent::Edited { transaction_id });
 7487        }
 7488    }
 7489
 7490    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7491        self.buffer
 7492            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7493    }
 7494
 7495    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7496        self.buffer
 7497            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7498    }
 7499
 7500    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7501        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7502            let line_mode = s.line_mode;
 7503            s.move_with(|map, selection| {
 7504                let cursor = if selection.is_empty() && !line_mode {
 7505                    movement::left(map, selection.start)
 7506                } else {
 7507                    selection.start
 7508                };
 7509                selection.collapse_to(cursor, SelectionGoal::None);
 7510            });
 7511        })
 7512    }
 7513
 7514    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7515        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7516            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7517        })
 7518    }
 7519
 7520    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7522            let line_mode = s.line_mode;
 7523            s.move_with(|map, selection| {
 7524                let cursor = if selection.is_empty() && !line_mode {
 7525                    movement::right(map, selection.end)
 7526                } else {
 7527                    selection.end
 7528                };
 7529                selection.collapse_to(cursor, SelectionGoal::None)
 7530            });
 7531        })
 7532    }
 7533
 7534    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7535        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7536            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7537        })
 7538    }
 7539
 7540    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7541        if self.take_rename(true, window, cx).is_some() {
 7542            return;
 7543        }
 7544
 7545        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7546            cx.propagate();
 7547            return;
 7548        }
 7549
 7550        let text_layout_details = &self.text_layout_details(window);
 7551        let selection_count = self.selections.count();
 7552        let first_selection = self.selections.first_anchor();
 7553
 7554        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7555            let line_mode = s.line_mode;
 7556            s.move_with(|map, selection| {
 7557                if !selection.is_empty() && !line_mode {
 7558                    selection.goal = SelectionGoal::None;
 7559                }
 7560                let (cursor, goal) = movement::up(
 7561                    map,
 7562                    selection.start,
 7563                    selection.goal,
 7564                    false,
 7565                    text_layout_details,
 7566                );
 7567                selection.collapse_to(cursor, goal);
 7568            });
 7569        });
 7570
 7571        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7572        {
 7573            cx.propagate();
 7574        }
 7575    }
 7576
 7577    pub fn move_up_by_lines(
 7578        &mut self,
 7579        action: &MoveUpByLines,
 7580        window: &mut Window,
 7581        cx: &mut Context<Self>,
 7582    ) {
 7583        if self.take_rename(true, window, cx).is_some() {
 7584            return;
 7585        }
 7586
 7587        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7588            cx.propagate();
 7589            return;
 7590        }
 7591
 7592        let text_layout_details = &self.text_layout_details(window);
 7593
 7594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7595            let line_mode = s.line_mode;
 7596            s.move_with(|map, selection| {
 7597                if !selection.is_empty() && !line_mode {
 7598                    selection.goal = SelectionGoal::None;
 7599                }
 7600                let (cursor, goal) = movement::up_by_rows(
 7601                    map,
 7602                    selection.start,
 7603                    action.lines,
 7604                    selection.goal,
 7605                    false,
 7606                    text_layout_details,
 7607                );
 7608                selection.collapse_to(cursor, goal);
 7609            });
 7610        })
 7611    }
 7612
 7613    pub fn move_down_by_lines(
 7614        &mut self,
 7615        action: &MoveDownByLines,
 7616        window: &mut Window,
 7617        cx: &mut Context<Self>,
 7618    ) {
 7619        if self.take_rename(true, window, cx).is_some() {
 7620            return;
 7621        }
 7622
 7623        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7624            cx.propagate();
 7625            return;
 7626        }
 7627
 7628        let text_layout_details = &self.text_layout_details(window);
 7629
 7630        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7631            let line_mode = s.line_mode;
 7632            s.move_with(|map, selection| {
 7633                if !selection.is_empty() && !line_mode {
 7634                    selection.goal = SelectionGoal::None;
 7635                }
 7636                let (cursor, goal) = movement::down_by_rows(
 7637                    map,
 7638                    selection.start,
 7639                    action.lines,
 7640                    selection.goal,
 7641                    false,
 7642                    text_layout_details,
 7643                );
 7644                selection.collapse_to(cursor, goal);
 7645            });
 7646        })
 7647    }
 7648
 7649    pub fn select_down_by_lines(
 7650        &mut self,
 7651        action: &SelectDownByLines,
 7652        window: &mut Window,
 7653        cx: &mut Context<Self>,
 7654    ) {
 7655        let text_layout_details = &self.text_layout_details(window);
 7656        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7657            s.move_heads_with(|map, head, goal| {
 7658                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7659            })
 7660        })
 7661    }
 7662
 7663    pub fn select_up_by_lines(
 7664        &mut self,
 7665        action: &SelectUpByLines,
 7666        window: &mut Window,
 7667        cx: &mut Context<Self>,
 7668    ) {
 7669        let text_layout_details = &self.text_layout_details(window);
 7670        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7671            s.move_heads_with(|map, head, goal| {
 7672                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7673            })
 7674        })
 7675    }
 7676
 7677    pub fn select_page_up(
 7678        &mut self,
 7679        _: &SelectPageUp,
 7680        window: &mut Window,
 7681        cx: &mut Context<Self>,
 7682    ) {
 7683        let Some(row_count) = self.visible_row_count() else {
 7684            return;
 7685        };
 7686
 7687        let text_layout_details = &self.text_layout_details(window);
 7688
 7689        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7690            s.move_heads_with(|map, head, goal| {
 7691                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7692            })
 7693        })
 7694    }
 7695
 7696    pub fn move_page_up(
 7697        &mut self,
 7698        action: &MovePageUp,
 7699        window: &mut Window,
 7700        cx: &mut Context<Self>,
 7701    ) {
 7702        if self.take_rename(true, window, cx).is_some() {
 7703            return;
 7704        }
 7705
 7706        if self
 7707            .context_menu
 7708            .borrow_mut()
 7709            .as_mut()
 7710            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7711            .unwrap_or(false)
 7712        {
 7713            return;
 7714        }
 7715
 7716        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7717            cx.propagate();
 7718            return;
 7719        }
 7720
 7721        let Some(row_count) = self.visible_row_count() else {
 7722            return;
 7723        };
 7724
 7725        let autoscroll = if action.center_cursor {
 7726            Autoscroll::center()
 7727        } else {
 7728            Autoscroll::fit()
 7729        };
 7730
 7731        let text_layout_details = &self.text_layout_details(window);
 7732
 7733        self.change_selections(Some(autoscroll), window, cx, |s| {
 7734            let line_mode = s.line_mode;
 7735            s.move_with(|map, selection| {
 7736                if !selection.is_empty() && !line_mode {
 7737                    selection.goal = SelectionGoal::None;
 7738                }
 7739                let (cursor, goal) = movement::up_by_rows(
 7740                    map,
 7741                    selection.end,
 7742                    row_count,
 7743                    selection.goal,
 7744                    false,
 7745                    text_layout_details,
 7746                );
 7747                selection.collapse_to(cursor, goal);
 7748            });
 7749        });
 7750    }
 7751
 7752    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 7753        let text_layout_details = &self.text_layout_details(window);
 7754        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7755            s.move_heads_with(|map, head, goal| {
 7756                movement::up(map, head, goal, false, text_layout_details)
 7757            })
 7758        })
 7759    }
 7760
 7761    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 7762        self.take_rename(true, window, cx);
 7763
 7764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7765            cx.propagate();
 7766            return;
 7767        }
 7768
 7769        let text_layout_details = &self.text_layout_details(window);
 7770        let selection_count = self.selections.count();
 7771        let first_selection = self.selections.first_anchor();
 7772
 7773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7774            let line_mode = s.line_mode;
 7775            s.move_with(|map, selection| {
 7776                if !selection.is_empty() && !line_mode {
 7777                    selection.goal = SelectionGoal::None;
 7778                }
 7779                let (cursor, goal) = movement::down(
 7780                    map,
 7781                    selection.end,
 7782                    selection.goal,
 7783                    false,
 7784                    text_layout_details,
 7785                );
 7786                selection.collapse_to(cursor, goal);
 7787            });
 7788        });
 7789
 7790        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7791        {
 7792            cx.propagate();
 7793        }
 7794    }
 7795
 7796    pub fn select_page_down(
 7797        &mut self,
 7798        _: &SelectPageDown,
 7799        window: &mut Window,
 7800        cx: &mut Context<Self>,
 7801    ) {
 7802        let Some(row_count) = self.visible_row_count() else {
 7803            return;
 7804        };
 7805
 7806        let text_layout_details = &self.text_layout_details(window);
 7807
 7808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7809            s.move_heads_with(|map, head, goal| {
 7810                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7811            })
 7812        })
 7813    }
 7814
 7815    pub fn move_page_down(
 7816        &mut self,
 7817        action: &MovePageDown,
 7818        window: &mut Window,
 7819        cx: &mut Context<Self>,
 7820    ) {
 7821        if self.take_rename(true, window, cx).is_some() {
 7822            return;
 7823        }
 7824
 7825        if self
 7826            .context_menu
 7827            .borrow_mut()
 7828            .as_mut()
 7829            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7830            .unwrap_or(false)
 7831        {
 7832            return;
 7833        }
 7834
 7835        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7836            cx.propagate();
 7837            return;
 7838        }
 7839
 7840        let Some(row_count) = self.visible_row_count() else {
 7841            return;
 7842        };
 7843
 7844        let autoscroll = if action.center_cursor {
 7845            Autoscroll::center()
 7846        } else {
 7847            Autoscroll::fit()
 7848        };
 7849
 7850        let text_layout_details = &self.text_layout_details(window);
 7851        self.change_selections(Some(autoscroll), window, cx, |s| {
 7852            let line_mode = s.line_mode;
 7853            s.move_with(|map, selection| {
 7854                if !selection.is_empty() && !line_mode {
 7855                    selection.goal = SelectionGoal::None;
 7856                }
 7857                let (cursor, goal) = movement::down_by_rows(
 7858                    map,
 7859                    selection.end,
 7860                    row_count,
 7861                    selection.goal,
 7862                    false,
 7863                    text_layout_details,
 7864                );
 7865                selection.collapse_to(cursor, goal);
 7866            });
 7867        });
 7868    }
 7869
 7870    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 7871        let text_layout_details = &self.text_layout_details(window);
 7872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7873            s.move_heads_with(|map, head, goal| {
 7874                movement::down(map, head, goal, false, text_layout_details)
 7875            })
 7876        });
 7877    }
 7878
 7879    pub fn context_menu_first(
 7880        &mut self,
 7881        _: &ContextMenuFirst,
 7882        _window: &mut Window,
 7883        cx: &mut Context<Self>,
 7884    ) {
 7885        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7886            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7887        }
 7888    }
 7889
 7890    pub fn context_menu_prev(
 7891        &mut self,
 7892        _: &ContextMenuPrev,
 7893        _window: &mut Window,
 7894        cx: &mut Context<Self>,
 7895    ) {
 7896        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7897            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7898        }
 7899    }
 7900
 7901    pub fn context_menu_next(
 7902        &mut self,
 7903        _: &ContextMenuNext,
 7904        _window: &mut Window,
 7905        cx: &mut Context<Self>,
 7906    ) {
 7907        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7908            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7909        }
 7910    }
 7911
 7912    pub fn context_menu_last(
 7913        &mut self,
 7914        _: &ContextMenuLast,
 7915        _window: &mut Window,
 7916        cx: &mut Context<Self>,
 7917    ) {
 7918        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7919            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7920        }
 7921    }
 7922
 7923    pub fn move_to_previous_word_start(
 7924        &mut self,
 7925        _: &MoveToPreviousWordStart,
 7926        window: &mut Window,
 7927        cx: &mut Context<Self>,
 7928    ) {
 7929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7930            s.move_cursors_with(|map, head, _| {
 7931                (
 7932                    movement::previous_word_start(map, head),
 7933                    SelectionGoal::None,
 7934                )
 7935            });
 7936        })
 7937    }
 7938
 7939    pub fn move_to_previous_subword_start(
 7940        &mut self,
 7941        _: &MoveToPreviousSubwordStart,
 7942        window: &mut Window,
 7943        cx: &mut Context<Self>,
 7944    ) {
 7945        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7946            s.move_cursors_with(|map, head, _| {
 7947                (
 7948                    movement::previous_subword_start(map, head),
 7949                    SelectionGoal::None,
 7950                )
 7951            });
 7952        })
 7953    }
 7954
 7955    pub fn select_to_previous_word_start(
 7956        &mut self,
 7957        _: &SelectToPreviousWordStart,
 7958        window: &mut Window,
 7959        cx: &mut Context<Self>,
 7960    ) {
 7961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7962            s.move_heads_with(|map, head, _| {
 7963                (
 7964                    movement::previous_word_start(map, head),
 7965                    SelectionGoal::None,
 7966                )
 7967            });
 7968        })
 7969    }
 7970
 7971    pub fn select_to_previous_subword_start(
 7972        &mut self,
 7973        _: &SelectToPreviousSubwordStart,
 7974        window: &mut Window,
 7975        cx: &mut Context<Self>,
 7976    ) {
 7977        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7978            s.move_heads_with(|map, head, _| {
 7979                (
 7980                    movement::previous_subword_start(map, head),
 7981                    SelectionGoal::None,
 7982                )
 7983            });
 7984        })
 7985    }
 7986
 7987    pub fn delete_to_previous_word_start(
 7988        &mut self,
 7989        action: &DeleteToPreviousWordStart,
 7990        window: &mut Window,
 7991        cx: &mut Context<Self>,
 7992    ) {
 7993        self.transact(window, cx, |this, window, cx| {
 7994            this.select_autoclose_pair(window, cx);
 7995            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7996                let line_mode = s.line_mode;
 7997                s.move_with(|map, selection| {
 7998                    if selection.is_empty() && !line_mode {
 7999                        let cursor = if action.ignore_newlines {
 8000                            movement::previous_word_start(map, selection.head())
 8001                        } else {
 8002                            movement::previous_word_start_or_newline(map, selection.head())
 8003                        };
 8004                        selection.set_head(cursor, SelectionGoal::None);
 8005                    }
 8006                });
 8007            });
 8008            this.insert("", window, cx);
 8009        });
 8010    }
 8011
 8012    pub fn delete_to_previous_subword_start(
 8013        &mut self,
 8014        _: &DeleteToPreviousSubwordStart,
 8015        window: &mut Window,
 8016        cx: &mut Context<Self>,
 8017    ) {
 8018        self.transact(window, cx, |this, window, cx| {
 8019            this.select_autoclose_pair(window, cx);
 8020            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8021                let line_mode = s.line_mode;
 8022                s.move_with(|map, selection| {
 8023                    if selection.is_empty() && !line_mode {
 8024                        let cursor = movement::previous_subword_start(map, selection.head());
 8025                        selection.set_head(cursor, SelectionGoal::None);
 8026                    }
 8027                });
 8028            });
 8029            this.insert("", window, cx);
 8030        });
 8031    }
 8032
 8033    pub fn move_to_next_word_end(
 8034        &mut self,
 8035        _: &MoveToNextWordEnd,
 8036        window: &mut Window,
 8037        cx: &mut Context<Self>,
 8038    ) {
 8039        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8040            s.move_cursors_with(|map, head, _| {
 8041                (movement::next_word_end(map, head), SelectionGoal::None)
 8042            });
 8043        })
 8044    }
 8045
 8046    pub fn move_to_next_subword_end(
 8047        &mut self,
 8048        _: &MoveToNextSubwordEnd,
 8049        window: &mut Window,
 8050        cx: &mut Context<Self>,
 8051    ) {
 8052        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8053            s.move_cursors_with(|map, head, _| {
 8054                (movement::next_subword_end(map, head), SelectionGoal::None)
 8055            });
 8056        })
 8057    }
 8058
 8059    pub fn select_to_next_word_end(
 8060        &mut self,
 8061        _: &SelectToNextWordEnd,
 8062        window: &mut Window,
 8063        cx: &mut Context<Self>,
 8064    ) {
 8065        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8066            s.move_heads_with(|map, head, _| {
 8067                (movement::next_word_end(map, head), SelectionGoal::None)
 8068            });
 8069        })
 8070    }
 8071
 8072    pub fn select_to_next_subword_end(
 8073        &mut self,
 8074        _: &SelectToNextSubwordEnd,
 8075        window: &mut Window,
 8076        cx: &mut Context<Self>,
 8077    ) {
 8078        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8079            s.move_heads_with(|map, head, _| {
 8080                (movement::next_subword_end(map, head), SelectionGoal::None)
 8081            });
 8082        })
 8083    }
 8084
 8085    pub fn delete_to_next_word_end(
 8086        &mut self,
 8087        action: &DeleteToNextWordEnd,
 8088        window: &mut Window,
 8089        cx: &mut Context<Self>,
 8090    ) {
 8091        self.transact(window, cx, |this, window, cx| {
 8092            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8093                let line_mode = s.line_mode;
 8094                s.move_with(|map, selection| {
 8095                    if selection.is_empty() && !line_mode {
 8096                        let cursor = if action.ignore_newlines {
 8097                            movement::next_word_end(map, selection.head())
 8098                        } else {
 8099                            movement::next_word_end_or_newline(map, selection.head())
 8100                        };
 8101                        selection.set_head(cursor, SelectionGoal::None);
 8102                    }
 8103                });
 8104            });
 8105            this.insert("", window, cx);
 8106        });
 8107    }
 8108
 8109    pub fn delete_to_next_subword_end(
 8110        &mut self,
 8111        _: &DeleteToNextSubwordEnd,
 8112        window: &mut Window,
 8113        cx: &mut Context<Self>,
 8114    ) {
 8115        self.transact(window, cx, |this, window, cx| {
 8116            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8117                s.move_with(|map, selection| {
 8118                    if selection.is_empty() {
 8119                        let cursor = movement::next_subword_end(map, selection.head());
 8120                        selection.set_head(cursor, SelectionGoal::None);
 8121                    }
 8122                });
 8123            });
 8124            this.insert("", window, cx);
 8125        });
 8126    }
 8127
 8128    pub fn move_to_beginning_of_line(
 8129        &mut self,
 8130        action: &MoveToBeginningOfLine,
 8131        window: &mut Window,
 8132        cx: &mut Context<Self>,
 8133    ) {
 8134        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8135            s.move_cursors_with(|map, head, _| {
 8136                (
 8137                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8138                    SelectionGoal::None,
 8139                )
 8140            });
 8141        })
 8142    }
 8143
 8144    pub fn select_to_beginning_of_line(
 8145        &mut self,
 8146        action: &SelectToBeginningOfLine,
 8147        window: &mut Window,
 8148        cx: &mut Context<Self>,
 8149    ) {
 8150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8151            s.move_heads_with(|map, head, _| {
 8152                (
 8153                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8154                    SelectionGoal::None,
 8155                )
 8156            });
 8157        });
 8158    }
 8159
 8160    pub fn delete_to_beginning_of_line(
 8161        &mut self,
 8162        _: &DeleteToBeginningOfLine,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) {
 8166        self.transact(window, cx, |this, window, cx| {
 8167            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8168                s.move_with(|_, selection| {
 8169                    selection.reversed = true;
 8170                });
 8171            });
 8172
 8173            this.select_to_beginning_of_line(
 8174                &SelectToBeginningOfLine {
 8175                    stop_at_soft_wraps: false,
 8176                },
 8177                window,
 8178                cx,
 8179            );
 8180            this.backspace(&Backspace, window, cx);
 8181        });
 8182    }
 8183
 8184    pub fn move_to_end_of_line(
 8185        &mut self,
 8186        action: &MoveToEndOfLine,
 8187        window: &mut Window,
 8188        cx: &mut Context<Self>,
 8189    ) {
 8190        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8191            s.move_cursors_with(|map, head, _| {
 8192                (
 8193                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8194                    SelectionGoal::None,
 8195                )
 8196            });
 8197        })
 8198    }
 8199
 8200    pub fn select_to_end_of_line(
 8201        &mut self,
 8202        action: &SelectToEndOfLine,
 8203        window: &mut Window,
 8204        cx: &mut Context<Self>,
 8205    ) {
 8206        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8207            s.move_heads_with(|map, head, _| {
 8208                (
 8209                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8210                    SelectionGoal::None,
 8211                )
 8212            });
 8213        })
 8214    }
 8215
 8216    pub fn delete_to_end_of_line(
 8217        &mut self,
 8218        _: &DeleteToEndOfLine,
 8219        window: &mut Window,
 8220        cx: &mut Context<Self>,
 8221    ) {
 8222        self.transact(window, cx, |this, window, cx| {
 8223            this.select_to_end_of_line(
 8224                &SelectToEndOfLine {
 8225                    stop_at_soft_wraps: false,
 8226                },
 8227                window,
 8228                cx,
 8229            );
 8230            this.delete(&Delete, window, cx);
 8231        });
 8232    }
 8233
 8234    pub fn cut_to_end_of_line(
 8235        &mut self,
 8236        _: &CutToEndOfLine,
 8237        window: &mut Window,
 8238        cx: &mut Context<Self>,
 8239    ) {
 8240        self.transact(window, cx, |this, window, cx| {
 8241            this.select_to_end_of_line(
 8242                &SelectToEndOfLine {
 8243                    stop_at_soft_wraps: false,
 8244                },
 8245                window,
 8246                cx,
 8247            );
 8248            this.cut(&Cut, window, cx);
 8249        });
 8250    }
 8251
 8252    pub fn move_to_start_of_paragraph(
 8253        &mut self,
 8254        _: &MoveToStartOfParagraph,
 8255        window: &mut Window,
 8256        cx: &mut Context<Self>,
 8257    ) {
 8258        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8259            cx.propagate();
 8260            return;
 8261        }
 8262
 8263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8264            s.move_with(|map, selection| {
 8265                selection.collapse_to(
 8266                    movement::start_of_paragraph(map, selection.head(), 1),
 8267                    SelectionGoal::None,
 8268                )
 8269            });
 8270        })
 8271    }
 8272
 8273    pub fn move_to_end_of_paragraph(
 8274        &mut self,
 8275        _: &MoveToEndOfParagraph,
 8276        window: &mut Window,
 8277        cx: &mut Context<Self>,
 8278    ) {
 8279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8280            cx.propagate();
 8281            return;
 8282        }
 8283
 8284        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8285            s.move_with(|map, selection| {
 8286                selection.collapse_to(
 8287                    movement::end_of_paragraph(map, selection.head(), 1),
 8288                    SelectionGoal::None,
 8289                )
 8290            });
 8291        })
 8292    }
 8293
 8294    pub fn select_to_start_of_paragraph(
 8295        &mut self,
 8296        _: &SelectToStartOfParagraph,
 8297        window: &mut Window,
 8298        cx: &mut Context<Self>,
 8299    ) {
 8300        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8301            cx.propagate();
 8302            return;
 8303        }
 8304
 8305        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8306            s.move_heads_with(|map, head, _| {
 8307                (
 8308                    movement::start_of_paragraph(map, head, 1),
 8309                    SelectionGoal::None,
 8310                )
 8311            });
 8312        })
 8313    }
 8314
 8315    pub fn select_to_end_of_paragraph(
 8316        &mut self,
 8317        _: &SelectToEndOfParagraph,
 8318        window: &mut Window,
 8319        cx: &mut Context<Self>,
 8320    ) {
 8321        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8322            cx.propagate();
 8323            return;
 8324        }
 8325
 8326        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8327            s.move_heads_with(|map, head, _| {
 8328                (
 8329                    movement::end_of_paragraph(map, head, 1),
 8330                    SelectionGoal::None,
 8331                )
 8332            });
 8333        })
 8334    }
 8335
 8336    pub fn move_to_beginning(
 8337        &mut self,
 8338        _: &MoveToBeginning,
 8339        window: &mut Window,
 8340        cx: &mut Context<Self>,
 8341    ) {
 8342        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8343            cx.propagate();
 8344            return;
 8345        }
 8346
 8347        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8348            s.select_ranges(vec![0..0]);
 8349        });
 8350    }
 8351
 8352    pub fn select_to_beginning(
 8353        &mut self,
 8354        _: &SelectToBeginning,
 8355        window: &mut Window,
 8356        cx: &mut Context<Self>,
 8357    ) {
 8358        let mut selection = self.selections.last::<Point>(cx);
 8359        selection.set_head(Point::zero(), SelectionGoal::None);
 8360
 8361        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8362            s.select(vec![selection]);
 8363        });
 8364    }
 8365
 8366    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8367        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8368            cx.propagate();
 8369            return;
 8370        }
 8371
 8372        let cursor = self.buffer.read(cx).read(cx).len();
 8373        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8374            s.select_ranges(vec![cursor..cursor])
 8375        });
 8376    }
 8377
 8378    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8379        self.nav_history = nav_history;
 8380    }
 8381
 8382    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8383        self.nav_history.as_ref()
 8384    }
 8385
 8386    fn push_to_nav_history(
 8387        &mut self,
 8388        cursor_anchor: Anchor,
 8389        new_position: Option<Point>,
 8390        cx: &mut Context<Self>,
 8391    ) {
 8392        if let Some(nav_history) = self.nav_history.as_mut() {
 8393            let buffer = self.buffer.read(cx).read(cx);
 8394            let cursor_position = cursor_anchor.to_point(&buffer);
 8395            let scroll_state = self.scroll_manager.anchor();
 8396            let scroll_top_row = scroll_state.top_row(&buffer);
 8397            drop(buffer);
 8398
 8399            if let Some(new_position) = new_position {
 8400                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8401                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8402                    return;
 8403                }
 8404            }
 8405
 8406            nav_history.push(
 8407                Some(NavigationData {
 8408                    cursor_anchor,
 8409                    cursor_position,
 8410                    scroll_anchor: scroll_state,
 8411                    scroll_top_row,
 8412                }),
 8413                cx,
 8414            );
 8415        }
 8416    }
 8417
 8418    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8419        let buffer = self.buffer.read(cx).snapshot(cx);
 8420        let mut selection = self.selections.first::<usize>(cx);
 8421        selection.set_head(buffer.len(), SelectionGoal::None);
 8422        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8423            s.select(vec![selection]);
 8424        });
 8425    }
 8426
 8427    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8428        let end = self.buffer.read(cx).read(cx).len();
 8429        self.change_selections(None, window, cx, |s| {
 8430            s.select_ranges(vec![0..end]);
 8431        });
 8432    }
 8433
 8434    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8435        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8436        let mut selections = self.selections.all::<Point>(cx);
 8437        let max_point = display_map.buffer_snapshot.max_point();
 8438        for selection in &mut selections {
 8439            let rows = selection.spanned_rows(true, &display_map);
 8440            selection.start = Point::new(rows.start.0, 0);
 8441            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8442            selection.reversed = false;
 8443        }
 8444        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8445            s.select(selections);
 8446        });
 8447    }
 8448
 8449    pub fn split_selection_into_lines(
 8450        &mut self,
 8451        _: &SplitSelectionIntoLines,
 8452        window: &mut Window,
 8453        cx: &mut Context<Self>,
 8454    ) {
 8455        let mut to_unfold = Vec::new();
 8456        let mut new_selection_ranges = Vec::new();
 8457        {
 8458            let selections = self.selections.all::<Point>(cx);
 8459            let buffer = self.buffer.read(cx).read(cx);
 8460            for selection in selections {
 8461                for row in selection.start.row..selection.end.row {
 8462                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8463                    new_selection_ranges.push(cursor..cursor);
 8464                }
 8465                new_selection_ranges.push(selection.end..selection.end);
 8466                to_unfold.push(selection.start..selection.end);
 8467            }
 8468        }
 8469        self.unfold_ranges(&to_unfold, true, true, cx);
 8470        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8471            s.select_ranges(new_selection_ranges);
 8472        });
 8473    }
 8474
 8475    pub fn add_selection_above(
 8476        &mut self,
 8477        _: &AddSelectionAbove,
 8478        window: &mut Window,
 8479        cx: &mut Context<Self>,
 8480    ) {
 8481        self.add_selection(true, window, cx);
 8482    }
 8483
 8484    pub fn add_selection_below(
 8485        &mut self,
 8486        _: &AddSelectionBelow,
 8487        window: &mut Window,
 8488        cx: &mut Context<Self>,
 8489    ) {
 8490        self.add_selection(false, window, cx);
 8491    }
 8492
 8493    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8494        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8495        let mut selections = self.selections.all::<Point>(cx);
 8496        let text_layout_details = self.text_layout_details(window);
 8497        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8498            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8499            let range = oldest_selection.display_range(&display_map).sorted();
 8500
 8501            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8502            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8503            let positions = start_x.min(end_x)..start_x.max(end_x);
 8504
 8505            selections.clear();
 8506            let mut stack = Vec::new();
 8507            for row in range.start.row().0..=range.end.row().0 {
 8508                if let Some(selection) = self.selections.build_columnar_selection(
 8509                    &display_map,
 8510                    DisplayRow(row),
 8511                    &positions,
 8512                    oldest_selection.reversed,
 8513                    &text_layout_details,
 8514                ) {
 8515                    stack.push(selection.id);
 8516                    selections.push(selection);
 8517                }
 8518            }
 8519
 8520            if above {
 8521                stack.reverse();
 8522            }
 8523
 8524            AddSelectionsState { above, stack }
 8525        });
 8526
 8527        let last_added_selection = *state.stack.last().unwrap();
 8528        let mut new_selections = Vec::new();
 8529        if above == state.above {
 8530            let end_row = if above {
 8531                DisplayRow(0)
 8532            } else {
 8533                display_map.max_point().row()
 8534            };
 8535
 8536            'outer: for selection in selections {
 8537                if selection.id == last_added_selection {
 8538                    let range = selection.display_range(&display_map).sorted();
 8539                    debug_assert_eq!(range.start.row(), range.end.row());
 8540                    let mut row = range.start.row();
 8541                    let positions =
 8542                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8543                            px(start)..px(end)
 8544                        } else {
 8545                            let start_x =
 8546                                display_map.x_for_display_point(range.start, &text_layout_details);
 8547                            let end_x =
 8548                                display_map.x_for_display_point(range.end, &text_layout_details);
 8549                            start_x.min(end_x)..start_x.max(end_x)
 8550                        };
 8551
 8552                    while row != end_row {
 8553                        if above {
 8554                            row.0 -= 1;
 8555                        } else {
 8556                            row.0 += 1;
 8557                        }
 8558
 8559                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8560                            &display_map,
 8561                            row,
 8562                            &positions,
 8563                            selection.reversed,
 8564                            &text_layout_details,
 8565                        ) {
 8566                            state.stack.push(new_selection.id);
 8567                            if above {
 8568                                new_selections.push(new_selection);
 8569                                new_selections.push(selection);
 8570                            } else {
 8571                                new_selections.push(selection);
 8572                                new_selections.push(new_selection);
 8573                            }
 8574
 8575                            continue 'outer;
 8576                        }
 8577                    }
 8578                }
 8579
 8580                new_selections.push(selection);
 8581            }
 8582        } else {
 8583            new_selections = selections;
 8584            new_selections.retain(|s| s.id != last_added_selection);
 8585            state.stack.pop();
 8586        }
 8587
 8588        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8589            s.select(new_selections);
 8590        });
 8591        if state.stack.len() > 1 {
 8592            self.add_selections_state = Some(state);
 8593        }
 8594    }
 8595
 8596    pub fn select_next_match_internal(
 8597        &mut self,
 8598        display_map: &DisplaySnapshot,
 8599        replace_newest: bool,
 8600        autoscroll: Option<Autoscroll>,
 8601        window: &mut Window,
 8602        cx: &mut Context<Self>,
 8603    ) -> Result<()> {
 8604        fn select_next_match_ranges(
 8605            this: &mut Editor,
 8606            range: Range<usize>,
 8607            replace_newest: bool,
 8608            auto_scroll: Option<Autoscroll>,
 8609            window: &mut Window,
 8610            cx: &mut Context<Editor>,
 8611        ) {
 8612            this.unfold_ranges(&[range.clone()], false, true, cx);
 8613            this.change_selections(auto_scroll, window, cx, |s| {
 8614                if replace_newest {
 8615                    s.delete(s.newest_anchor().id);
 8616                }
 8617                s.insert_range(range.clone());
 8618            });
 8619        }
 8620
 8621        let buffer = &display_map.buffer_snapshot;
 8622        let mut selections = self.selections.all::<usize>(cx);
 8623        if let Some(mut select_next_state) = self.select_next_state.take() {
 8624            let query = &select_next_state.query;
 8625            if !select_next_state.done {
 8626                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8627                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8628                let mut next_selected_range = None;
 8629
 8630                let bytes_after_last_selection =
 8631                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8632                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8633                let query_matches = query
 8634                    .stream_find_iter(bytes_after_last_selection)
 8635                    .map(|result| (last_selection.end, result))
 8636                    .chain(
 8637                        query
 8638                            .stream_find_iter(bytes_before_first_selection)
 8639                            .map(|result| (0, result)),
 8640                    );
 8641
 8642                for (start_offset, query_match) in query_matches {
 8643                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8644                    let offset_range =
 8645                        start_offset + query_match.start()..start_offset + query_match.end();
 8646                    let display_range = offset_range.start.to_display_point(display_map)
 8647                        ..offset_range.end.to_display_point(display_map);
 8648
 8649                    if !select_next_state.wordwise
 8650                        || (!movement::is_inside_word(display_map, display_range.start)
 8651                            && !movement::is_inside_word(display_map, display_range.end))
 8652                    {
 8653                        // TODO: This is n^2, because we might check all the selections
 8654                        if !selections
 8655                            .iter()
 8656                            .any(|selection| selection.range().overlaps(&offset_range))
 8657                        {
 8658                            next_selected_range = Some(offset_range);
 8659                            break;
 8660                        }
 8661                    }
 8662                }
 8663
 8664                if let Some(next_selected_range) = next_selected_range {
 8665                    select_next_match_ranges(
 8666                        self,
 8667                        next_selected_range,
 8668                        replace_newest,
 8669                        autoscroll,
 8670                        window,
 8671                        cx,
 8672                    );
 8673                } else {
 8674                    select_next_state.done = true;
 8675                }
 8676            }
 8677
 8678            self.select_next_state = Some(select_next_state);
 8679        } else {
 8680            let mut only_carets = true;
 8681            let mut same_text_selected = true;
 8682            let mut selected_text = None;
 8683
 8684            let mut selections_iter = selections.iter().peekable();
 8685            while let Some(selection) = selections_iter.next() {
 8686                if selection.start != selection.end {
 8687                    only_carets = false;
 8688                }
 8689
 8690                if same_text_selected {
 8691                    if selected_text.is_none() {
 8692                        selected_text =
 8693                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8694                    }
 8695
 8696                    if let Some(next_selection) = selections_iter.peek() {
 8697                        if next_selection.range().len() == selection.range().len() {
 8698                            let next_selected_text = buffer
 8699                                .text_for_range(next_selection.range())
 8700                                .collect::<String>();
 8701                            if Some(next_selected_text) != selected_text {
 8702                                same_text_selected = false;
 8703                                selected_text = None;
 8704                            }
 8705                        } else {
 8706                            same_text_selected = false;
 8707                            selected_text = None;
 8708                        }
 8709                    }
 8710                }
 8711            }
 8712
 8713            if only_carets {
 8714                for selection in &mut selections {
 8715                    let word_range = movement::surrounding_word(
 8716                        display_map,
 8717                        selection.start.to_display_point(display_map),
 8718                    );
 8719                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8720                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8721                    selection.goal = SelectionGoal::None;
 8722                    selection.reversed = false;
 8723                    select_next_match_ranges(
 8724                        self,
 8725                        selection.start..selection.end,
 8726                        replace_newest,
 8727                        autoscroll,
 8728                        window,
 8729                        cx,
 8730                    );
 8731                }
 8732
 8733                if selections.len() == 1 {
 8734                    let selection = selections
 8735                        .last()
 8736                        .expect("ensured that there's only one selection");
 8737                    let query = buffer
 8738                        .text_for_range(selection.start..selection.end)
 8739                        .collect::<String>();
 8740                    let is_empty = query.is_empty();
 8741                    let select_state = SelectNextState {
 8742                        query: AhoCorasick::new(&[query])?,
 8743                        wordwise: true,
 8744                        done: is_empty,
 8745                    };
 8746                    self.select_next_state = Some(select_state);
 8747                } else {
 8748                    self.select_next_state = None;
 8749                }
 8750            } else if let Some(selected_text) = selected_text {
 8751                self.select_next_state = Some(SelectNextState {
 8752                    query: AhoCorasick::new(&[selected_text])?,
 8753                    wordwise: false,
 8754                    done: false,
 8755                });
 8756                self.select_next_match_internal(
 8757                    display_map,
 8758                    replace_newest,
 8759                    autoscroll,
 8760                    window,
 8761                    cx,
 8762                )?;
 8763            }
 8764        }
 8765        Ok(())
 8766    }
 8767
 8768    pub fn select_all_matches(
 8769        &mut self,
 8770        _action: &SelectAllMatches,
 8771        window: &mut Window,
 8772        cx: &mut Context<Self>,
 8773    ) -> Result<()> {
 8774        self.push_to_selection_history();
 8775        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8776
 8777        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 8778        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8779            return Ok(());
 8780        };
 8781        if select_next_state.done {
 8782            return Ok(());
 8783        }
 8784
 8785        let mut new_selections = self.selections.all::<usize>(cx);
 8786
 8787        let buffer = &display_map.buffer_snapshot;
 8788        let query_matches = select_next_state
 8789            .query
 8790            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8791
 8792        for query_match in query_matches {
 8793            let query_match = query_match.unwrap(); // can only fail due to I/O
 8794            let offset_range = query_match.start()..query_match.end();
 8795            let display_range = offset_range.start.to_display_point(&display_map)
 8796                ..offset_range.end.to_display_point(&display_map);
 8797
 8798            if !select_next_state.wordwise
 8799                || (!movement::is_inside_word(&display_map, display_range.start)
 8800                    && !movement::is_inside_word(&display_map, display_range.end))
 8801            {
 8802                self.selections.change_with(cx, |selections| {
 8803                    new_selections.push(Selection {
 8804                        id: selections.new_selection_id(),
 8805                        start: offset_range.start,
 8806                        end: offset_range.end,
 8807                        reversed: false,
 8808                        goal: SelectionGoal::None,
 8809                    });
 8810                });
 8811            }
 8812        }
 8813
 8814        new_selections.sort_by_key(|selection| selection.start);
 8815        let mut ix = 0;
 8816        while ix + 1 < new_selections.len() {
 8817            let current_selection = &new_selections[ix];
 8818            let next_selection = &new_selections[ix + 1];
 8819            if current_selection.range().overlaps(&next_selection.range()) {
 8820                if current_selection.id < next_selection.id {
 8821                    new_selections.remove(ix + 1);
 8822                } else {
 8823                    new_selections.remove(ix);
 8824                }
 8825            } else {
 8826                ix += 1;
 8827            }
 8828        }
 8829
 8830        select_next_state.done = true;
 8831        self.unfold_ranges(
 8832            &new_selections
 8833                .iter()
 8834                .map(|selection| selection.range())
 8835                .collect::<Vec<_>>(),
 8836            false,
 8837            false,
 8838            cx,
 8839        );
 8840        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8841            selections.select(new_selections)
 8842        });
 8843
 8844        Ok(())
 8845    }
 8846
 8847    pub fn select_next(
 8848        &mut self,
 8849        action: &SelectNext,
 8850        window: &mut Window,
 8851        cx: &mut Context<Self>,
 8852    ) -> Result<()> {
 8853        self.push_to_selection_history();
 8854        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8855        self.select_next_match_internal(
 8856            &display_map,
 8857            action.replace_newest,
 8858            Some(Autoscroll::newest()),
 8859            window,
 8860            cx,
 8861        )?;
 8862        Ok(())
 8863    }
 8864
 8865    pub fn select_previous(
 8866        &mut self,
 8867        action: &SelectPrevious,
 8868        window: &mut Window,
 8869        cx: &mut Context<Self>,
 8870    ) -> Result<()> {
 8871        self.push_to_selection_history();
 8872        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8873        let buffer = &display_map.buffer_snapshot;
 8874        let mut selections = self.selections.all::<usize>(cx);
 8875        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8876            let query = &select_prev_state.query;
 8877            if !select_prev_state.done {
 8878                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8879                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8880                let mut next_selected_range = None;
 8881                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8882                let bytes_before_last_selection =
 8883                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8884                let bytes_after_first_selection =
 8885                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8886                let query_matches = query
 8887                    .stream_find_iter(bytes_before_last_selection)
 8888                    .map(|result| (last_selection.start, result))
 8889                    .chain(
 8890                        query
 8891                            .stream_find_iter(bytes_after_first_selection)
 8892                            .map(|result| (buffer.len(), result)),
 8893                    );
 8894                for (end_offset, query_match) in query_matches {
 8895                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8896                    let offset_range =
 8897                        end_offset - query_match.end()..end_offset - query_match.start();
 8898                    let display_range = offset_range.start.to_display_point(&display_map)
 8899                        ..offset_range.end.to_display_point(&display_map);
 8900
 8901                    if !select_prev_state.wordwise
 8902                        || (!movement::is_inside_word(&display_map, display_range.start)
 8903                            && !movement::is_inside_word(&display_map, display_range.end))
 8904                    {
 8905                        next_selected_range = Some(offset_range);
 8906                        break;
 8907                    }
 8908                }
 8909
 8910                if let Some(next_selected_range) = next_selected_range {
 8911                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8912                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8913                        if action.replace_newest {
 8914                            s.delete(s.newest_anchor().id);
 8915                        }
 8916                        s.insert_range(next_selected_range);
 8917                    });
 8918                } else {
 8919                    select_prev_state.done = true;
 8920                }
 8921            }
 8922
 8923            self.select_prev_state = Some(select_prev_state);
 8924        } else {
 8925            let mut only_carets = true;
 8926            let mut same_text_selected = true;
 8927            let mut selected_text = None;
 8928
 8929            let mut selections_iter = selections.iter().peekable();
 8930            while let Some(selection) = selections_iter.next() {
 8931                if selection.start != selection.end {
 8932                    only_carets = false;
 8933                }
 8934
 8935                if same_text_selected {
 8936                    if selected_text.is_none() {
 8937                        selected_text =
 8938                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8939                    }
 8940
 8941                    if let Some(next_selection) = selections_iter.peek() {
 8942                        if next_selection.range().len() == selection.range().len() {
 8943                            let next_selected_text = buffer
 8944                                .text_for_range(next_selection.range())
 8945                                .collect::<String>();
 8946                            if Some(next_selected_text) != selected_text {
 8947                                same_text_selected = false;
 8948                                selected_text = None;
 8949                            }
 8950                        } else {
 8951                            same_text_selected = false;
 8952                            selected_text = None;
 8953                        }
 8954                    }
 8955                }
 8956            }
 8957
 8958            if only_carets {
 8959                for selection in &mut selections {
 8960                    let word_range = movement::surrounding_word(
 8961                        &display_map,
 8962                        selection.start.to_display_point(&display_map),
 8963                    );
 8964                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8965                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8966                    selection.goal = SelectionGoal::None;
 8967                    selection.reversed = false;
 8968                }
 8969                if selections.len() == 1 {
 8970                    let selection = selections
 8971                        .last()
 8972                        .expect("ensured that there's only one selection");
 8973                    let query = buffer
 8974                        .text_for_range(selection.start..selection.end)
 8975                        .collect::<String>();
 8976                    let is_empty = query.is_empty();
 8977                    let select_state = SelectNextState {
 8978                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8979                        wordwise: true,
 8980                        done: is_empty,
 8981                    };
 8982                    self.select_prev_state = Some(select_state);
 8983                } else {
 8984                    self.select_prev_state = None;
 8985                }
 8986
 8987                self.unfold_ranges(
 8988                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8989                    false,
 8990                    true,
 8991                    cx,
 8992                );
 8993                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8994                    s.select(selections);
 8995                });
 8996            } else if let Some(selected_text) = selected_text {
 8997                self.select_prev_state = Some(SelectNextState {
 8998                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8999                    wordwise: false,
 9000                    done: false,
 9001                });
 9002                self.select_previous(action, window, cx)?;
 9003            }
 9004        }
 9005        Ok(())
 9006    }
 9007
 9008    pub fn toggle_comments(
 9009        &mut self,
 9010        action: &ToggleComments,
 9011        window: &mut Window,
 9012        cx: &mut Context<Self>,
 9013    ) {
 9014        if self.read_only(cx) {
 9015            return;
 9016        }
 9017        let text_layout_details = &self.text_layout_details(window);
 9018        self.transact(window, cx, |this, window, cx| {
 9019            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9020            let mut edits = Vec::new();
 9021            let mut selection_edit_ranges = Vec::new();
 9022            let mut last_toggled_row = None;
 9023            let snapshot = this.buffer.read(cx).read(cx);
 9024            let empty_str: Arc<str> = Arc::default();
 9025            let mut suffixes_inserted = Vec::new();
 9026            let ignore_indent = action.ignore_indent;
 9027
 9028            fn comment_prefix_range(
 9029                snapshot: &MultiBufferSnapshot,
 9030                row: MultiBufferRow,
 9031                comment_prefix: &str,
 9032                comment_prefix_whitespace: &str,
 9033                ignore_indent: bool,
 9034            ) -> Range<Point> {
 9035                let indent_size = if ignore_indent {
 9036                    0
 9037                } else {
 9038                    snapshot.indent_size_for_line(row).len
 9039                };
 9040
 9041                let start = Point::new(row.0, indent_size);
 9042
 9043                let mut line_bytes = snapshot
 9044                    .bytes_in_range(start..snapshot.max_point())
 9045                    .flatten()
 9046                    .copied();
 9047
 9048                // If this line currently begins with the line comment prefix, then record
 9049                // the range containing the prefix.
 9050                if line_bytes
 9051                    .by_ref()
 9052                    .take(comment_prefix.len())
 9053                    .eq(comment_prefix.bytes())
 9054                {
 9055                    // Include any whitespace that matches the comment prefix.
 9056                    let matching_whitespace_len = line_bytes
 9057                        .zip(comment_prefix_whitespace.bytes())
 9058                        .take_while(|(a, b)| a == b)
 9059                        .count() as u32;
 9060                    let end = Point::new(
 9061                        start.row,
 9062                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9063                    );
 9064                    start..end
 9065                } else {
 9066                    start..start
 9067                }
 9068            }
 9069
 9070            fn comment_suffix_range(
 9071                snapshot: &MultiBufferSnapshot,
 9072                row: MultiBufferRow,
 9073                comment_suffix: &str,
 9074                comment_suffix_has_leading_space: bool,
 9075            ) -> Range<Point> {
 9076                let end = Point::new(row.0, snapshot.line_len(row));
 9077                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9078
 9079                let mut line_end_bytes = snapshot
 9080                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9081                    .flatten()
 9082                    .copied();
 9083
 9084                let leading_space_len = if suffix_start_column > 0
 9085                    && line_end_bytes.next() == Some(b' ')
 9086                    && comment_suffix_has_leading_space
 9087                {
 9088                    1
 9089                } else {
 9090                    0
 9091                };
 9092
 9093                // If this line currently begins with the line comment prefix, then record
 9094                // the range containing the prefix.
 9095                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9096                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9097                    start..end
 9098                } else {
 9099                    end..end
 9100                }
 9101            }
 9102
 9103            // TODO: Handle selections that cross excerpts
 9104            for selection in &mut selections {
 9105                let start_column = snapshot
 9106                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9107                    .len;
 9108                let language = if let Some(language) =
 9109                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9110                {
 9111                    language
 9112                } else {
 9113                    continue;
 9114                };
 9115
 9116                selection_edit_ranges.clear();
 9117
 9118                // If multiple selections contain a given row, avoid processing that
 9119                // row more than once.
 9120                let mut start_row = MultiBufferRow(selection.start.row);
 9121                if last_toggled_row == Some(start_row) {
 9122                    start_row = start_row.next_row();
 9123                }
 9124                let end_row =
 9125                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9126                        MultiBufferRow(selection.end.row - 1)
 9127                    } else {
 9128                        MultiBufferRow(selection.end.row)
 9129                    };
 9130                last_toggled_row = Some(end_row);
 9131
 9132                if start_row > end_row {
 9133                    continue;
 9134                }
 9135
 9136                // If the language has line comments, toggle those.
 9137                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9138
 9139                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9140                if ignore_indent {
 9141                    full_comment_prefixes = full_comment_prefixes
 9142                        .into_iter()
 9143                        .map(|s| Arc::from(s.trim_end()))
 9144                        .collect();
 9145                }
 9146
 9147                if !full_comment_prefixes.is_empty() {
 9148                    let first_prefix = full_comment_prefixes
 9149                        .first()
 9150                        .expect("prefixes is non-empty");
 9151                    let prefix_trimmed_lengths = full_comment_prefixes
 9152                        .iter()
 9153                        .map(|p| p.trim_end_matches(' ').len())
 9154                        .collect::<SmallVec<[usize; 4]>>();
 9155
 9156                    let mut all_selection_lines_are_comments = true;
 9157
 9158                    for row in start_row.0..=end_row.0 {
 9159                        let row = MultiBufferRow(row);
 9160                        if start_row < end_row && snapshot.is_line_blank(row) {
 9161                            continue;
 9162                        }
 9163
 9164                        let prefix_range = full_comment_prefixes
 9165                            .iter()
 9166                            .zip(prefix_trimmed_lengths.iter().copied())
 9167                            .map(|(prefix, trimmed_prefix_len)| {
 9168                                comment_prefix_range(
 9169                                    snapshot.deref(),
 9170                                    row,
 9171                                    &prefix[..trimmed_prefix_len],
 9172                                    &prefix[trimmed_prefix_len..],
 9173                                    ignore_indent,
 9174                                )
 9175                            })
 9176                            .max_by_key(|range| range.end.column - range.start.column)
 9177                            .expect("prefixes is non-empty");
 9178
 9179                        if prefix_range.is_empty() {
 9180                            all_selection_lines_are_comments = false;
 9181                        }
 9182
 9183                        selection_edit_ranges.push(prefix_range);
 9184                    }
 9185
 9186                    if all_selection_lines_are_comments {
 9187                        edits.extend(
 9188                            selection_edit_ranges
 9189                                .iter()
 9190                                .cloned()
 9191                                .map(|range| (range, empty_str.clone())),
 9192                        );
 9193                    } else {
 9194                        let min_column = selection_edit_ranges
 9195                            .iter()
 9196                            .map(|range| range.start.column)
 9197                            .min()
 9198                            .unwrap_or(0);
 9199                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9200                            let position = Point::new(range.start.row, min_column);
 9201                            (position..position, first_prefix.clone())
 9202                        }));
 9203                    }
 9204                } else if let Some((full_comment_prefix, comment_suffix)) =
 9205                    language.block_comment_delimiters()
 9206                {
 9207                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9208                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9209                    let prefix_range = comment_prefix_range(
 9210                        snapshot.deref(),
 9211                        start_row,
 9212                        comment_prefix,
 9213                        comment_prefix_whitespace,
 9214                        ignore_indent,
 9215                    );
 9216                    let suffix_range = comment_suffix_range(
 9217                        snapshot.deref(),
 9218                        end_row,
 9219                        comment_suffix.trim_start_matches(' '),
 9220                        comment_suffix.starts_with(' '),
 9221                    );
 9222
 9223                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9224                        edits.push((
 9225                            prefix_range.start..prefix_range.start,
 9226                            full_comment_prefix.clone(),
 9227                        ));
 9228                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9229                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9230                    } else {
 9231                        edits.push((prefix_range, empty_str.clone()));
 9232                        edits.push((suffix_range, empty_str.clone()));
 9233                    }
 9234                } else {
 9235                    continue;
 9236                }
 9237            }
 9238
 9239            drop(snapshot);
 9240            this.buffer.update(cx, |buffer, cx| {
 9241                buffer.edit(edits, None, cx);
 9242            });
 9243
 9244            // Adjust selections so that they end before any comment suffixes that
 9245            // were inserted.
 9246            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9247            let mut selections = this.selections.all::<Point>(cx);
 9248            let snapshot = this.buffer.read(cx).read(cx);
 9249            for selection in &mut selections {
 9250                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9251                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9252                        Ordering::Less => {
 9253                            suffixes_inserted.next();
 9254                            continue;
 9255                        }
 9256                        Ordering::Greater => break,
 9257                        Ordering::Equal => {
 9258                            if selection.end.column == snapshot.line_len(row) {
 9259                                if selection.is_empty() {
 9260                                    selection.start.column -= suffix_len as u32;
 9261                                }
 9262                                selection.end.column -= suffix_len as u32;
 9263                            }
 9264                            break;
 9265                        }
 9266                    }
 9267                }
 9268            }
 9269
 9270            drop(snapshot);
 9271            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9272                s.select(selections)
 9273            });
 9274
 9275            let selections = this.selections.all::<Point>(cx);
 9276            let selections_on_single_row = selections.windows(2).all(|selections| {
 9277                selections[0].start.row == selections[1].start.row
 9278                    && selections[0].end.row == selections[1].end.row
 9279                    && selections[0].start.row == selections[0].end.row
 9280            });
 9281            let selections_selecting = selections
 9282                .iter()
 9283                .any(|selection| selection.start != selection.end);
 9284            let advance_downwards = action.advance_downwards
 9285                && selections_on_single_row
 9286                && !selections_selecting
 9287                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9288
 9289            if advance_downwards {
 9290                let snapshot = this.buffer.read(cx).snapshot(cx);
 9291
 9292                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9293                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9294                        let mut point = display_point.to_point(display_snapshot);
 9295                        point.row += 1;
 9296                        point = snapshot.clip_point(point, Bias::Left);
 9297                        let display_point = point.to_display_point(display_snapshot);
 9298                        let goal = SelectionGoal::HorizontalPosition(
 9299                            display_snapshot
 9300                                .x_for_display_point(display_point, text_layout_details)
 9301                                .into(),
 9302                        );
 9303                        (display_point, goal)
 9304                    })
 9305                });
 9306            }
 9307        });
 9308    }
 9309
 9310    pub fn select_enclosing_symbol(
 9311        &mut self,
 9312        _: &SelectEnclosingSymbol,
 9313        window: &mut Window,
 9314        cx: &mut Context<Self>,
 9315    ) {
 9316        let buffer = self.buffer.read(cx).snapshot(cx);
 9317        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9318
 9319        fn update_selection(
 9320            selection: &Selection<usize>,
 9321            buffer_snap: &MultiBufferSnapshot,
 9322        ) -> Option<Selection<usize>> {
 9323            let cursor = selection.head();
 9324            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9325            for symbol in symbols.iter().rev() {
 9326                let start = symbol.range.start.to_offset(buffer_snap);
 9327                let end = symbol.range.end.to_offset(buffer_snap);
 9328                let new_range = start..end;
 9329                if start < selection.start || end > selection.end {
 9330                    return Some(Selection {
 9331                        id: selection.id,
 9332                        start: new_range.start,
 9333                        end: new_range.end,
 9334                        goal: SelectionGoal::None,
 9335                        reversed: selection.reversed,
 9336                    });
 9337                }
 9338            }
 9339            None
 9340        }
 9341
 9342        let mut selected_larger_symbol = false;
 9343        let new_selections = old_selections
 9344            .iter()
 9345            .map(|selection| match update_selection(selection, &buffer) {
 9346                Some(new_selection) => {
 9347                    if new_selection.range() != selection.range() {
 9348                        selected_larger_symbol = true;
 9349                    }
 9350                    new_selection
 9351                }
 9352                None => selection.clone(),
 9353            })
 9354            .collect::<Vec<_>>();
 9355
 9356        if selected_larger_symbol {
 9357            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9358                s.select(new_selections);
 9359            });
 9360        }
 9361    }
 9362
 9363    pub fn select_larger_syntax_node(
 9364        &mut self,
 9365        _: &SelectLargerSyntaxNode,
 9366        window: &mut Window,
 9367        cx: &mut Context<Self>,
 9368    ) {
 9369        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9370        let buffer = self.buffer.read(cx).snapshot(cx);
 9371        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9372
 9373        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9374        let mut selected_larger_node = false;
 9375        let new_selections = old_selections
 9376            .iter()
 9377            .map(|selection| {
 9378                let old_range = selection.start..selection.end;
 9379                let mut new_range = old_range.clone();
 9380                let mut new_node = None;
 9381                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9382                {
 9383                    new_node = Some(node);
 9384                    new_range = containing_range;
 9385                    if !display_map.intersects_fold(new_range.start)
 9386                        && !display_map.intersects_fold(new_range.end)
 9387                    {
 9388                        break;
 9389                    }
 9390                }
 9391
 9392                if let Some(node) = new_node {
 9393                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9394                    // nodes. Parent and grandparent are also logged because this operation will not
 9395                    // visit nodes that have the same range as their parent.
 9396                    log::info!("Node: {node:?}");
 9397                    let parent = node.parent();
 9398                    log::info!("Parent: {parent:?}");
 9399                    let grandparent = parent.and_then(|x| x.parent());
 9400                    log::info!("Grandparent: {grandparent:?}");
 9401                }
 9402
 9403                selected_larger_node |= new_range != old_range;
 9404                Selection {
 9405                    id: selection.id,
 9406                    start: new_range.start,
 9407                    end: new_range.end,
 9408                    goal: SelectionGoal::None,
 9409                    reversed: selection.reversed,
 9410                }
 9411            })
 9412            .collect::<Vec<_>>();
 9413
 9414        if selected_larger_node {
 9415            stack.push(old_selections);
 9416            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9417                s.select(new_selections);
 9418            });
 9419        }
 9420        self.select_larger_syntax_node_stack = stack;
 9421    }
 9422
 9423    pub fn select_smaller_syntax_node(
 9424        &mut self,
 9425        _: &SelectSmallerSyntaxNode,
 9426        window: &mut Window,
 9427        cx: &mut Context<Self>,
 9428    ) {
 9429        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9430        if let Some(selections) = stack.pop() {
 9431            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9432                s.select(selections.to_vec());
 9433            });
 9434        }
 9435        self.select_larger_syntax_node_stack = stack;
 9436    }
 9437
 9438    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9439        if !EditorSettings::get_global(cx).gutter.runnables {
 9440            self.clear_tasks();
 9441            return Task::ready(());
 9442        }
 9443        let project = self.project.as_ref().map(Entity::downgrade);
 9444        cx.spawn_in(window, |this, mut cx| async move {
 9445            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9446            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9447                return;
 9448            };
 9449            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9450                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9451            }) else {
 9452                return;
 9453            };
 9454
 9455            let hide_runnables = project
 9456                .update(&mut cx, |project, cx| {
 9457                    // Do not display any test indicators in non-dev server remote projects.
 9458                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9459                })
 9460                .unwrap_or(true);
 9461            if hide_runnables {
 9462                return;
 9463            }
 9464            let new_rows =
 9465                cx.background_executor()
 9466                    .spawn({
 9467                        let snapshot = display_snapshot.clone();
 9468                        async move {
 9469                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9470                        }
 9471                    })
 9472                    .await;
 9473
 9474            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9475            this.update(&mut cx, |this, _| {
 9476                this.clear_tasks();
 9477                for (key, value) in rows {
 9478                    this.insert_tasks(key, value);
 9479                }
 9480            })
 9481            .ok();
 9482        })
 9483    }
 9484    fn fetch_runnable_ranges(
 9485        snapshot: &DisplaySnapshot,
 9486        range: Range<Anchor>,
 9487    ) -> Vec<language::RunnableRange> {
 9488        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9489    }
 9490
 9491    fn runnable_rows(
 9492        project: Entity<Project>,
 9493        snapshot: DisplaySnapshot,
 9494        runnable_ranges: Vec<RunnableRange>,
 9495        mut cx: AsyncWindowContext,
 9496    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9497        runnable_ranges
 9498            .into_iter()
 9499            .filter_map(|mut runnable| {
 9500                let tasks = cx
 9501                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9502                    .ok()?;
 9503                if tasks.is_empty() {
 9504                    return None;
 9505                }
 9506
 9507                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9508
 9509                let row = snapshot
 9510                    .buffer_snapshot
 9511                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9512                    .1
 9513                    .start
 9514                    .row;
 9515
 9516                let context_range =
 9517                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9518                Some((
 9519                    (runnable.buffer_id, row),
 9520                    RunnableTasks {
 9521                        templates: tasks,
 9522                        offset: MultiBufferOffset(runnable.run_range.start),
 9523                        context_range,
 9524                        column: point.column,
 9525                        extra_variables: runnable.extra_captures,
 9526                    },
 9527                ))
 9528            })
 9529            .collect()
 9530    }
 9531
 9532    fn templates_with_tags(
 9533        project: &Entity<Project>,
 9534        runnable: &mut Runnable,
 9535        cx: &mut App,
 9536    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9537        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9538            let (worktree_id, file) = project
 9539                .buffer_for_id(runnable.buffer, cx)
 9540                .and_then(|buffer| buffer.read(cx).file())
 9541                .map(|file| (file.worktree_id(cx), file.clone()))
 9542                .unzip();
 9543
 9544            (
 9545                project.task_store().read(cx).task_inventory().cloned(),
 9546                worktree_id,
 9547                file,
 9548            )
 9549        });
 9550
 9551        let tags = mem::take(&mut runnable.tags);
 9552        let mut tags: Vec<_> = tags
 9553            .into_iter()
 9554            .flat_map(|tag| {
 9555                let tag = tag.0.clone();
 9556                inventory
 9557                    .as_ref()
 9558                    .into_iter()
 9559                    .flat_map(|inventory| {
 9560                        inventory.read(cx).list_tasks(
 9561                            file.clone(),
 9562                            Some(runnable.language.clone()),
 9563                            worktree_id,
 9564                            cx,
 9565                        )
 9566                    })
 9567                    .filter(move |(_, template)| {
 9568                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9569                    })
 9570            })
 9571            .sorted_by_key(|(kind, _)| kind.to_owned())
 9572            .collect();
 9573        if let Some((leading_tag_source, _)) = tags.first() {
 9574            // Strongest source wins; if we have worktree tag binding, prefer that to
 9575            // global and language bindings;
 9576            // if we have a global binding, prefer that to language binding.
 9577            let first_mismatch = tags
 9578                .iter()
 9579                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9580            if let Some(index) = first_mismatch {
 9581                tags.truncate(index);
 9582            }
 9583        }
 9584
 9585        tags
 9586    }
 9587
 9588    pub fn move_to_enclosing_bracket(
 9589        &mut self,
 9590        _: &MoveToEnclosingBracket,
 9591        window: &mut Window,
 9592        cx: &mut Context<Self>,
 9593    ) {
 9594        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9595            s.move_offsets_with(|snapshot, selection| {
 9596                let Some(enclosing_bracket_ranges) =
 9597                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9598                else {
 9599                    return;
 9600                };
 9601
 9602                let mut best_length = usize::MAX;
 9603                let mut best_inside = false;
 9604                let mut best_in_bracket_range = false;
 9605                let mut best_destination = None;
 9606                for (open, close) in enclosing_bracket_ranges {
 9607                    let close = close.to_inclusive();
 9608                    let length = close.end() - open.start;
 9609                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9610                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9611                        || close.contains(&selection.head());
 9612
 9613                    // If best is next to a bracket and current isn't, skip
 9614                    if !in_bracket_range && best_in_bracket_range {
 9615                        continue;
 9616                    }
 9617
 9618                    // Prefer smaller lengths unless best is inside and current isn't
 9619                    if length > best_length && (best_inside || !inside) {
 9620                        continue;
 9621                    }
 9622
 9623                    best_length = length;
 9624                    best_inside = inside;
 9625                    best_in_bracket_range = in_bracket_range;
 9626                    best_destination = Some(
 9627                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9628                            if inside {
 9629                                open.end
 9630                            } else {
 9631                                open.start
 9632                            }
 9633                        } else if inside {
 9634                            *close.start()
 9635                        } else {
 9636                            *close.end()
 9637                        },
 9638                    );
 9639                }
 9640
 9641                if let Some(destination) = best_destination {
 9642                    selection.collapse_to(destination, SelectionGoal::None);
 9643                }
 9644            })
 9645        });
 9646    }
 9647
 9648    pub fn undo_selection(
 9649        &mut self,
 9650        _: &UndoSelection,
 9651        window: &mut Window,
 9652        cx: &mut Context<Self>,
 9653    ) {
 9654        self.end_selection(window, cx);
 9655        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9656        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9657            self.change_selections(None, window, cx, |s| {
 9658                s.select_anchors(entry.selections.to_vec())
 9659            });
 9660            self.select_next_state = entry.select_next_state;
 9661            self.select_prev_state = entry.select_prev_state;
 9662            self.add_selections_state = entry.add_selections_state;
 9663            self.request_autoscroll(Autoscroll::newest(), cx);
 9664        }
 9665        self.selection_history.mode = SelectionHistoryMode::Normal;
 9666    }
 9667
 9668    pub fn redo_selection(
 9669        &mut self,
 9670        _: &RedoSelection,
 9671        window: &mut Window,
 9672        cx: &mut Context<Self>,
 9673    ) {
 9674        self.end_selection(window, cx);
 9675        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9676        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9677            self.change_selections(None, window, cx, |s| {
 9678                s.select_anchors(entry.selections.to_vec())
 9679            });
 9680            self.select_next_state = entry.select_next_state;
 9681            self.select_prev_state = entry.select_prev_state;
 9682            self.add_selections_state = entry.add_selections_state;
 9683            self.request_autoscroll(Autoscroll::newest(), cx);
 9684        }
 9685        self.selection_history.mode = SelectionHistoryMode::Normal;
 9686    }
 9687
 9688    pub fn expand_excerpts(
 9689        &mut self,
 9690        action: &ExpandExcerpts,
 9691        _: &mut Window,
 9692        cx: &mut Context<Self>,
 9693    ) {
 9694        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9695    }
 9696
 9697    pub fn expand_excerpts_down(
 9698        &mut self,
 9699        action: &ExpandExcerptsDown,
 9700        _: &mut Window,
 9701        cx: &mut Context<Self>,
 9702    ) {
 9703        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9704    }
 9705
 9706    pub fn expand_excerpts_up(
 9707        &mut self,
 9708        action: &ExpandExcerptsUp,
 9709        _: &mut Window,
 9710        cx: &mut Context<Self>,
 9711    ) {
 9712        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9713    }
 9714
 9715    pub fn expand_excerpts_for_direction(
 9716        &mut self,
 9717        lines: u32,
 9718        direction: ExpandExcerptDirection,
 9719
 9720        cx: &mut Context<Self>,
 9721    ) {
 9722        let selections = self.selections.disjoint_anchors();
 9723
 9724        let lines = if lines == 0 {
 9725            EditorSettings::get_global(cx).expand_excerpt_lines
 9726        } else {
 9727            lines
 9728        };
 9729
 9730        self.buffer.update(cx, |buffer, cx| {
 9731            let snapshot = buffer.snapshot(cx);
 9732            let mut excerpt_ids = selections
 9733                .iter()
 9734                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9735                .collect::<Vec<_>>();
 9736            excerpt_ids.sort();
 9737            excerpt_ids.dedup();
 9738            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9739        })
 9740    }
 9741
 9742    pub fn expand_excerpt(
 9743        &mut self,
 9744        excerpt: ExcerptId,
 9745        direction: ExpandExcerptDirection,
 9746        cx: &mut Context<Self>,
 9747    ) {
 9748        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9749        self.buffer.update(cx, |buffer, cx| {
 9750            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9751        })
 9752    }
 9753
 9754    pub fn go_to_singleton_buffer_point(
 9755        &mut self,
 9756        point: Point,
 9757        window: &mut Window,
 9758        cx: &mut Context<Self>,
 9759    ) {
 9760        self.go_to_singleton_buffer_range(point..point, window, cx);
 9761    }
 9762
 9763    pub fn go_to_singleton_buffer_range(
 9764        &mut self,
 9765        range: Range<Point>,
 9766        window: &mut Window,
 9767        cx: &mut Context<Self>,
 9768    ) {
 9769        let multibuffer = self.buffer().read(cx);
 9770        let Some(buffer) = multibuffer.as_singleton() else {
 9771            return;
 9772        };
 9773        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9774            return;
 9775        };
 9776        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9777            return;
 9778        };
 9779        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9780            s.select_anchor_ranges([start..end])
 9781        });
 9782    }
 9783
 9784    fn go_to_diagnostic(
 9785        &mut self,
 9786        _: &GoToDiagnostic,
 9787        window: &mut Window,
 9788        cx: &mut Context<Self>,
 9789    ) {
 9790        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9791    }
 9792
 9793    fn go_to_prev_diagnostic(
 9794        &mut self,
 9795        _: &GoToPrevDiagnostic,
 9796        window: &mut Window,
 9797        cx: &mut Context<Self>,
 9798    ) {
 9799        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9800    }
 9801
 9802    pub fn go_to_diagnostic_impl(
 9803        &mut self,
 9804        direction: Direction,
 9805        window: &mut Window,
 9806        cx: &mut Context<Self>,
 9807    ) {
 9808        let buffer = self.buffer.read(cx).snapshot(cx);
 9809        let selection = self.selections.newest::<usize>(cx);
 9810
 9811        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9812        if direction == Direction::Next {
 9813            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9814                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9815                    return;
 9816                };
 9817                self.activate_diagnostics(
 9818                    buffer_id,
 9819                    popover.local_diagnostic.diagnostic.group_id,
 9820                    window,
 9821                    cx,
 9822                );
 9823                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9824                    let primary_range_start = active_diagnostics.primary_range.start;
 9825                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9826                        let mut new_selection = s.newest_anchor().clone();
 9827                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9828                        s.select_anchors(vec![new_selection.clone()]);
 9829                    });
 9830                    self.refresh_inline_completion(false, true, window, cx);
 9831                }
 9832                return;
 9833            }
 9834        }
 9835
 9836        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9837            active_diagnostics
 9838                .primary_range
 9839                .to_offset(&buffer)
 9840                .to_inclusive()
 9841        });
 9842        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9843            if active_primary_range.contains(&selection.head()) {
 9844                *active_primary_range.start()
 9845            } else {
 9846                selection.head()
 9847            }
 9848        } else {
 9849            selection.head()
 9850        };
 9851        let snapshot = self.snapshot(window, cx);
 9852        loop {
 9853            let mut diagnostics;
 9854            if direction == Direction::Prev {
 9855                diagnostics = buffer
 9856                    .diagnostics_in_range::<_, usize>(0..search_start)
 9857                    .collect::<Vec<_>>();
 9858                diagnostics.reverse();
 9859            } else {
 9860                diagnostics = buffer
 9861                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9862                    .collect::<Vec<_>>();
 9863            };
 9864            let group = diagnostics
 9865                .into_iter()
 9866                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9867                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9868                // be sorted in a stable way
 9869                // skip until we are at current active diagnostic, if it exists
 9870                .skip_while(|entry| {
 9871                    let is_in_range = match direction {
 9872                        Direction::Prev => entry.range.end > search_start,
 9873                        Direction::Next => entry.range.start < search_start,
 9874                    };
 9875                    is_in_range
 9876                        && self
 9877                            .active_diagnostics
 9878                            .as_ref()
 9879                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9880                })
 9881                .find_map(|entry| {
 9882                    if entry.diagnostic.is_primary
 9883                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9884                        && entry.range.start != entry.range.end
 9885                        // if we match with the active diagnostic, skip it
 9886                        && Some(entry.diagnostic.group_id)
 9887                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9888                    {
 9889                        Some((entry.range, entry.diagnostic.group_id))
 9890                    } else {
 9891                        None
 9892                    }
 9893                });
 9894
 9895            if let Some((primary_range, group_id)) = group {
 9896                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9897                    return;
 9898                };
 9899                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9900                if self.active_diagnostics.is_some() {
 9901                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9902                        s.select(vec![Selection {
 9903                            id: selection.id,
 9904                            start: primary_range.start,
 9905                            end: primary_range.start,
 9906                            reversed: false,
 9907                            goal: SelectionGoal::None,
 9908                        }]);
 9909                    });
 9910                    self.refresh_inline_completion(false, true, window, cx);
 9911                }
 9912                break;
 9913            } else {
 9914                // Cycle around to the start of the buffer, potentially moving back to the start of
 9915                // the currently active diagnostic.
 9916                active_primary_range.take();
 9917                if direction == Direction::Prev {
 9918                    if search_start == buffer.len() {
 9919                        break;
 9920                    } else {
 9921                        search_start = buffer.len();
 9922                    }
 9923                } else if search_start == 0 {
 9924                    break;
 9925                } else {
 9926                    search_start = 0;
 9927                }
 9928            }
 9929        }
 9930    }
 9931
 9932    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9933        let snapshot = self.snapshot(window, cx);
 9934        let selection = self.selections.newest::<Point>(cx);
 9935        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9936    }
 9937
 9938    fn go_to_hunk_after_position(
 9939        &mut self,
 9940        snapshot: &EditorSnapshot,
 9941        position: Point,
 9942        window: &mut Window,
 9943        cx: &mut Context<Editor>,
 9944    ) -> Option<MultiBufferDiffHunk> {
 9945        let mut hunk = snapshot
 9946            .buffer_snapshot
 9947            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9948            .find(|hunk| hunk.row_range.start.0 > position.row);
 9949        if hunk.is_none() {
 9950            hunk = snapshot
 9951                .buffer_snapshot
 9952                .diff_hunks_in_range(Point::zero()..position)
 9953                .find(|hunk| hunk.row_range.end.0 < position.row)
 9954        }
 9955        if let Some(hunk) = &hunk {
 9956            let destination = Point::new(hunk.row_range.start.0, 0);
 9957            self.unfold_ranges(&[destination..destination], false, false, cx);
 9958            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9959                s.select_ranges(vec![destination..destination]);
 9960            });
 9961        }
 9962
 9963        hunk
 9964    }
 9965
 9966    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9967        let snapshot = self.snapshot(window, cx);
 9968        let selection = self.selections.newest::<Point>(cx);
 9969        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9970    }
 9971
 9972    fn go_to_hunk_before_position(
 9973        &mut self,
 9974        snapshot: &EditorSnapshot,
 9975        position: Point,
 9976        window: &mut Window,
 9977        cx: &mut Context<Editor>,
 9978    ) -> Option<MultiBufferDiffHunk> {
 9979        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9980        if hunk.is_none() {
 9981            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9982        }
 9983        if let Some(hunk) = &hunk {
 9984            let destination = Point::new(hunk.row_range.start.0, 0);
 9985            self.unfold_ranges(&[destination..destination], false, false, cx);
 9986            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9987                s.select_ranges(vec![destination..destination]);
 9988            });
 9989        }
 9990
 9991        hunk
 9992    }
 9993
 9994    pub fn go_to_definition(
 9995        &mut self,
 9996        _: &GoToDefinition,
 9997        window: &mut Window,
 9998        cx: &mut Context<Self>,
 9999    ) -> Task<Result<Navigated>> {
10000        let definition =
10001            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10002        cx.spawn_in(window, |editor, mut cx| async move {
10003            if definition.await? == Navigated::Yes {
10004                return Ok(Navigated::Yes);
10005            }
10006            match editor.update_in(&mut cx, |editor, window, cx| {
10007                editor.find_all_references(&FindAllReferences, window, cx)
10008            })? {
10009                Some(references) => references.await,
10010                None => Ok(Navigated::No),
10011            }
10012        })
10013    }
10014
10015    pub fn go_to_declaration(
10016        &mut self,
10017        _: &GoToDeclaration,
10018        window: &mut Window,
10019        cx: &mut Context<Self>,
10020    ) -> Task<Result<Navigated>> {
10021        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10022    }
10023
10024    pub fn go_to_declaration_split(
10025        &mut self,
10026        _: &GoToDeclaration,
10027        window: &mut Window,
10028        cx: &mut Context<Self>,
10029    ) -> Task<Result<Navigated>> {
10030        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10031    }
10032
10033    pub fn go_to_implementation(
10034        &mut self,
10035        _: &GoToImplementation,
10036        window: &mut Window,
10037        cx: &mut Context<Self>,
10038    ) -> Task<Result<Navigated>> {
10039        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10040    }
10041
10042    pub fn go_to_implementation_split(
10043        &mut self,
10044        _: &GoToImplementationSplit,
10045        window: &mut Window,
10046        cx: &mut Context<Self>,
10047    ) -> Task<Result<Navigated>> {
10048        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10049    }
10050
10051    pub fn go_to_type_definition(
10052        &mut self,
10053        _: &GoToTypeDefinition,
10054        window: &mut Window,
10055        cx: &mut Context<Self>,
10056    ) -> Task<Result<Navigated>> {
10057        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10058    }
10059
10060    pub fn go_to_definition_split(
10061        &mut self,
10062        _: &GoToDefinitionSplit,
10063        window: &mut Window,
10064        cx: &mut Context<Self>,
10065    ) -> Task<Result<Navigated>> {
10066        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10067    }
10068
10069    pub fn go_to_type_definition_split(
10070        &mut self,
10071        _: &GoToTypeDefinitionSplit,
10072        window: &mut Window,
10073        cx: &mut Context<Self>,
10074    ) -> Task<Result<Navigated>> {
10075        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10076    }
10077
10078    fn go_to_definition_of_kind(
10079        &mut self,
10080        kind: GotoDefinitionKind,
10081        split: bool,
10082        window: &mut Window,
10083        cx: &mut Context<Self>,
10084    ) -> Task<Result<Navigated>> {
10085        let Some(provider) = self.semantics_provider.clone() else {
10086            return Task::ready(Ok(Navigated::No));
10087        };
10088        let head = self.selections.newest::<usize>(cx).head();
10089        let buffer = self.buffer.read(cx);
10090        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10091            text_anchor
10092        } else {
10093            return Task::ready(Ok(Navigated::No));
10094        };
10095
10096        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10097            return Task::ready(Ok(Navigated::No));
10098        };
10099
10100        cx.spawn_in(window, |editor, mut cx| async move {
10101            let definitions = definitions.await?;
10102            let navigated = editor
10103                .update_in(&mut cx, |editor, window, cx| {
10104                    editor.navigate_to_hover_links(
10105                        Some(kind),
10106                        definitions
10107                            .into_iter()
10108                            .filter(|location| {
10109                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10110                            })
10111                            .map(HoverLink::Text)
10112                            .collect::<Vec<_>>(),
10113                        split,
10114                        window,
10115                        cx,
10116                    )
10117                })?
10118                .await?;
10119            anyhow::Ok(navigated)
10120        })
10121    }
10122
10123    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10124        let selection = self.selections.newest_anchor();
10125        let head = selection.head();
10126        let tail = selection.tail();
10127
10128        let Some((buffer, start_position)) =
10129            self.buffer.read(cx).text_anchor_for_position(head, cx)
10130        else {
10131            return;
10132        };
10133
10134        let end_position = if head != tail {
10135            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10136                return;
10137            };
10138            Some(pos)
10139        } else {
10140            None
10141        };
10142
10143        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10144            let url = if let Some(end_pos) = end_position {
10145                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10146            } else {
10147                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10148            };
10149
10150            if let Some(url) = url {
10151                editor.update(&mut cx, |_, cx| {
10152                    cx.open_url(&url);
10153                })
10154            } else {
10155                Ok(())
10156            }
10157        });
10158
10159        url_finder.detach();
10160    }
10161
10162    pub fn open_selected_filename(
10163        &mut self,
10164        _: &OpenSelectedFilename,
10165        window: &mut Window,
10166        cx: &mut Context<Self>,
10167    ) {
10168        let Some(workspace) = self.workspace() else {
10169            return;
10170        };
10171
10172        let position = self.selections.newest_anchor().head();
10173
10174        let Some((buffer, buffer_position)) =
10175            self.buffer.read(cx).text_anchor_for_position(position, cx)
10176        else {
10177            return;
10178        };
10179
10180        let project = self.project.clone();
10181
10182        cx.spawn_in(window, |_, mut cx| async move {
10183            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10184
10185            if let Some((_, path)) = result {
10186                workspace
10187                    .update_in(&mut cx, |workspace, window, cx| {
10188                        workspace.open_resolved_path(path, window, cx)
10189                    })?
10190                    .await?;
10191            }
10192            anyhow::Ok(())
10193        })
10194        .detach();
10195    }
10196
10197    pub(crate) fn navigate_to_hover_links(
10198        &mut self,
10199        kind: Option<GotoDefinitionKind>,
10200        mut definitions: Vec<HoverLink>,
10201        split: bool,
10202        window: &mut Window,
10203        cx: &mut Context<Editor>,
10204    ) -> Task<Result<Navigated>> {
10205        // If there is one definition, just open it directly
10206        if definitions.len() == 1 {
10207            let definition = definitions.pop().unwrap();
10208
10209            enum TargetTaskResult {
10210                Location(Option<Location>),
10211                AlreadyNavigated,
10212            }
10213
10214            let target_task = match definition {
10215                HoverLink::Text(link) => {
10216                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10217                }
10218                HoverLink::InlayHint(lsp_location, server_id) => {
10219                    let computation =
10220                        self.compute_target_location(lsp_location, server_id, window, cx);
10221                    cx.background_executor().spawn(async move {
10222                        let location = computation.await?;
10223                        Ok(TargetTaskResult::Location(location))
10224                    })
10225                }
10226                HoverLink::Url(url) => {
10227                    cx.open_url(&url);
10228                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10229                }
10230                HoverLink::File(path) => {
10231                    if let Some(workspace) = self.workspace() {
10232                        cx.spawn_in(window, |_, mut cx| async move {
10233                            workspace
10234                                .update_in(&mut cx, |workspace, window, cx| {
10235                                    workspace.open_resolved_path(path, window, cx)
10236                                })?
10237                                .await
10238                                .map(|_| TargetTaskResult::AlreadyNavigated)
10239                        })
10240                    } else {
10241                        Task::ready(Ok(TargetTaskResult::Location(None)))
10242                    }
10243                }
10244            };
10245            cx.spawn_in(window, |editor, mut cx| async move {
10246                let target = match target_task.await.context("target resolution task")? {
10247                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10248                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10249                    TargetTaskResult::Location(Some(target)) => target,
10250                };
10251
10252                editor.update_in(&mut cx, |editor, window, cx| {
10253                    let Some(workspace) = editor.workspace() else {
10254                        return Navigated::No;
10255                    };
10256                    let pane = workspace.read(cx).active_pane().clone();
10257
10258                    let range = target.range.to_point(target.buffer.read(cx));
10259                    let range = editor.range_for_match(&range);
10260                    let range = collapse_multiline_range(range);
10261
10262                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10263                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10264                    } else {
10265                        window.defer(cx, move |window, cx| {
10266                            let target_editor: Entity<Self> =
10267                                workspace.update(cx, |workspace, cx| {
10268                                    let pane = if split {
10269                                        workspace.adjacent_pane(window, cx)
10270                                    } else {
10271                                        workspace.active_pane().clone()
10272                                    };
10273
10274                                    workspace.open_project_item(
10275                                        pane,
10276                                        target.buffer.clone(),
10277                                        true,
10278                                        true,
10279                                        window,
10280                                        cx,
10281                                    )
10282                                });
10283                            target_editor.update(cx, |target_editor, cx| {
10284                                // When selecting a definition in a different buffer, disable the nav history
10285                                // to avoid creating a history entry at the previous cursor location.
10286                                pane.update(cx, |pane, _| pane.disable_history());
10287                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10288                                pane.update(cx, |pane, _| pane.enable_history());
10289                            });
10290                        });
10291                    }
10292                    Navigated::Yes
10293                })
10294            })
10295        } else if !definitions.is_empty() {
10296            cx.spawn_in(window, |editor, mut cx| async move {
10297                let (title, location_tasks, workspace) = editor
10298                    .update_in(&mut cx, |editor, window, cx| {
10299                        let tab_kind = match kind {
10300                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10301                            _ => "Definitions",
10302                        };
10303                        let title = definitions
10304                            .iter()
10305                            .find_map(|definition| match definition {
10306                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10307                                    let buffer = origin.buffer.read(cx);
10308                                    format!(
10309                                        "{} for {}",
10310                                        tab_kind,
10311                                        buffer
10312                                            .text_for_range(origin.range.clone())
10313                                            .collect::<String>()
10314                                    )
10315                                }),
10316                                HoverLink::InlayHint(_, _) => None,
10317                                HoverLink::Url(_) => None,
10318                                HoverLink::File(_) => None,
10319                            })
10320                            .unwrap_or(tab_kind.to_string());
10321                        let location_tasks = definitions
10322                            .into_iter()
10323                            .map(|definition| match definition {
10324                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10325                                HoverLink::InlayHint(lsp_location, server_id) => editor
10326                                    .compute_target_location(lsp_location, server_id, window, cx),
10327                                HoverLink::Url(_) => Task::ready(Ok(None)),
10328                                HoverLink::File(_) => Task::ready(Ok(None)),
10329                            })
10330                            .collect::<Vec<_>>();
10331                        (title, location_tasks, editor.workspace().clone())
10332                    })
10333                    .context("location tasks preparation")?;
10334
10335                let locations = future::join_all(location_tasks)
10336                    .await
10337                    .into_iter()
10338                    .filter_map(|location| location.transpose())
10339                    .collect::<Result<_>>()
10340                    .context("location tasks")?;
10341
10342                let Some(workspace) = workspace else {
10343                    return Ok(Navigated::No);
10344                };
10345                let opened = workspace
10346                    .update_in(&mut cx, |workspace, window, cx| {
10347                        Self::open_locations_in_multibuffer(
10348                            workspace,
10349                            locations,
10350                            title,
10351                            split,
10352                            MultibufferSelectionMode::First,
10353                            window,
10354                            cx,
10355                        )
10356                    })
10357                    .ok();
10358
10359                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10360            })
10361        } else {
10362            Task::ready(Ok(Navigated::No))
10363        }
10364    }
10365
10366    fn compute_target_location(
10367        &self,
10368        lsp_location: lsp::Location,
10369        server_id: LanguageServerId,
10370        window: &mut Window,
10371        cx: &mut Context<Self>,
10372    ) -> Task<anyhow::Result<Option<Location>>> {
10373        let Some(project) = self.project.clone() else {
10374            return Task::ready(Ok(None));
10375        };
10376
10377        cx.spawn_in(window, move |editor, mut cx| async move {
10378            let location_task = editor.update(&mut cx, |_, cx| {
10379                project.update(cx, |project, cx| {
10380                    let language_server_name = project
10381                        .language_server_statuses(cx)
10382                        .find(|(id, _)| server_id == *id)
10383                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10384                    language_server_name.map(|language_server_name| {
10385                        project.open_local_buffer_via_lsp(
10386                            lsp_location.uri.clone(),
10387                            server_id,
10388                            language_server_name,
10389                            cx,
10390                        )
10391                    })
10392                })
10393            })?;
10394            let location = match location_task {
10395                Some(task) => Some({
10396                    let target_buffer_handle = task.await.context("open local buffer")?;
10397                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10398                        let target_start = target_buffer
10399                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10400                        let target_end = target_buffer
10401                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10402                        target_buffer.anchor_after(target_start)
10403                            ..target_buffer.anchor_before(target_end)
10404                    })?;
10405                    Location {
10406                        buffer: target_buffer_handle,
10407                        range,
10408                    }
10409                }),
10410                None => None,
10411            };
10412            Ok(location)
10413        })
10414    }
10415
10416    pub fn find_all_references(
10417        &mut self,
10418        _: &FindAllReferences,
10419        window: &mut Window,
10420        cx: &mut Context<Self>,
10421    ) -> Option<Task<Result<Navigated>>> {
10422        let selection = self.selections.newest::<usize>(cx);
10423        let multi_buffer = self.buffer.read(cx);
10424        let head = selection.head();
10425
10426        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10427        let head_anchor = multi_buffer_snapshot.anchor_at(
10428            head,
10429            if head < selection.tail() {
10430                Bias::Right
10431            } else {
10432                Bias::Left
10433            },
10434        );
10435
10436        match self
10437            .find_all_references_task_sources
10438            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10439        {
10440            Ok(_) => {
10441                log::info!(
10442                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10443                );
10444                return None;
10445            }
10446            Err(i) => {
10447                self.find_all_references_task_sources.insert(i, head_anchor);
10448            }
10449        }
10450
10451        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10452        let workspace = self.workspace()?;
10453        let project = workspace.read(cx).project().clone();
10454        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10455        Some(cx.spawn_in(window, |editor, mut cx| async move {
10456            let _cleanup = defer({
10457                let mut cx = cx.clone();
10458                move || {
10459                    let _ = editor.update(&mut cx, |editor, _| {
10460                        if let Ok(i) =
10461                            editor
10462                                .find_all_references_task_sources
10463                                .binary_search_by(|anchor| {
10464                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10465                                })
10466                        {
10467                            editor.find_all_references_task_sources.remove(i);
10468                        }
10469                    });
10470                }
10471            });
10472
10473            let locations = references.await?;
10474            if locations.is_empty() {
10475                return anyhow::Ok(Navigated::No);
10476            }
10477
10478            workspace.update_in(&mut cx, |workspace, window, cx| {
10479                let title = locations
10480                    .first()
10481                    .as_ref()
10482                    .map(|location| {
10483                        let buffer = location.buffer.read(cx);
10484                        format!(
10485                            "References to `{}`",
10486                            buffer
10487                                .text_for_range(location.range.clone())
10488                                .collect::<String>()
10489                        )
10490                    })
10491                    .unwrap();
10492                Self::open_locations_in_multibuffer(
10493                    workspace,
10494                    locations,
10495                    title,
10496                    false,
10497                    MultibufferSelectionMode::First,
10498                    window,
10499                    cx,
10500                );
10501                Navigated::Yes
10502            })
10503        }))
10504    }
10505
10506    /// Opens a multibuffer with the given project locations in it
10507    pub fn open_locations_in_multibuffer(
10508        workspace: &mut Workspace,
10509        mut locations: Vec<Location>,
10510        title: String,
10511        split: bool,
10512        multibuffer_selection_mode: MultibufferSelectionMode,
10513        window: &mut Window,
10514        cx: &mut Context<Workspace>,
10515    ) {
10516        // If there are multiple definitions, open them in a multibuffer
10517        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10518        let mut locations = locations.into_iter().peekable();
10519        let mut ranges = Vec::new();
10520        let capability = workspace.project().read(cx).capability();
10521
10522        let excerpt_buffer = cx.new(|cx| {
10523            let mut multibuffer = MultiBuffer::new(capability);
10524            while let Some(location) = locations.next() {
10525                let buffer = location.buffer.read(cx);
10526                let mut ranges_for_buffer = Vec::new();
10527                let range = location.range.to_offset(buffer);
10528                ranges_for_buffer.push(range.clone());
10529
10530                while let Some(next_location) = locations.peek() {
10531                    if next_location.buffer == location.buffer {
10532                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10533                        locations.next();
10534                    } else {
10535                        break;
10536                    }
10537                }
10538
10539                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10540                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10541                    location.buffer.clone(),
10542                    ranges_for_buffer,
10543                    DEFAULT_MULTIBUFFER_CONTEXT,
10544                    cx,
10545                ))
10546            }
10547
10548            multibuffer.with_title(title)
10549        });
10550
10551        let editor = cx.new(|cx| {
10552            Editor::for_multibuffer(
10553                excerpt_buffer,
10554                Some(workspace.project().clone()),
10555                true,
10556                window,
10557                cx,
10558            )
10559        });
10560        editor.update(cx, |editor, cx| {
10561            match multibuffer_selection_mode {
10562                MultibufferSelectionMode::First => {
10563                    if let Some(first_range) = ranges.first() {
10564                        editor.change_selections(None, window, cx, |selections| {
10565                            selections.clear_disjoint();
10566                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10567                        });
10568                    }
10569                    editor.highlight_background::<Self>(
10570                        &ranges,
10571                        |theme| theme.editor_highlighted_line_background,
10572                        cx,
10573                    );
10574                }
10575                MultibufferSelectionMode::All => {
10576                    editor.change_selections(None, window, cx, |selections| {
10577                        selections.clear_disjoint();
10578                        selections.select_anchor_ranges(ranges);
10579                    });
10580                }
10581            }
10582            editor.register_buffers_with_language_servers(cx);
10583        });
10584
10585        let item = Box::new(editor);
10586        let item_id = item.item_id();
10587
10588        if split {
10589            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10590        } else {
10591            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10592                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10593                    pane.close_current_preview_item(window, cx)
10594                } else {
10595                    None
10596                }
10597            });
10598            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10599        }
10600        workspace.active_pane().update(cx, |pane, cx| {
10601            pane.set_preview_item_id(Some(item_id), cx);
10602        });
10603    }
10604
10605    pub fn rename(
10606        &mut self,
10607        _: &Rename,
10608        window: &mut Window,
10609        cx: &mut Context<Self>,
10610    ) -> Option<Task<Result<()>>> {
10611        use language::ToOffset as _;
10612
10613        let provider = self.semantics_provider.clone()?;
10614        let selection = self.selections.newest_anchor().clone();
10615        let (cursor_buffer, cursor_buffer_position) = self
10616            .buffer
10617            .read(cx)
10618            .text_anchor_for_position(selection.head(), cx)?;
10619        let (tail_buffer, cursor_buffer_position_end) = self
10620            .buffer
10621            .read(cx)
10622            .text_anchor_for_position(selection.tail(), cx)?;
10623        if tail_buffer != cursor_buffer {
10624            return None;
10625        }
10626
10627        let snapshot = cursor_buffer.read(cx).snapshot();
10628        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10629        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10630        let prepare_rename = provider
10631            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10632            .unwrap_or_else(|| Task::ready(Ok(None)));
10633        drop(snapshot);
10634
10635        Some(cx.spawn_in(window, |this, mut cx| async move {
10636            let rename_range = if let Some(range) = prepare_rename.await? {
10637                Some(range)
10638            } else {
10639                this.update(&mut cx, |this, cx| {
10640                    let buffer = this.buffer.read(cx).snapshot(cx);
10641                    let mut buffer_highlights = this
10642                        .document_highlights_for_position(selection.head(), &buffer)
10643                        .filter(|highlight| {
10644                            highlight.start.excerpt_id == selection.head().excerpt_id
10645                                && highlight.end.excerpt_id == selection.head().excerpt_id
10646                        });
10647                    buffer_highlights
10648                        .next()
10649                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10650                })?
10651            };
10652            if let Some(rename_range) = rename_range {
10653                this.update_in(&mut cx, |this, window, cx| {
10654                    let snapshot = cursor_buffer.read(cx).snapshot();
10655                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10656                    let cursor_offset_in_rename_range =
10657                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10658                    let cursor_offset_in_rename_range_end =
10659                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10660
10661                    this.take_rename(false, window, cx);
10662                    let buffer = this.buffer.read(cx).read(cx);
10663                    let cursor_offset = selection.head().to_offset(&buffer);
10664                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10665                    let rename_end = rename_start + rename_buffer_range.len();
10666                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10667                    let mut old_highlight_id = None;
10668                    let old_name: Arc<str> = buffer
10669                        .chunks(rename_start..rename_end, true)
10670                        .map(|chunk| {
10671                            if old_highlight_id.is_none() {
10672                                old_highlight_id = chunk.syntax_highlight_id;
10673                            }
10674                            chunk.text
10675                        })
10676                        .collect::<String>()
10677                        .into();
10678
10679                    drop(buffer);
10680
10681                    // Position the selection in the rename editor so that it matches the current selection.
10682                    this.show_local_selections = false;
10683                    let rename_editor = cx.new(|cx| {
10684                        let mut editor = Editor::single_line(window, cx);
10685                        editor.buffer.update(cx, |buffer, cx| {
10686                            buffer.edit([(0..0, old_name.clone())], None, cx)
10687                        });
10688                        let rename_selection_range = match cursor_offset_in_rename_range
10689                            .cmp(&cursor_offset_in_rename_range_end)
10690                        {
10691                            Ordering::Equal => {
10692                                editor.select_all(&SelectAll, window, cx);
10693                                return editor;
10694                            }
10695                            Ordering::Less => {
10696                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10697                            }
10698                            Ordering::Greater => {
10699                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10700                            }
10701                        };
10702                        if rename_selection_range.end > old_name.len() {
10703                            editor.select_all(&SelectAll, window, cx);
10704                        } else {
10705                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10706                                s.select_ranges([rename_selection_range]);
10707                            });
10708                        }
10709                        editor
10710                    });
10711                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10712                        if e == &EditorEvent::Focused {
10713                            cx.emit(EditorEvent::FocusedIn)
10714                        }
10715                    })
10716                    .detach();
10717
10718                    let write_highlights =
10719                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10720                    let read_highlights =
10721                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10722                    let ranges = write_highlights
10723                        .iter()
10724                        .flat_map(|(_, ranges)| ranges.iter())
10725                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10726                        .cloned()
10727                        .collect();
10728
10729                    this.highlight_text::<Rename>(
10730                        ranges,
10731                        HighlightStyle {
10732                            fade_out: Some(0.6),
10733                            ..Default::default()
10734                        },
10735                        cx,
10736                    );
10737                    let rename_focus_handle = rename_editor.focus_handle(cx);
10738                    window.focus(&rename_focus_handle);
10739                    let block_id = this.insert_blocks(
10740                        [BlockProperties {
10741                            style: BlockStyle::Flex,
10742                            placement: BlockPlacement::Below(range.start),
10743                            height: 1,
10744                            render: Arc::new({
10745                                let rename_editor = rename_editor.clone();
10746                                move |cx: &mut BlockContext| {
10747                                    let mut text_style = cx.editor_style.text.clone();
10748                                    if let Some(highlight_style) = old_highlight_id
10749                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10750                                    {
10751                                        text_style = text_style.highlight(highlight_style);
10752                                    }
10753                                    div()
10754                                        .block_mouse_down()
10755                                        .pl(cx.anchor_x)
10756                                        .child(EditorElement::new(
10757                                            &rename_editor,
10758                                            EditorStyle {
10759                                                background: cx.theme().system().transparent,
10760                                                local_player: cx.editor_style.local_player,
10761                                                text: text_style,
10762                                                scrollbar_width: cx.editor_style.scrollbar_width,
10763                                                syntax: cx.editor_style.syntax.clone(),
10764                                                status: cx.editor_style.status.clone(),
10765                                                inlay_hints_style: HighlightStyle {
10766                                                    font_weight: Some(FontWeight::BOLD),
10767                                                    ..make_inlay_hints_style(cx.app)
10768                                                },
10769                                                inline_completion_styles: make_suggestion_styles(
10770                                                    cx.app,
10771                                                ),
10772                                                ..EditorStyle::default()
10773                                            },
10774                                        ))
10775                                        .into_any_element()
10776                                }
10777                            }),
10778                            priority: 0,
10779                        }],
10780                        Some(Autoscroll::fit()),
10781                        cx,
10782                    )[0];
10783                    this.pending_rename = Some(RenameState {
10784                        range,
10785                        old_name,
10786                        editor: rename_editor,
10787                        block_id,
10788                    });
10789                })?;
10790            }
10791
10792            Ok(())
10793        }))
10794    }
10795
10796    pub fn confirm_rename(
10797        &mut self,
10798        _: &ConfirmRename,
10799        window: &mut Window,
10800        cx: &mut Context<Self>,
10801    ) -> Option<Task<Result<()>>> {
10802        let rename = self.take_rename(false, window, cx)?;
10803        let workspace = self.workspace()?.downgrade();
10804        let (buffer, start) = self
10805            .buffer
10806            .read(cx)
10807            .text_anchor_for_position(rename.range.start, cx)?;
10808        let (end_buffer, _) = self
10809            .buffer
10810            .read(cx)
10811            .text_anchor_for_position(rename.range.end, cx)?;
10812        if buffer != end_buffer {
10813            return None;
10814        }
10815
10816        let old_name = rename.old_name;
10817        let new_name = rename.editor.read(cx).text(cx);
10818
10819        let rename = self.semantics_provider.as_ref()?.perform_rename(
10820            &buffer,
10821            start,
10822            new_name.clone(),
10823            cx,
10824        )?;
10825
10826        Some(cx.spawn_in(window, |editor, mut cx| async move {
10827            let project_transaction = rename.await?;
10828            Self::open_project_transaction(
10829                &editor,
10830                workspace,
10831                project_transaction,
10832                format!("Rename: {}{}", old_name, new_name),
10833                cx.clone(),
10834            )
10835            .await?;
10836
10837            editor.update(&mut cx, |editor, cx| {
10838                editor.refresh_document_highlights(cx);
10839            })?;
10840            Ok(())
10841        }))
10842    }
10843
10844    fn take_rename(
10845        &mut self,
10846        moving_cursor: bool,
10847        window: &mut Window,
10848        cx: &mut Context<Self>,
10849    ) -> Option<RenameState> {
10850        let rename = self.pending_rename.take()?;
10851        if rename.editor.focus_handle(cx).is_focused(window) {
10852            window.focus(&self.focus_handle);
10853        }
10854
10855        self.remove_blocks(
10856            [rename.block_id].into_iter().collect(),
10857            Some(Autoscroll::fit()),
10858            cx,
10859        );
10860        self.clear_highlights::<Rename>(cx);
10861        self.show_local_selections = true;
10862
10863        if moving_cursor {
10864            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10865                editor.selections.newest::<usize>(cx).head()
10866            });
10867
10868            // Update the selection to match the position of the selection inside
10869            // the rename editor.
10870            let snapshot = self.buffer.read(cx).read(cx);
10871            let rename_range = rename.range.to_offset(&snapshot);
10872            let cursor_in_editor = snapshot
10873                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10874                .min(rename_range.end);
10875            drop(snapshot);
10876
10877            self.change_selections(None, window, cx, |s| {
10878                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10879            });
10880        } else {
10881            self.refresh_document_highlights(cx);
10882        }
10883
10884        Some(rename)
10885    }
10886
10887    pub fn pending_rename(&self) -> Option<&RenameState> {
10888        self.pending_rename.as_ref()
10889    }
10890
10891    fn format(
10892        &mut self,
10893        _: &Format,
10894        window: &mut Window,
10895        cx: &mut Context<Self>,
10896    ) -> Option<Task<Result<()>>> {
10897        let project = match &self.project {
10898            Some(project) => project.clone(),
10899            None => return None,
10900        };
10901
10902        Some(self.perform_format(
10903            project,
10904            FormatTrigger::Manual,
10905            FormatTarget::Buffers,
10906            window,
10907            cx,
10908        ))
10909    }
10910
10911    fn format_selections(
10912        &mut self,
10913        _: &FormatSelections,
10914        window: &mut Window,
10915        cx: &mut Context<Self>,
10916    ) -> Option<Task<Result<()>>> {
10917        let project = match &self.project {
10918            Some(project) => project.clone(),
10919            None => return None,
10920        };
10921
10922        let ranges = self
10923            .selections
10924            .all_adjusted(cx)
10925            .into_iter()
10926            .map(|selection| selection.range())
10927            .collect_vec();
10928
10929        Some(self.perform_format(
10930            project,
10931            FormatTrigger::Manual,
10932            FormatTarget::Ranges(ranges),
10933            window,
10934            cx,
10935        ))
10936    }
10937
10938    fn perform_format(
10939        &mut self,
10940        project: Entity<Project>,
10941        trigger: FormatTrigger,
10942        target: FormatTarget,
10943        window: &mut Window,
10944        cx: &mut Context<Self>,
10945    ) -> Task<Result<()>> {
10946        let buffer = self.buffer.clone();
10947        let (buffers, target) = match target {
10948            FormatTarget::Buffers => {
10949                let mut buffers = buffer.read(cx).all_buffers();
10950                if trigger == FormatTrigger::Save {
10951                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10952                }
10953                (buffers, LspFormatTarget::Buffers)
10954            }
10955            FormatTarget::Ranges(selection_ranges) => {
10956                let multi_buffer = buffer.read(cx);
10957                let snapshot = multi_buffer.read(cx);
10958                let mut buffers = HashSet::default();
10959                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10960                    BTreeMap::new();
10961                for selection_range in selection_ranges {
10962                    for (buffer, buffer_range, _) in
10963                        snapshot.range_to_buffer_ranges(selection_range)
10964                    {
10965                        let buffer_id = buffer.remote_id();
10966                        let start = buffer.anchor_before(buffer_range.start);
10967                        let end = buffer.anchor_after(buffer_range.end);
10968                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10969                        buffer_id_to_ranges
10970                            .entry(buffer_id)
10971                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10972                            .or_insert_with(|| vec![start..end]);
10973                    }
10974                }
10975                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10976            }
10977        };
10978
10979        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10980        let format = project.update(cx, |project, cx| {
10981            project.format(buffers, target, true, trigger, cx)
10982        });
10983
10984        cx.spawn_in(window, |_, mut cx| async move {
10985            let transaction = futures::select_biased! {
10986                () = timeout => {
10987                    log::warn!("timed out waiting for formatting");
10988                    None
10989                }
10990                transaction = format.log_err().fuse() => transaction,
10991            };
10992
10993            buffer
10994                .update(&mut cx, |buffer, cx| {
10995                    if let Some(transaction) = transaction {
10996                        if !buffer.is_singleton() {
10997                            buffer.push_transaction(&transaction.0, cx);
10998                        }
10999                    }
11000
11001                    cx.notify();
11002                })
11003                .ok();
11004
11005            Ok(())
11006        })
11007    }
11008
11009    fn restart_language_server(
11010        &mut self,
11011        _: &RestartLanguageServer,
11012        _: &mut Window,
11013        cx: &mut Context<Self>,
11014    ) {
11015        if let Some(project) = self.project.clone() {
11016            self.buffer.update(cx, |multi_buffer, cx| {
11017                project.update(cx, |project, cx| {
11018                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11019                });
11020            })
11021        }
11022    }
11023
11024    fn cancel_language_server_work(
11025        &mut self,
11026        _: &actions::CancelLanguageServerWork,
11027        _: &mut Window,
11028        cx: &mut Context<Self>,
11029    ) {
11030        if let Some(project) = self.project.clone() {
11031            self.buffer.update(cx, |multi_buffer, cx| {
11032                project.update(cx, |project, cx| {
11033                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11034                });
11035            })
11036        }
11037    }
11038
11039    fn show_character_palette(
11040        &mut self,
11041        _: &ShowCharacterPalette,
11042        window: &mut Window,
11043        _: &mut Context<Self>,
11044    ) {
11045        window.show_character_palette();
11046    }
11047
11048    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11049        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11050            let buffer = self.buffer.read(cx).snapshot(cx);
11051            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11052            let is_valid = buffer
11053                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11054                .any(|entry| {
11055                    entry.diagnostic.is_primary
11056                        && !entry.range.is_empty()
11057                        && entry.range.start == primary_range_start
11058                        && entry.diagnostic.message == active_diagnostics.primary_message
11059                });
11060
11061            if is_valid != active_diagnostics.is_valid {
11062                active_diagnostics.is_valid = is_valid;
11063                let mut new_styles = HashMap::default();
11064                for (block_id, diagnostic) in &active_diagnostics.blocks {
11065                    new_styles.insert(
11066                        *block_id,
11067                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11068                    );
11069                }
11070                self.display_map.update(cx, |display_map, _cx| {
11071                    display_map.replace_blocks(new_styles)
11072                });
11073            }
11074        }
11075    }
11076
11077    fn activate_diagnostics(
11078        &mut self,
11079        buffer_id: BufferId,
11080        group_id: usize,
11081        window: &mut Window,
11082        cx: &mut Context<Self>,
11083    ) {
11084        self.dismiss_diagnostics(cx);
11085        let snapshot = self.snapshot(window, cx);
11086        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11087            let buffer = self.buffer.read(cx).snapshot(cx);
11088
11089            let mut primary_range = None;
11090            let mut primary_message = None;
11091            let diagnostic_group = buffer
11092                .diagnostic_group(buffer_id, group_id)
11093                .filter_map(|entry| {
11094                    let start = entry.range.start;
11095                    let end = entry.range.end;
11096                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11097                        && (start.row == end.row
11098                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11099                    {
11100                        return None;
11101                    }
11102                    if entry.diagnostic.is_primary {
11103                        primary_range = Some(entry.range.clone());
11104                        primary_message = Some(entry.diagnostic.message.clone());
11105                    }
11106                    Some(entry)
11107                })
11108                .collect::<Vec<_>>();
11109            let primary_range = primary_range?;
11110            let primary_message = primary_message?;
11111
11112            let blocks = display_map
11113                .insert_blocks(
11114                    diagnostic_group.iter().map(|entry| {
11115                        let diagnostic = entry.diagnostic.clone();
11116                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11117                        BlockProperties {
11118                            style: BlockStyle::Fixed,
11119                            placement: BlockPlacement::Below(
11120                                buffer.anchor_after(entry.range.start),
11121                            ),
11122                            height: message_height,
11123                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11124                            priority: 0,
11125                        }
11126                    }),
11127                    cx,
11128                )
11129                .into_iter()
11130                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11131                .collect();
11132
11133            Some(ActiveDiagnosticGroup {
11134                primary_range: buffer.anchor_before(primary_range.start)
11135                    ..buffer.anchor_after(primary_range.end),
11136                primary_message,
11137                group_id,
11138                blocks,
11139                is_valid: true,
11140            })
11141        });
11142    }
11143
11144    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11145        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11146            self.display_map.update(cx, |display_map, cx| {
11147                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11148            });
11149            cx.notify();
11150        }
11151    }
11152
11153    pub fn set_selections_from_remote(
11154        &mut self,
11155        selections: Vec<Selection<Anchor>>,
11156        pending_selection: Option<Selection<Anchor>>,
11157        window: &mut Window,
11158        cx: &mut Context<Self>,
11159    ) {
11160        let old_cursor_position = self.selections.newest_anchor().head();
11161        self.selections.change_with(cx, |s| {
11162            s.select_anchors(selections);
11163            if let Some(pending_selection) = pending_selection {
11164                s.set_pending(pending_selection, SelectMode::Character);
11165            } else {
11166                s.clear_pending();
11167            }
11168        });
11169        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11170    }
11171
11172    fn push_to_selection_history(&mut self) {
11173        self.selection_history.push(SelectionHistoryEntry {
11174            selections: self.selections.disjoint_anchors(),
11175            select_next_state: self.select_next_state.clone(),
11176            select_prev_state: self.select_prev_state.clone(),
11177            add_selections_state: self.add_selections_state.clone(),
11178        });
11179    }
11180
11181    pub fn transact(
11182        &mut self,
11183        window: &mut Window,
11184        cx: &mut Context<Self>,
11185        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11186    ) -> Option<TransactionId> {
11187        self.start_transaction_at(Instant::now(), window, cx);
11188        update(self, window, cx);
11189        self.end_transaction_at(Instant::now(), cx)
11190    }
11191
11192    pub fn start_transaction_at(
11193        &mut self,
11194        now: Instant,
11195        window: &mut Window,
11196        cx: &mut Context<Self>,
11197    ) {
11198        self.end_selection(window, cx);
11199        if let Some(tx_id) = self
11200            .buffer
11201            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11202        {
11203            self.selection_history
11204                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11205            cx.emit(EditorEvent::TransactionBegun {
11206                transaction_id: tx_id,
11207            })
11208        }
11209    }
11210
11211    pub fn end_transaction_at(
11212        &mut self,
11213        now: Instant,
11214        cx: &mut Context<Self>,
11215    ) -> Option<TransactionId> {
11216        if let Some(transaction_id) = self
11217            .buffer
11218            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11219        {
11220            if let Some((_, end_selections)) =
11221                self.selection_history.transaction_mut(transaction_id)
11222            {
11223                *end_selections = Some(self.selections.disjoint_anchors());
11224            } else {
11225                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11226            }
11227
11228            cx.emit(EditorEvent::Edited { transaction_id });
11229            Some(transaction_id)
11230        } else {
11231            None
11232        }
11233    }
11234
11235    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11236        if self.selection_mark_mode {
11237            self.change_selections(None, window, cx, |s| {
11238                s.move_with(|_, sel| {
11239                    sel.collapse_to(sel.head(), SelectionGoal::None);
11240                });
11241            })
11242        }
11243        self.selection_mark_mode = true;
11244        cx.notify();
11245    }
11246
11247    pub fn swap_selection_ends(
11248        &mut self,
11249        _: &actions::SwapSelectionEnds,
11250        window: &mut Window,
11251        cx: &mut Context<Self>,
11252    ) {
11253        self.change_selections(None, window, cx, |s| {
11254            s.move_with(|_, sel| {
11255                if sel.start != sel.end {
11256                    sel.reversed = !sel.reversed
11257                }
11258            });
11259        });
11260        self.request_autoscroll(Autoscroll::newest(), cx);
11261        cx.notify();
11262    }
11263
11264    pub fn toggle_fold(
11265        &mut self,
11266        _: &actions::ToggleFold,
11267        window: &mut Window,
11268        cx: &mut Context<Self>,
11269    ) {
11270        if self.is_singleton(cx) {
11271            let selection = self.selections.newest::<Point>(cx);
11272
11273            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11274            let range = if selection.is_empty() {
11275                let point = selection.head().to_display_point(&display_map);
11276                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11277                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11278                    .to_point(&display_map);
11279                start..end
11280            } else {
11281                selection.range()
11282            };
11283            if display_map.folds_in_range(range).next().is_some() {
11284                self.unfold_lines(&Default::default(), window, cx)
11285            } else {
11286                self.fold(&Default::default(), window, cx)
11287            }
11288        } else {
11289            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11290            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11291                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11292                .map(|(snapshot, _, _)| snapshot.remote_id())
11293                .collect();
11294
11295            for buffer_id in buffer_ids {
11296                if self.is_buffer_folded(buffer_id, cx) {
11297                    self.unfold_buffer(buffer_id, cx);
11298                } else {
11299                    self.fold_buffer(buffer_id, cx);
11300                }
11301            }
11302        }
11303    }
11304
11305    pub fn toggle_fold_recursive(
11306        &mut self,
11307        _: &actions::ToggleFoldRecursive,
11308        window: &mut Window,
11309        cx: &mut Context<Self>,
11310    ) {
11311        let selection = self.selections.newest::<Point>(cx);
11312
11313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11314        let range = if selection.is_empty() {
11315            let point = selection.head().to_display_point(&display_map);
11316            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11317            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11318                .to_point(&display_map);
11319            start..end
11320        } else {
11321            selection.range()
11322        };
11323        if display_map.folds_in_range(range).next().is_some() {
11324            self.unfold_recursive(&Default::default(), window, cx)
11325        } else {
11326            self.fold_recursive(&Default::default(), window, cx)
11327        }
11328    }
11329
11330    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11331        if self.is_singleton(cx) {
11332            let mut to_fold = Vec::new();
11333            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11334            let selections = self.selections.all_adjusted(cx);
11335
11336            for selection in selections {
11337                let range = selection.range().sorted();
11338                let buffer_start_row = range.start.row;
11339
11340                if range.start.row != range.end.row {
11341                    let mut found = false;
11342                    let mut row = range.start.row;
11343                    while row <= range.end.row {
11344                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11345                        {
11346                            found = true;
11347                            row = crease.range().end.row + 1;
11348                            to_fold.push(crease);
11349                        } else {
11350                            row += 1
11351                        }
11352                    }
11353                    if found {
11354                        continue;
11355                    }
11356                }
11357
11358                for row in (0..=range.start.row).rev() {
11359                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11360                        if crease.range().end.row >= buffer_start_row {
11361                            to_fold.push(crease);
11362                            if row <= range.start.row {
11363                                break;
11364                            }
11365                        }
11366                    }
11367                }
11368            }
11369
11370            self.fold_creases(to_fold, true, window, cx);
11371        } else {
11372            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11373
11374            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11375                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11376                .map(|(snapshot, _, _)| snapshot.remote_id())
11377                .collect();
11378            for buffer_id in buffer_ids {
11379                self.fold_buffer(buffer_id, cx);
11380            }
11381        }
11382    }
11383
11384    fn fold_at_level(
11385        &mut self,
11386        fold_at: &FoldAtLevel,
11387        window: &mut Window,
11388        cx: &mut Context<Self>,
11389    ) {
11390        if !self.buffer.read(cx).is_singleton() {
11391            return;
11392        }
11393
11394        let fold_at_level = fold_at.level;
11395        let snapshot = self.buffer.read(cx).snapshot(cx);
11396        let mut to_fold = Vec::new();
11397        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11398
11399        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11400            while start_row < end_row {
11401                match self
11402                    .snapshot(window, cx)
11403                    .crease_for_buffer_row(MultiBufferRow(start_row))
11404                {
11405                    Some(crease) => {
11406                        let nested_start_row = crease.range().start.row + 1;
11407                        let nested_end_row = crease.range().end.row;
11408
11409                        if current_level < fold_at_level {
11410                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11411                        } else if current_level == fold_at_level {
11412                            to_fold.push(crease);
11413                        }
11414
11415                        start_row = nested_end_row + 1;
11416                    }
11417                    None => start_row += 1,
11418                }
11419            }
11420        }
11421
11422        self.fold_creases(to_fold, true, window, cx);
11423    }
11424
11425    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11426        if self.buffer.read(cx).is_singleton() {
11427            let mut fold_ranges = Vec::new();
11428            let snapshot = self.buffer.read(cx).snapshot(cx);
11429
11430            for row in 0..snapshot.max_row().0 {
11431                if let Some(foldable_range) = self
11432                    .snapshot(window, cx)
11433                    .crease_for_buffer_row(MultiBufferRow(row))
11434                {
11435                    fold_ranges.push(foldable_range);
11436                }
11437            }
11438
11439            self.fold_creases(fold_ranges, true, window, cx);
11440        } else {
11441            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11442                editor
11443                    .update_in(&mut cx, |editor, _, cx| {
11444                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11445                            editor.fold_buffer(buffer_id, cx);
11446                        }
11447                    })
11448                    .ok();
11449            });
11450        }
11451    }
11452
11453    pub fn fold_function_bodies(
11454        &mut self,
11455        _: &actions::FoldFunctionBodies,
11456        window: &mut Window,
11457        cx: &mut Context<Self>,
11458    ) {
11459        let snapshot = self.buffer.read(cx).snapshot(cx);
11460
11461        let ranges = snapshot
11462            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11463            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11464            .collect::<Vec<_>>();
11465
11466        let creases = ranges
11467            .into_iter()
11468            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11469            .collect();
11470
11471        self.fold_creases(creases, true, window, cx);
11472    }
11473
11474    pub fn fold_recursive(
11475        &mut self,
11476        _: &actions::FoldRecursive,
11477        window: &mut Window,
11478        cx: &mut Context<Self>,
11479    ) {
11480        let mut to_fold = Vec::new();
11481        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11482        let selections = self.selections.all_adjusted(cx);
11483
11484        for selection in selections {
11485            let range = selection.range().sorted();
11486            let buffer_start_row = range.start.row;
11487
11488            if range.start.row != range.end.row {
11489                let mut found = false;
11490                for row in range.start.row..=range.end.row {
11491                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11492                        found = true;
11493                        to_fold.push(crease);
11494                    }
11495                }
11496                if found {
11497                    continue;
11498                }
11499            }
11500
11501            for row in (0..=range.start.row).rev() {
11502                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11503                    if crease.range().end.row >= buffer_start_row {
11504                        to_fold.push(crease);
11505                    } else {
11506                        break;
11507                    }
11508                }
11509            }
11510        }
11511
11512        self.fold_creases(to_fold, true, window, cx);
11513    }
11514
11515    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11516        let buffer_row = fold_at.buffer_row;
11517        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11518
11519        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11520            let autoscroll = self
11521                .selections
11522                .all::<Point>(cx)
11523                .iter()
11524                .any(|selection| crease.range().overlaps(&selection.range()));
11525
11526            self.fold_creases(vec![crease], autoscroll, window, cx);
11527        }
11528    }
11529
11530    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11531        if self.is_singleton(cx) {
11532            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11533            let buffer = &display_map.buffer_snapshot;
11534            let selections = self.selections.all::<Point>(cx);
11535            let ranges = selections
11536                .iter()
11537                .map(|s| {
11538                    let range = s.display_range(&display_map).sorted();
11539                    let mut start = range.start.to_point(&display_map);
11540                    let mut end = range.end.to_point(&display_map);
11541                    start.column = 0;
11542                    end.column = buffer.line_len(MultiBufferRow(end.row));
11543                    start..end
11544                })
11545                .collect::<Vec<_>>();
11546
11547            self.unfold_ranges(&ranges, true, true, cx);
11548        } else {
11549            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11550            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11551                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11552                .map(|(snapshot, _, _)| snapshot.remote_id())
11553                .collect();
11554            for buffer_id in buffer_ids {
11555                self.unfold_buffer(buffer_id, cx);
11556            }
11557        }
11558    }
11559
11560    pub fn unfold_recursive(
11561        &mut self,
11562        _: &UnfoldRecursive,
11563        _window: &mut Window,
11564        cx: &mut Context<Self>,
11565    ) {
11566        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11567        let selections = self.selections.all::<Point>(cx);
11568        let ranges = selections
11569            .iter()
11570            .map(|s| {
11571                let mut range = s.display_range(&display_map).sorted();
11572                *range.start.column_mut() = 0;
11573                *range.end.column_mut() = display_map.line_len(range.end.row());
11574                let start = range.start.to_point(&display_map);
11575                let end = range.end.to_point(&display_map);
11576                start..end
11577            })
11578            .collect::<Vec<_>>();
11579
11580        self.unfold_ranges(&ranges, true, true, cx);
11581    }
11582
11583    pub fn unfold_at(
11584        &mut self,
11585        unfold_at: &UnfoldAt,
11586        _window: &mut Window,
11587        cx: &mut Context<Self>,
11588    ) {
11589        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11590
11591        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11592            ..Point::new(
11593                unfold_at.buffer_row.0,
11594                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11595            );
11596
11597        let autoscroll = self
11598            .selections
11599            .all::<Point>(cx)
11600            .iter()
11601            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11602
11603        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11604    }
11605
11606    pub fn unfold_all(
11607        &mut self,
11608        _: &actions::UnfoldAll,
11609        _window: &mut Window,
11610        cx: &mut Context<Self>,
11611    ) {
11612        if self.buffer.read(cx).is_singleton() {
11613            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11614            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11615        } else {
11616            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11617                editor
11618                    .update(&mut cx, |editor, cx| {
11619                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11620                            editor.unfold_buffer(buffer_id, cx);
11621                        }
11622                    })
11623                    .ok();
11624            });
11625        }
11626    }
11627
11628    pub fn fold_selected_ranges(
11629        &mut self,
11630        _: &FoldSelectedRanges,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        let selections = self.selections.all::<Point>(cx);
11635        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11636        let line_mode = self.selections.line_mode;
11637        let ranges = selections
11638            .into_iter()
11639            .map(|s| {
11640                if line_mode {
11641                    let start = Point::new(s.start.row, 0);
11642                    let end = Point::new(
11643                        s.end.row,
11644                        display_map
11645                            .buffer_snapshot
11646                            .line_len(MultiBufferRow(s.end.row)),
11647                    );
11648                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11649                } else {
11650                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11651                }
11652            })
11653            .collect::<Vec<_>>();
11654        self.fold_creases(ranges, true, window, cx);
11655    }
11656
11657    pub fn fold_ranges<T: ToOffset + Clone>(
11658        &mut self,
11659        ranges: Vec<Range<T>>,
11660        auto_scroll: bool,
11661        window: &mut Window,
11662        cx: &mut Context<Self>,
11663    ) {
11664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11665        let ranges = ranges
11666            .into_iter()
11667            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11668            .collect::<Vec<_>>();
11669        self.fold_creases(ranges, auto_scroll, window, cx);
11670    }
11671
11672    pub fn fold_creases<T: ToOffset + Clone>(
11673        &mut self,
11674        creases: Vec<Crease<T>>,
11675        auto_scroll: bool,
11676        window: &mut Window,
11677        cx: &mut Context<Self>,
11678    ) {
11679        if creases.is_empty() {
11680            return;
11681        }
11682
11683        let mut buffers_affected = HashSet::default();
11684        let multi_buffer = self.buffer().read(cx);
11685        for crease in &creases {
11686            if let Some((_, buffer, _)) =
11687                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11688            {
11689                buffers_affected.insert(buffer.read(cx).remote_id());
11690            };
11691        }
11692
11693        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11694
11695        if auto_scroll {
11696            self.request_autoscroll(Autoscroll::fit(), cx);
11697        }
11698
11699        cx.notify();
11700
11701        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11702            // Clear diagnostics block when folding a range that contains it.
11703            let snapshot = self.snapshot(window, cx);
11704            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11705                drop(snapshot);
11706                self.active_diagnostics = Some(active_diagnostics);
11707                self.dismiss_diagnostics(cx);
11708            } else {
11709                self.active_diagnostics = Some(active_diagnostics);
11710            }
11711        }
11712
11713        self.scrollbar_marker_state.dirty = true;
11714    }
11715
11716    /// Removes any folds whose ranges intersect any of the given ranges.
11717    pub fn unfold_ranges<T: ToOffset + Clone>(
11718        &mut self,
11719        ranges: &[Range<T>],
11720        inclusive: bool,
11721        auto_scroll: bool,
11722        cx: &mut Context<Self>,
11723    ) {
11724        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11725            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11726        });
11727    }
11728
11729    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11730        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11731            return;
11732        }
11733        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11734            return;
11735        };
11736        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11737        self.display_map
11738            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11739        cx.emit(EditorEvent::BufferFoldToggled {
11740            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11741            folded: true,
11742        });
11743        cx.notify();
11744    }
11745
11746    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11747        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11748            return;
11749        }
11750        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11751            return;
11752        };
11753        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11754        self.display_map.update(cx, |display_map, cx| {
11755            display_map.unfold_buffer(buffer_id, cx);
11756        });
11757        cx.emit(EditorEvent::BufferFoldToggled {
11758            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11759            folded: false,
11760        });
11761        cx.notify();
11762    }
11763
11764    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11765        self.display_map.read(cx).is_buffer_folded(buffer)
11766    }
11767
11768    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11769        self.display_map.read(cx).folded_buffers()
11770    }
11771
11772    /// Removes any folds with the given ranges.
11773    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11774        &mut self,
11775        ranges: &[Range<T>],
11776        type_id: TypeId,
11777        auto_scroll: bool,
11778        cx: &mut Context<Self>,
11779    ) {
11780        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11781            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11782        });
11783    }
11784
11785    fn remove_folds_with<T: ToOffset + Clone>(
11786        &mut self,
11787        ranges: &[Range<T>],
11788        auto_scroll: bool,
11789        cx: &mut Context<Self>,
11790        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11791    ) {
11792        if ranges.is_empty() {
11793            return;
11794        }
11795
11796        let mut buffers_affected = HashSet::default();
11797        let multi_buffer = self.buffer().read(cx);
11798        for range in ranges {
11799            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11800                buffers_affected.insert(buffer.read(cx).remote_id());
11801            };
11802        }
11803
11804        self.display_map.update(cx, update);
11805
11806        if auto_scroll {
11807            self.request_autoscroll(Autoscroll::fit(), cx);
11808        }
11809
11810        cx.notify();
11811        self.scrollbar_marker_state.dirty = true;
11812        self.active_indent_guides_state.dirty = true;
11813    }
11814
11815    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11816        self.display_map.read(cx).fold_placeholder.clone()
11817    }
11818
11819    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11820        self.buffer.update(cx, |buffer, cx| {
11821            buffer.set_all_diff_hunks_expanded(cx);
11822        });
11823    }
11824
11825    pub fn expand_all_diff_hunks(
11826        &mut self,
11827        _: &ExpandAllHunkDiffs,
11828        _window: &mut Window,
11829        cx: &mut Context<Self>,
11830    ) {
11831        self.buffer.update(cx, |buffer, cx| {
11832            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11833        });
11834    }
11835
11836    pub fn toggle_selected_diff_hunks(
11837        &mut self,
11838        _: &ToggleSelectedDiffHunks,
11839        _window: &mut Window,
11840        cx: &mut Context<Self>,
11841    ) {
11842        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11843        self.toggle_diff_hunks_in_ranges(ranges, cx);
11844    }
11845
11846    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11847        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11848        self.buffer
11849            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11850    }
11851
11852    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11853        self.buffer.update(cx, |buffer, cx| {
11854            let ranges = vec![Anchor::min()..Anchor::max()];
11855            if !buffer.all_diff_hunks_expanded()
11856                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11857            {
11858                buffer.collapse_diff_hunks(ranges, cx);
11859                true
11860            } else {
11861                false
11862            }
11863        })
11864    }
11865
11866    fn toggle_diff_hunks_in_ranges(
11867        &mut self,
11868        ranges: Vec<Range<Anchor>>,
11869        cx: &mut Context<'_, Editor>,
11870    ) {
11871        self.buffer.update(cx, |buffer, cx| {
11872            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11873                buffer.collapse_diff_hunks(ranges, cx)
11874            } else {
11875                buffer.expand_diff_hunks(ranges, cx)
11876            }
11877        })
11878    }
11879
11880    pub(crate) fn apply_all_diff_hunks(
11881        &mut self,
11882        _: &ApplyAllDiffHunks,
11883        window: &mut Window,
11884        cx: &mut Context<Self>,
11885    ) {
11886        let buffers = self.buffer.read(cx).all_buffers();
11887        for branch_buffer in buffers {
11888            branch_buffer.update(cx, |branch_buffer, cx| {
11889                branch_buffer.merge_into_base(Vec::new(), cx);
11890            });
11891        }
11892
11893        if let Some(project) = self.project.clone() {
11894            self.save(true, project, window, cx).detach_and_log_err(cx);
11895        }
11896    }
11897
11898    pub(crate) fn apply_selected_diff_hunks(
11899        &mut self,
11900        _: &ApplyDiffHunk,
11901        window: &mut Window,
11902        cx: &mut Context<Self>,
11903    ) {
11904        let snapshot = self.snapshot(window, cx);
11905        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11906        let mut ranges_by_buffer = HashMap::default();
11907        self.transact(window, cx, |editor, _window, cx| {
11908            for hunk in hunks {
11909                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11910                    ranges_by_buffer
11911                        .entry(buffer.clone())
11912                        .or_insert_with(Vec::new)
11913                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11914                }
11915            }
11916
11917            for (buffer, ranges) in ranges_by_buffer {
11918                buffer.update(cx, |buffer, cx| {
11919                    buffer.merge_into_base(ranges, cx);
11920                });
11921            }
11922        });
11923
11924        if let Some(project) = self.project.clone() {
11925            self.save(true, project, window, cx).detach_and_log_err(cx);
11926        }
11927    }
11928
11929    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11930        if hovered != self.gutter_hovered {
11931            self.gutter_hovered = hovered;
11932            cx.notify();
11933        }
11934    }
11935
11936    pub fn insert_blocks(
11937        &mut self,
11938        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11939        autoscroll: Option<Autoscroll>,
11940        cx: &mut Context<Self>,
11941    ) -> Vec<CustomBlockId> {
11942        let blocks = self
11943            .display_map
11944            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11945        if let Some(autoscroll) = autoscroll {
11946            self.request_autoscroll(autoscroll, cx);
11947        }
11948        cx.notify();
11949        blocks
11950    }
11951
11952    pub fn resize_blocks(
11953        &mut self,
11954        heights: HashMap<CustomBlockId, u32>,
11955        autoscroll: Option<Autoscroll>,
11956        cx: &mut Context<Self>,
11957    ) {
11958        self.display_map
11959            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11960        if let Some(autoscroll) = autoscroll {
11961            self.request_autoscroll(autoscroll, cx);
11962        }
11963        cx.notify();
11964    }
11965
11966    pub fn replace_blocks(
11967        &mut self,
11968        renderers: HashMap<CustomBlockId, RenderBlock>,
11969        autoscroll: Option<Autoscroll>,
11970        cx: &mut Context<Self>,
11971    ) {
11972        self.display_map
11973            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11974        if let Some(autoscroll) = autoscroll {
11975            self.request_autoscroll(autoscroll, cx);
11976        }
11977        cx.notify();
11978    }
11979
11980    pub fn remove_blocks(
11981        &mut self,
11982        block_ids: HashSet<CustomBlockId>,
11983        autoscroll: Option<Autoscroll>,
11984        cx: &mut Context<Self>,
11985    ) {
11986        self.display_map.update(cx, |display_map, cx| {
11987            display_map.remove_blocks(block_ids, cx)
11988        });
11989        if let Some(autoscroll) = autoscroll {
11990            self.request_autoscroll(autoscroll, cx);
11991        }
11992        cx.notify();
11993    }
11994
11995    pub fn row_for_block(
11996        &self,
11997        block_id: CustomBlockId,
11998        cx: &mut Context<Self>,
11999    ) -> Option<DisplayRow> {
12000        self.display_map
12001            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12002    }
12003
12004    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12005        self.focused_block = Some(focused_block);
12006    }
12007
12008    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12009        self.focused_block.take()
12010    }
12011
12012    pub fn insert_creases(
12013        &mut self,
12014        creases: impl IntoIterator<Item = Crease<Anchor>>,
12015        cx: &mut Context<Self>,
12016    ) -> Vec<CreaseId> {
12017        self.display_map
12018            .update(cx, |map, cx| map.insert_creases(creases, cx))
12019    }
12020
12021    pub fn remove_creases(
12022        &mut self,
12023        ids: impl IntoIterator<Item = CreaseId>,
12024        cx: &mut Context<Self>,
12025    ) {
12026        self.display_map
12027            .update(cx, |map, cx| map.remove_creases(ids, cx));
12028    }
12029
12030    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12031        self.display_map
12032            .update(cx, |map, cx| map.snapshot(cx))
12033            .longest_row()
12034    }
12035
12036    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12037        self.display_map
12038            .update(cx, |map, cx| map.snapshot(cx))
12039            .max_point()
12040    }
12041
12042    pub fn text(&self, cx: &App) -> String {
12043        self.buffer.read(cx).read(cx).text()
12044    }
12045
12046    pub fn text_option(&self, cx: &App) -> Option<String> {
12047        let text = self.text(cx);
12048        let text = text.trim();
12049
12050        if text.is_empty() {
12051            return None;
12052        }
12053
12054        Some(text.to_string())
12055    }
12056
12057    pub fn set_text(
12058        &mut self,
12059        text: impl Into<Arc<str>>,
12060        window: &mut Window,
12061        cx: &mut Context<Self>,
12062    ) {
12063        self.transact(window, cx, |this, _, cx| {
12064            this.buffer
12065                .read(cx)
12066                .as_singleton()
12067                .expect("you can only call set_text on editors for singleton buffers")
12068                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12069        });
12070    }
12071
12072    pub fn display_text(&self, cx: &mut App) -> String {
12073        self.display_map
12074            .update(cx, |map, cx| map.snapshot(cx))
12075            .text()
12076    }
12077
12078    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12079        let mut wrap_guides = smallvec::smallvec![];
12080
12081        if self.show_wrap_guides == Some(false) {
12082            return wrap_guides;
12083        }
12084
12085        let settings = self.buffer.read(cx).settings_at(0, cx);
12086        if settings.show_wrap_guides {
12087            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12088                wrap_guides.push((soft_wrap as usize, true));
12089            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12090                wrap_guides.push((soft_wrap as usize, true));
12091            }
12092            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12093        }
12094
12095        wrap_guides
12096    }
12097
12098    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12099        let settings = self.buffer.read(cx).settings_at(0, cx);
12100        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12101        match mode {
12102            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12103                SoftWrap::None
12104            }
12105            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12106            language_settings::SoftWrap::PreferredLineLength => {
12107                SoftWrap::Column(settings.preferred_line_length)
12108            }
12109            language_settings::SoftWrap::Bounded => {
12110                SoftWrap::Bounded(settings.preferred_line_length)
12111            }
12112        }
12113    }
12114
12115    pub fn set_soft_wrap_mode(
12116        &mut self,
12117        mode: language_settings::SoftWrap,
12118
12119        cx: &mut Context<Self>,
12120    ) {
12121        self.soft_wrap_mode_override = Some(mode);
12122        cx.notify();
12123    }
12124
12125    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12126        self.text_style_refinement = Some(style);
12127    }
12128
12129    /// called by the Element so we know what style we were most recently rendered with.
12130    pub(crate) fn set_style(
12131        &mut self,
12132        style: EditorStyle,
12133        window: &mut Window,
12134        cx: &mut Context<Self>,
12135    ) {
12136        let rem_size = window.rem_size();
12137        self.display_map.update(cx, |map, cx| {
12138            map.set_font(
12139                style.text.font(),
12140                style.text.font_size.to_pixels(rem_size),
12141                cx,
12142            )
12143        });
12144        self.style = Some(style);
12145    }
12146
12147    pub fn style(&self) -> Option<&EditorStyle> {
12148        self.style.as_ref()
12149    }
12150
12151    // Called by the element. This method is not designed to be called outside of the editor
12152    // element's layout code because it does not notify when rewrapping is computed synchronously.
12153    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12154        self.display_map
12155            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12156    }
12157
12158    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12159        if self.soft_wrap_mode_override.is_some() {
12160            self.soft_wrap_mode_override.take();
12161        } else {
12162            let soft_wrap = match self.soft_wrap_mode(cx) {
12163                SoftWrap::GitDiff => return,
12164                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12165                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12166                    language_settings::SoftWrap::None
12167                }
12168            };
12169            self.soft_wrap_mode_override = Some(soft_wrap);
12170        }
12171        cx.notify();
12172    }
12173
12174    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12175        let Some(workspace) = self.workspace() else {
12176            return;
12177        };
12178        let fs = workspace.read(cx).app_state().fs.clone();
12179        let current_show = TabBarSettings::get_global(cx).show;
12180        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12181            setting.show = Some(!current_show);
12182        });
12183    }
12184
12185    pub fn toggle_indent_guides(
12186        &mut self,
12187        _: &ToggleIndentGuides,
12188        _: &mut Window,
12189        cx: &mut Context<Self>,
12190    ) {
12191        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12192            self.buffer
12193                .read(cx)
12194                .settings_at(0, cx)
12195                .indent_guides
12196                .enabled
12197        });
12198        self.show_indent_guides = Some(!currently_enabled);
12199        cx.notify();
12200    }
12201
12202    fn should_show_indent_guides(&self) -> Option<bool> {
12203        self.show_indent_guides
12204    }
12205
12206    pub fn toggle_line_numbers(
12207        &mut self,
12208        _: &ToggleLineNumbers,
12209        _: &mut Window,
12210        cx: &mut Context<Self>,
12211    ) {
12212        let mut editor_settings = EditorSettings::get_global(cx).clone();
12213        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12214        EditorSettings::override_global(editor_settings, cx);
12215    }
12216
12217    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12218        self.use_relative_line_numbers
12219            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12220    }
12221
12222    pub fn toggle_relative_line_numbers(
12223        &mut self,
12224        _: &ToggleRelativeLineNumbers,
12225        _: &mut Window,
12226        cx: &mut Context<Self>,
12227    ) {
12228        let is_relative = self.should_use_relative_line_numbers(cx);
12229        self.set_relative_line_number(Some(!is_relative), cx)
12230    }
12231
12232    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12233        self.use_relative_line_numbers = is_relative;
12234        cx.notify();
12235    }
12236
12237    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12238        self.show_gutter = show_gutter;
12239        cx.notify();
12240    }
12241
12242    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12243        self.show_scrollbars = show_scrollbars;
12244        cx.notify();
12245    }
12246
12247    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12248        self.show_line_numbers = Some(show_line_numbers);
12249        cx.notify();
12250    }
12251
12252    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12253        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12254        cx.notify();
12255    }
12256
12257    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12258        self.show_code_actions = Some(show_code_actions);
12259        cx.notify();
12260    }
12261
12262    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12263        self.show_runnables = Some(show_runnables);
12264        cx.notify();
12265    }
12266
12267    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12268        if self.display_map.read(cx).masked != masked {
12269            self.display_map.update(cx, |map, _| map.masked = masked);
12270        }
12271        cx.notify()
12272    }
12273
12274    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12275        self.show_wrap_guides = Some(show_wrap_guides);
12276        cx.notify();
12277    }
12278
12279    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12280        self.show_indent_guides = Some(show_indent_guides);
12281        cx.notify();
12282    }
12283
12284    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12285        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12286            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12287                if let Some(dir) = file.abs_path(cx).parent() {
12288                    return Some(dir.to_owned());
12289                }
12290            }
12291
12292            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12293                return Some(project_path.path.to_path_buf());
12294            }
12295        }
12296
12297        None
12298    }
12299
12300    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12301        self.active_excerpt(cx)?
12302            .1
12303            .read(cx)
12304            .file()
12305            .and_then(|f| f.as_local())
12306    }
12307
12308    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12309        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12310            let project_path = buffer.read(cx).project_path(cx)?;
12311            let project = self.project.as_ref()?.read(cx);
12312            project.absolute_path(&project_path, cx)
12313        })
12314    }
12315
12316    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12317        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12318            let project_path = buffer.read(cx).project_path(cx)?;
12319            let project = self.project.as_ref()?.read(cx);
12320            let entry = project.entry_for_path(&project_path, cx)?;
12321            let path = entry.path.to_path_buf();
12322            Some(path)
12323        })
12324    }
12325
12326    pub fn reveal_in_finder(
12327        &mut self,
12328        _: &RevealInFileManager,
12329        _window: &mut Window,
12330        cx: &mut Context<Self>,
12331    ) {
12332        if let Some(target) = self.target_file(cx) {
12333            cx.reveal_path(&target.abs_path(cx));
12334        }
12335    }
12336
12337    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12338        if let Some(path) = self.target_file_abs_path(cx) {
12339            if let Some(path) = path.to_str() {
12340                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12341            }
12342        }
12343    }
12344
12345    pub fn copy_relative_path(
12346        &mut self,
12347        _: &CopyRelativePath,
12348        _window: &mut Window,
12349        cx: &mut Context<Self>,
12350    ) {
12351        if let Some(path) = self.target_file_path(cx) {
12352            if let Some(path) = path.to_str() {
12353                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12354            }
12355        }
12356    }
12357
12358    pub fn toggle_git_blame(
12359        &mut self,
12360        _: &ToggleGitBlame,
12361        window: &mut Window,
12362        cx: &mut Context<Self>,
12363    ) {
12364        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12365
12366        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12367            self.start_git_blame(true, window, cx);
12368        }
12369
12370        cx.notify();
12371    }
12372
12373    pub fn toggle_git_blame_inline(
12374        &mut self,
12375        _: &ToggleGitBlameInline,
12376        window: &mut Window,
12377        cx: &mut Context<Self>,
12378    ) {
12379        self.toggle_git_blame_inline_internal(true, window, cx);
12380        cx.notify();
12381    }
12382
12383    pub fn git_blame_inline_enabled(&self) -> bool {
12384        self.git_blame_inline_enabled
12385    }
12386
12387    pub fn toggle_selection_menu(
12388        &mut self,
12389        _: &ToggleSelectionMenu,
12390        _: &mut Window,
12391        cx: &mut Context<Self>,
12392    ) {
12393        self.show_selection_menu = self
12394            .show_selection_menu
12395            .map(|show_selections_menu| !show_selections_menu)
12396            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12397
12398        cx.notify();
12399    }
12400
12401    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12402        self.show_selection_menu
12403            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12404    }
12405
12406    fn start_git_blame(
12407        &mut self,
12408        user_triggered: bool,
12409        window: &mut Window,
12410        cx: &mut Context<Self>,
12411    ) {
12412        if let Some(project) = self.project.as_ref() {
12413            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12414                return;
12415            };
12416
12417            if buffer.read(cx).file().is_none() {
12418                return;
12419            }
12420
12421            let focused = self.focus_handle(cx).contains_focused(window, cx);
12422
12423            let project = project.clone();
12424            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12425            self.blame_subscription =
12426                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12427            self.blame = Some(blame);
12428        }
12429    }
12430
12431    fn toggle_git_blame_inline_internal(
12432        &mut self,
12433        user_triggered: bool,
12434        window: &mut Window,
12435        cx: &mut Context<Self>,
12436    ) {
12437        if self.git_blame_inline_enabled {
12438            self.git_blame_inline_enabled = false;
12439            self.show_git_blame_inline = false;
12440            self.show_git_blame_inline_delay_task.take();
12441        } else {
12442            self.git_blame_inline_enabled = true;
12443            self.start_git_blame_inline(user_triggered, window, cx);
12444        }
12445
12446        cx.notify();
12447    }
12448
12449    fn start_git_blame_inline(
12450        &mut self,
12451        user_triggered: bool,
12452        window: &mut Window,
12453        cx: &mut Context<Self>,
12454    ) {
12455        self.start_git_blame(user_triggered, window, cx);
12456
12457        if ProjectSettings::get_global(cx)
12458            .git
12459            .inline_blame_delay()
12460            .is_some()
12461        {
12462            self.start_inline_blame_timer(window, cx);
12463        } else {
12464            self.show_git_blame_inline = true
12465        }
12466    }
12467
12468    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12469        self.blame.as_ref()
12470    }
12471
12472    pub fn show_git_blame_gutter(&self) -> bool {
12473        self.show_git_blame_gutter
12474    }
12475
12476    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12477        self.show_git_blame_gutter && self.has_blame_entries(cx)
12478    }
12479
12480    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12481        self.show_git_blame_inline
12482            && self.focus_handle.is_focused(window)
12483            && !self.newest_selection_head_on_empty_line(cx)
12484            && self.has_blame_entries(cx)
12485    }
12486
12487    fn has_blame_entries(&self, cx: &App) -> bool {
12488        self.blame()
12489            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12490    }
12491
12492    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12493        let cursor_anchor = self.selections.newest_anchor().head();
12494
12495        let snapshot = self.buffer.read(cx).snapshot(cx);
12496        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12497
12498        snapshot.line_len(buffer_row) == 0
12499    }
12500
12501    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12502        let buffer_and_selection = maybe!({
12503            let selection = self.selections.newest::<Point>(cx);
12504            let selection_range = selection.range();
12505
12506            let multi_buffer = self.buffer().read(cx);
12507            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12508            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12509
12510            let (buffer, range, _) = if selection.reversed {
12511                buffer_ranges.first()
12512            } else {
12513                buffer_ranges.last()
12514            }?;
12515
12516            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12517                ..text::ToPoint::to_point(&range.end, &buffer).row;
12518            Some((
12519                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12520                selection,
12521            ))
12522        });
12523
12524        let Some((buffer, selection)) = buffer_and_selection else {
12525            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12526        };
12527
12528        let Some(project) = self.project.as_ref() else {
12529            return Task::ready(Err(anyhow!("editor does not have project")));
12530        };
12531
12532        project.update(cx, |project, cx| {
12533            project.get_permalink_to_line(&buffer, selection, cx)
12534        })
12535    }
12536
12537    pub fn copy_permalink_to_line(
12538        &mut self,
12539        _: &CopyPermalinkToLine,
12540        window: &mut Window,
12541        cx: &mut Context<Self>,
12542    ) {
12543        let permalink_task = self.get_permalink_to_line(cx);
12544        let workspace = self.workspace();
12545
12546        cx.spawn_in(window, |_, mut cx| async move {
12547            match permalink_task.await {
12548                Ok(permalink) => {
12549                    cx.update(|_, cx| {
12550                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12551                    })
12552                    .ok();
12553                }
12554                Err(err) => {
12555                    let message = format!("Failed to copy permalink: {err}");
12556
12557                    Err::<(), anyhow::Error>(err).log_err();
12558
12559                    if let Some(workspace) = workspace {
12560                        workspace
12561                            .update_in(&mut cx, |workspace, _, cx| {
12562                                struct CopyPermalinkToLine;
12563
12564                                workspace.show_toast(
12565                                    Toast::new(
12566                                        NotificationId::unique::<CopyPermalinkToLine>(),
12567                                        message,
12568                                    ),
12569                                    cx,
12570                                )
12571                            })
12572                            .ok();
12573                    }
12574                }
12575            }
12576        })
12577        .detach();
12578    }
12579
12580    pub fn copy_file_location(
12581        &mut self,
12582        _: &CopyFileLocation,
12583        _: &mut Window,
12584        cx: &mut Context<Self>,
12585    ) {
12586        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12587        if let Some(file) = self.target_file(cx) {
12588            if let Some(path) = file.path().to_str() {
12589                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12590            }
12591        }
12592    }
12593
12594    pub fn open_permalink_to_line(
12595        &mut self,
12596        _: &OpenPermalinkToLine,
12597        window: &mut Window,
12598        cx: &mut Context<Self>,
12599    ) {
12600        let permalink_task = self.get_permalink_to_line(cx);
12601        let workspace = self.workspace();
12602
12603        cx.spawn_in(window, |_, mut cx| async move {
12604            match permalink_task.await {
12605                Ok(permalink) => {
12606                    cx.update(|_, cx| {
12607                        cx.open_url(permalink.as_ref());
12608                    })
12609                    .ok();
12610                }
12611                Err(err) => {
12612                    let message = format!("Failed to open permalink: {err}");
12613
12614                    Err::<(), anyhow::Error>(err).log_err();
12615
12616                    if let Some(workspace) = workspace {
12617                        workspace
12618                            .update(&mut cx, |workspace, cx| {
12619                                struct OpenPermalinkToLine;
12620
12621                                workspace.show_toast(
12622                                    Toast::new(
12623                                        NotificationId::unique::<OpenPermalinkToLine>(),
12624                                        message,
12625                                    ),
12626                                    cx,
12627                                )
12628                            })
12629                            .ok();
12630                    }
12631                }
12632            }
12633        })
12634        .detach();
12635    }
12636
12637    pub fn insert_uuid_v4(
12638        &mut self,
12639        _: &InsertUuidV4,
12640        window: &mut Window,
12641        cx: &mut Context<Self>,
12642    ) {
12643        self.insert_uuid(UuidVersion::V4, window, cx);
12644    }
12645
12646    pub fn insert_uuid_v7(
12647        &mut self,
12648        _: &InsertUuidV7,
12649        window: &mut Window,
12650        cx: &mut Context<Self>,
12651    ) {
12652        self.insert_uuid(UuidVersion::V7, window, cx);
12653    }
12654
12655    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12656        self.transact(window, cx, |this, window, cx| {
12657            let edits = this
12658                .selections
12659                .all::<Point>(cx)
12660                .into_iter()
12661                .map(|selection| {
12662                    let uuid = match version {
12663                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12664                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12665                    };
12666
12667                    (selection.range(), uuid.to_string())
12668                });
12669            this.edit(edits, cx);
12670            this.refresh_inline_completion(true, false, window, cx);
12671        });
12672    }
12673
12674    pub fn open_selections_in_multibuffer(
12675        &mut self,
12676        _: &OpenSelectionsInMultibuffer,
12677        window: &mut Window,
12678        cx: &mut Context<Self>,
12679    ) {
12680        let multibuffer = self.buffer.read(cx);
12681
12682        let Some(buffer) = multibuffer.as_singleton() else {
12683            return;
12684        };
12685
12686        let Some(workspace) = self.workspace() else {
12687            return;
12688        };
12689
12690        let locations = self
12691            .selections
12692            .disjoint_anchors()
12693            .iter()
12694            .map(|range| Location {
12695                buffer: buffer.clone(),
12696                range: range.start.text_anchor..range.end.text_anchor,
12697            })
12698            .collect::<Vec<_>>();
12699
12700        let title = multibuffer.title(cx).to_string();
12701
12702        cx.spawn_in(window, |_, mut cx| async move {
12703            workspace.update_in(&mut cx, |workspace, window, cx| {
12704                Self::open_locations_in_multibuffer(
12705                    workspace,
12706                    locations,
12707                    format!("Selections for '{title}'"),
12708                    false,
12709                    MultibufferSelectionMode::All,
12710                    window,
12711                    cx,
12712                );
12713            })
12714        })
12715        .detach();
12716    }
12717
12718    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12719    /// last highlight added will be used.
12720    ///
12721    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12722    pub fn highlight_rows<T: 'static>(
12723        &mut self,
12724        range: Range<Anchor>,
12725        color: Hsla,
12726        should_autoscroll: bool,
12727        cx: &mut Context<Self>,
12728    ) {
12729        let snapshot = self.buffer().read(cx).snapshot(cx);
12730        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12731        let ix = row_highlights.binary_search_by(|highlight| {
12732            Ordering::Equal
12733                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12734                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12735        });
12736
12737        if let Err(mut ix) = ix {
12738            let index = post_inc(&mut self.highlight_order);
12739
12740            // If this range intersects with the preceding highlight, then merge it with
12741            // the preceding highlight. Otherwise insert a new highlight.
12742            let mut merged = false;
12743            if ix > 0 {
12744                let prev_highlight = &mut row_highlights[ix - 1];
12745                if prev_highlight
12746                    .range
12747                    .end
12748                    .cmp(&range.start, &snapshot)
12749                    .is_ge()
12750                {
12751                    ix -= 1;
12752                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12753                        prev_highlight.range.end = range.end;
12754                    }
12755                    merged = true;
12756                    prev_highlight.index = index;
12757                    prev_highlight.color = color;
12758                    prev_highlight.should_autoscroll = should_autoscroll;
12759                }
12760            }
12761
12762            if !merged {
12763                row_highlights.insert(
12764                    ix,
12765                    RowHighlight {
12766                        range: range.clone(),
12767                        index,
12768                        color,
12769                        should_autoscroll,
12770                    },
12771                );
12772            }
12773
12774            // If any of the following highlights intersect with this one, merge them.
12775            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12776                let highlight = &row_highlights[ix];
12777                if next_highlight
12778                    .range
12779                    .start
12780                    .cmp(&highlight.range.end, &snapshot)
12781                    .is_le()
12782                {
12783                    if next_highlight
12784                        .range
12785                        .end
12786                        .cmp(&highlight.range.end, &snapshot)
12787                        .is_gt()
12788                    {
12789                        row_highlights[ix].range.end = next_highlight.range.end;
12790                    }
12791                    row_highlights.remove(ix + 1);
12792                } else {
12793                    break;
12794                }
12795            }
12796        }
12797    }
12798
12799    /// Remove any highlighted row ranges of the given type that intersect the
12800    /// given ranges.
12801    pub fn remove_highlighted_rows<T: 'static>(
12802        &mut self,
12803        ranges_to_remove: Vec<Range<Anchor>>,
12804        cx: &mut Context<Self>,
12805    ) {
12806        let snapshot = self.buffer().read(cx).snapshot(cx);
12807        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12808        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12809        row_highlights.retain(|highlight| {
12810            while let Some(range_to_remove) = ranges_to_remove.peek() {
12811                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12812                    Ordering::Less | Ordering::Equal => {
12813                        ranges_to_remove.next();
12814                    }
12815                    Ordering::Greater => {
12816                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12817                            Ordering::Less | Ordering::Equal => {
12818                                return false;
12819                            }
12820                            Ordering::Greater => break,
12821                        }
12822                    }
12823                }
12824            }
12825
12826            true
12827        })
12828    }
12829
12830    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12831    pub fn clear_row_highlights<T: 'static>(&mut self) {
12832        self.highlighted_rows.remove(&TypeId::of::<T>());
12833    }
12834
12835    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12836    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12837        self.highlighted_rows
12838            .get(&TypeId::of::<T>())
12839            .map_or(&[] as &[_], |vec| vec.as_slice())
12840            .iter()
12841            .map(|highlight| (highlight.range.clone(), highlight.color))
12842    }
12843
12844    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12845    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12846    /// Allows to ignore certain kinds of highlights.
12847    pub fn highlighted_display_rows(
12848        &self,
12849        window: &mut Window,
12850        cx: &mut App,
12851    ) -> BTreeMap<DisplayRow, Hsla> {
12852        let snapshot = self.snapshot(window, cx);
12853        let mut used_highlight_orders = HashMap::default();
12854        self.highlighted_rows
12855            .iter()
12856            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12857            .fold(
12858                BTreeMap::<DisplayRow, Hsla>::new(),
12859                |mut unique_rows, highlight| {
12860                    let start = highlight.range.start.to_display_point(&snapshot);
12861                    let end = highlight.range.end.to_display_point(&snapshot);
12862                    let start_row = start.row().0;
12863                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12864                        && end.column() == 0
12865                    {
12866                        end.row().0.saturating_sub(1)
12867                    } else {
12868                        end.row().0
12869                    };
12870                    for row in start_row..=end_row {
12871                        let used_index =
12872                            used_highlight_orders.entry(row).or_insert(highlight.index);
12873                        if highlight.index >= *used_index {
12874                            *used_index = highlight.index;
12875                            unique_rows.insert(DisplayRow(row), highlight.color);
12876                        }
12877                    }
12878                    unique_rows
12879                },
12880            )
12881    }
12882
12883    pub fn highlighted_display_row_for_autoscroll(
12884        &self,
12885        snapshot: &DisplaySnapshot,
12886    ) -> Option<DisplayRow> {
12887        self.highlighted_rows
12888            .values()
12889            .flat_map(|highlighted_rows| highlighted_rows.iter())
12890            .filter_map(|highlight| {
12891                if highlight.should_autoscroll {
12892                    Some(highlight.range.start.to_display_point(snapshot).row())
12893                } else {
12894                    None
12895                }
12896            })
12897            .min()
12898    }
12899
12900    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12901        self.highlight_background::<SearchWithinRange>(
12902            ranges,
12903            |colors| colors.editor_document_highlight_read_background,
12904            cx,
12905        )
12906    }
12907
12908    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12909        self.breadcrumb_header = Some(new_header);
12910    }
12911
12912    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12913        self.clear_background_highlights::<SearchWithinRange>(cx);
12914    }
12915
12916    pub fn highlight_background<T: 'static>(
12917        &mut self,
12918        ranges: &[Range<Anchor>],
12919        color_fetcher: fn(&ThemeColors) -> Hsla,
12920        cx: &mut Context<Self>,
12921    ) {
12922        self.background_highlights
12923            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12924        self.scrollbar_marker_state.dirty = true;
12925        cx.notify();
12926    }
12927
12928    pub fn clear_background_highlights<T: 'static>(
12929        &mut self,
12930        cx: &mut Context<Self>,
12931    ) -> Option<BackgroundHighlight> {
12932        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12933        if !text_highlights.1.is_empty() {
12934            self.scrollbar_marker_state.dirty = true;
12935            cx.notify();
12936        }
12937        Some(text_highlights)
12938    }
12939
12940    pub fn highlight_gutter<T: 'static>(
12941        &mut self,
12942        ranges: &[Range<Anchor>],
12943        color_fetcher: fn(&App) -> Hsla,
12944        cx: &mut Context<Self>,
12945    ) {
12946        self.gutter_highlights
12947            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12948        cx.notify();
12949    }
12950
12951    pub fn clear_gutter_highlights<T: 'static>(
12952        &mut self,
12953        cx: &mut Context<Self>,
12954    ) -> Option<GutterHighlight> {
12955        cx.notify();
12956        self.gutter_highlights.remove(&TypeId::of::<T>())
12957    }
12958
12959    #[cfg(feature = "test-support")]
12960    pub fn all_text_background_highlights(
12961        &self,
12962        window: &mut Window,
12963        cx: &mut Context<Self>,
12964    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12965        let snapshot = self.snapshot(window, cx);
12966        let buffer = &snapshot.buffer_snapshot;
12967        let start = buffer.anchor_before(0);
12968        let end = buffer.anchor_after(buffer.len());
12969        let theme = cx.theme().colors();
12970        self.background_highlights_in_range(start..end, &snapshot, theme)
12971    }
12972
12973    #[cfg(feature = "test-support")]
12974    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12975        let snapshot = self.buffer().read(cx).snapshot(cx);
12976
12977        let highlights = self
12978            .background_highlights
12979            .get(&TypeId::of::<items::BufferSearchHighlights>());
12980
12981        if let Some((_color, ranges)) = highlights {
12982            ranges
12983                .iter()
12984                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12985                .collect_vec()
12986        } else {
12987            vec![]
12988        }
12989    }
12990
12991    fn document_highlights_for_position<'a>(
12992        &'a self,
12993        position: Anchor,
12994        buffer: &'a MultiBufferSnapshot,
12995    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12996        let read_highlights = self
12997            .background_highlights
12998            .get(&TypeId::of::<DocumentHighlightRead>())
12999            .map(|h| &h.1);
13000        let write_highlights = self
13001            .background_highlights
13002            .get(&TypeId::of::<DocumentHighlightWrite>())
13003            .map(|h| &h.1);
13004        let left_position = position.bias_left(buffer);
13005        let right_position = position.bias_right(buffer);
13006        read_highlights
13007            .into_iter()
13008            .chain(write_highlights)
13009            .flat_map(move |ranges| {
13010                let start_ix = match ranges.binary_search_by(|probe| {
13011                    let cmp = probe.end.cmp(&left_position, buffer);
13012                    if cmp.is_ge() {
13013                        Ordering::Greater
13014                    } else {
13015                        Ordering::Less
13016                    }
13017                }) {
13018                    Ok(i) | Err(i) => i,
13019                };
13020
13021                ranges[start_ix..]
13022                    .iter()
13023                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13024            })
13025    }
13026
13027    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13028        self.background_highlights
13029            .get(&TypeId::of::<T>())
13030            .map_or(false, |(_, highlights)| !highlights.is_empty())
13031    }
13032
13033    pub fn background_highlights_in_range(
13034        &self,
13035        search_range: Range<Anchor>,
13036        display_snapshot: &DisplaySnapshot,
13037        theme: &ThemeColors,
13038    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13039        let mut results = Vec::new();
13040        for (color_fetcher, ranges) in self.background_highlights.values() {
13041            let color = color_fetcher(theme);
13042            let start_ix = match ranges.binary_search_by(|probe| {
13043                let cmp = probe
13044                    .end
13045                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13046                if cmp.is_gt() {
13047                    Ordering::Greater
13048                } else {
13049                    Ordering::Less
13050                }
13051            }) {
13052                Ok(i) | Err(i) => i,
13053            };
13054            for range in &ranges[start_ix..] {
13055                if range
13056                    .start
13057                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13058                    .is_ge()
13059                {
13060                    break;
13061                }
13062
13063                let start = range.start.to_display_point(display_snapshot);
13064                let end = range.end.to_display_point(display_snapshot);
13065                results.push((start..end, color))
13066            }
13067        }
13068        results
13069    }
13070
13071    pub fn background_highlight_row_ranges<T: 'static>(
13072        &self,
13073        search_range: Range<Anchor>,
13074        display_snapshot: &DisplaySnapshot,
13075        count: usize,
13076    ) -> Vec<RangeInclusive<DisplayPoint>> {
13077        let mut results = Vec::new();
13078        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13079            return vec![];
13080        };
13081
13082        let start_ix = match ranges.binary_search_by(|probe| {
13083            let cmp = probe
13084                .end
13085                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13086            if cmp.is_gt() {
13087                Ordering::Greater
13088            } else {
13089                Ordering::Less
13090            }
13091        }) {
13092            Ok(i) | Err(i) => i,
13093        };
13094        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13095            if let (Some(start_display), Some(end_display)) = (start, end) {
13096                results.push(
13097                    start_display.to_display_point(display_snapshot)
13098                        ..=end_display.to_display_point(display_snapshot),
13099                );
13100            }
13101        };
13102        let mut start_row: Option<Point> = None;
13103        let mut end_row: Option<Point> = None;
13104        if ranges.len() > count {
13105            return Vec::new();
13106        }
13107        for range in &ranges[start_ix..] {
13108            if range
13109                .start
13110                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13111                .is_ge()
13112            {
13113                break;
13114            }
13115            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13116            if let Some(current_row) = &end_row {
13117                if end.row == current_row.row {
13118                    continue;
13119                }
13120            }
13121            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13122            if start_row.is_none() {
13123                assert_eq!(end_row, None);
13124                start_row = Some(start);
13125                end_row = Some(end);
13126                continue;
13127            }
13128            if let Some(current_end) = end_row.as_mut() {
13129                if start.row > current_end.row + 1 {
13130                    push_region(start_row, end_row);
13131                    start_row = Some(start);
13132                    end_row = Some(end);
13133                } else {
13134                    // Merge two hunks.
13135                    *current_end = end;
13136                }
13137            } else {
13138                unreachable!();
13139            }
13140        }
13141        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13142        push_region(start_row, end_row);
13143        results
13144    }
13145
13146    pub fn gutter_highlights_in_range(
13147        &self,
13148        search_range: Range<Anchor>,
13149        display_snapshot: &DisplaySnapshot,
13150        cx: &App,
13151    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13152        let mut results = Vec::new();
13153        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13154            let color = color_fetcher(cx);
13155            let start_ix = match ranges.binary_search_by(|probe| {
13156                let cmp = probe
13157                    .end
13158                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13159                if cmp.is_gt() {
13160                    Ordering::Greater
13161                } else {
13162                    Ordering::Less
13163                }
13164            }) {
13165                Ok(i) | Err(i) => i,
13166            };
13167            for range in &ranges[start_ix..] {
13168                if range
13169                    .start
13170                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13171                    .is_ge()
13172                {
13173                    break;
13174                }
13175
13176                let start = range.start.to_display_point(display_snapshot);
13177                let end = range.end.to_display_point(display_snapshot);
13178                results.push((start..end, color))
13179            }
13180        }
13181        results
13182    }
13183
13184    /// Get the text ranges corresponding to the redaction query
13185    pub fn redacted_ranges(
13186        &self,
13187        search_range: Range<Anchor>,
13188        display_snapshot: &DisplaySnapshot,
13189        cx: &App,
13190    ) -> Vec<Range<DisplayPoint>> {
13191        display_snapshot
13192            .buffer_snapshot
13193            .redacted_ranges(search_range, |file| {
13194                if let Some(file) = file {
13195                    file.is_private()
13196                        && EditorSettings::get(
13197                            Some(SettingsLocation {
13198                                worktree_id: file.worktree_id(cx),
13199                                path: file.path().as_ref(),
13200                            }),
13201                            cx,
13202                        )
13203                        .redact_private_values
13204                } else {
13205                    false
13206                }
13207            })
13208            .map(|range| {
13209                range.start.to_display_point(display_snapshot)
13210                    ..range.end.to_display_point(display_snapshot)
13211            })
13212            .collect()
13213    }
13214
13215    pub fn highlight_text<T: 'static>(
13216        &mut self,
13217        ranges: Vec<Range<Anchor>>,
13218        style: HighlightStyle,
13219        cx: &mut Context<Self>,
13220    ) {
13221        self.display_map.update(cx, |map, _| {
13222            map.highlight_text(TypeId::of::<T>(), ranges, style)
13223        });
13224        cx.notify();
13225    }
13226
13227    pub(crate) fn highlight_inlays<T: 'static>(
13228        &mut self,
13229        highlights: Vec<InlayHighlight>,
13230        style: HighlightStyle,
13231        cx: &mut Context<Self>,
13232    ) {
13233        self.display_map.update(cx, |map, _| {
13234            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13235        });
13236        cx.notify();
13237    }
13238
13239    pub fn text_highlights<'a, T: 'static>(
13240        &'a self,
13241        cx: &'a App,
13242    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13243        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13244    }
13245
13246    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13247        let cleared = self
13248            .display_map
13249            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13250        if cleared {
13251            cx.notify();
13252        }
13253    }
13254
13255    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13256        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13257            && self.focus_handle.is_focused(window)
13258    }
13259
13260    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13261        self.show_cursor_when_unfocused = is_enabled;
13262        cx.notify();
13263    }
13264
13265    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13266        self.project
13267            .as_ref()
13268            .map(|project| project.read(cx).lsp_store())
13269    }
13270
13271    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13272        cx.notify();
13273    }
13274
13275    fn on_buffer_event(
13276        &mut self,
13277        multibuffer: &Entity<MultiBuffer>,
13278        event: &multi_buffer::Event,
13279        window: &mut Window,
13280        cx: &mut Context<Self>,
13281    ) {
13282        match event {
13283            multi_buffer::Event::Edited {
13284                singleton_buffer_edited,
13285                edited_buffer: buffer_edited,
13286            } => {
13287                self.scrollbar_marker_state.dirty = true;
13288                self.active_indent_guides_state.dirty = true;
13289                self.refresh_active_diagnostics(cx);
13290                self.refresh_code_actions(window, cx);
13291                if self.has_active_inline_completion() {
13292                    self.update_visible_inline_completion(window, cx);
13293                }
13294                if let Some(buffer) = buffer_edited {
13295                    let buffer_id = buffer.read(cx).remote_id();
13296                    if !self.registered_buffers.contains_key(&buffer_id) {
13297                        if let Some(lsp_store) = self.lsp_store(cx) {
13298                            lsp_store.update(cx, |lsp_store, cx| {
13299                                self.registered_buffers.insert(
13300                                    buffer_id,
13301                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13302                                );
13303                            })
13304                        }
13305                    }
13306                }
13307                cx.emit(EditorEvent::BufferEdited);
13308                cx.emit(SearchEvent::MatchesInvalidated);
13309                if *singleton_buffer_edited {
13310                    if let Some(project) = &self.project {
13311                        let project = project.read(cx);
13312                        #[allow(clippy::mutable_key_type)]
13313                        let languages_affected = multibuffer
13314                            .read(cx)
13315                            .all_buffers()
13316                            .into_iter()
13317                            .filter_map(|buffer| {
13318                                let buffer = buffer.read(cx);
13319                                let language = buffer.language()?;
13320                                if project.is_local()
13321                                    && project
13322                                        .language_servers_for_local_buffer(buffer, cx)
13323                                        .count()
13324                                        == 0
13325                                {
13326                                    None
13327                                } else {
13328                                    Some(language)
13329                                }
13330                            })
13331                            .cloned()
13332                            .collect::<HashSet<_>>();
13333                        if !languages_affected.is_empty() {
13334                            self.refresh_inlay_hints(
13335                                InlayHintRefreshReason::BufferEdited(languages_affected),
13336                                cx,
13337                            );
13338                        }
13339                    }
13340                }
13341
13342                let Some(project) = &self.project else { return };
13343                let (telemetry, is_via_ssh) = {
13344                    let project = project.read(cx);
13345                    let telemetry = project.client().telemetry().clone();
13346                    let is_via_ssh = project.is_via_ssh();
13347                    (telemetry, is_via_ssh)
13348                };
13349                refresh_linked_ranges(self, window, cx);
13350                telemetry.log_edit_event("editor", is_via_ssh);
13351            }
13352            multi_buffer::Event::ExcerptsAdded {
13353                buffer,
13354                predecessor,
13355                excerpts,
13356            } => {
13357                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13358                let buffer_id = buffer.read(cx).remote_id();
13359                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13360                    if let Some(project) = &self.project {
13361                        get_unstaged_changes_for_buffers(
13362                            project,
13363                            [buffer.clone()],
13364                            self.buffer.clone(),
13365                            cx,
13366                        );
13367                    }
13368                }
13369                cx.emit(EditorEvent::ExcerptsAdded {
13370                    buffer: buffer.clone(),
13371                    predecessor: *predecessor,
13372                    excerpts: excerpts.clone(),
13373                });
13374                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13375            }
13376            multi_buffer::Event::ExcerptsRemoved { ids } => {
13377                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13378                let buffer = self.buffer.read(cx);
13379                self.registered_buffers
13380                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13381                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13382            }
13383            multi_buffer::Event::ExcerptsEdited { ids } => {
13384                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13385            }
13386            multi_buffer::Event::ExcerptsExpanded { ids } => {
13387                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13388                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13389            }
13390            multi_buffer::Event::Reparsed(buffer_id) => {
13391                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13392
13393                cx.emit(EditorEvent::Reparsed(*buffer_id));
13394            }
13395            multi_buffer::Event::DiffHunksToggled => {
13396                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13397            }
13398            multi_buffer::Event::LanguageChanged(buffer_id) => {
13399                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13400                cx.emit(EditorEvent::Reparsed(*buffer_id));
13401                cx.notify();
13402            }
13403            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13404            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13405            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13406                cx.emit(EditorEvent::TitleChanged)
13407            }
13408            // multi_buffer::Event::DiffBaseChanged => {
13409            //     self.scrollbar_marker_state.dirty = true;
13410            //     cx.emit(EditorEvent::DiffBaseChanged);
13411            //     cx.notify();
13412            // }
13413            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13414            multi_buffer::Event::DiagnosticsUpdated => {
13415                self.refresh_active_diagnostics(cx);
13416                self.scrollbar_marker_state.dirty = true;
13417                cx.notify();
13418            }
13419            _ => {}
13420        };
13421    }
13422
13423    fn on_display_map_changed(
13424        &mut self,
13425        _: Entity<DisplayMap>,
13426        _: &mut Window,
13427        cx: &mut Context<Self>,
13428    ) {
13429        cx.notify();
13430    }
13431
13432    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13433        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13434        self.refresh_inline_completion(true, false, window, cx);
13435        self.refresh_inlay_hints(
13436            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13437                self.selections.newest_anchor().head(),
13438                &self.buffer.read(cx).snapshot(cx),
13439                cx,
13440            )),
13441            cx,
13442        );
13443
13444        let old_cursor_shape = self.cursor_shape;
13445
13446        {
13447            let editor_settings = EditorSettings::get_global(cx);
13448            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13449            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13450            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13451        }
13452
13453        if old_cursor_shape != self.cursor_shape {
13454            cx.emit(EditorEvent::CursorShapeChanged);
13455        }
13456
13457        let project_settings = ProjectSettings::get_global(cx);
13458        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13459
13460        if self.mode == EditorMode::Full {
13461            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13462            if self.git_blame_inline_enabled != inline_blame_enabled {
13463                self.toggle_git_blame_inline_internal(false, window, cx);
13464            }
13465        }
13466
13467        cx.notify();
13468    }
13469
13470    pub fn set_searchable(&mut self, searchable: bool) {
13471        self.searchable = searchable;
13472    }
13473
13474    pub fn searchable(&self) -> bool {
13475        self.searchable
13476    }
13477
13478    fn open_proposed_changes_editor(
13479        &mut self,
13480        _: &OpenProposedChangesEditor,
13481        window: &mut Window,
13482        cx: &mut Context<Self>,
13483    ) {
13484        let Some(workspace) = self.workspace() else {
13485            cx.propagate();
13486            return;
13487        };
13488
13489        let selections = self.selections.all::<usize>(cx);
13490        let multi_buffer = self.buffer.read(cx);
13491        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13492        let mut new_selections_by_buffer = HashMap::default();
13493        for selection in selections {
13494            for (buffer, range, _) in
13495                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13496            {
13497                let mut range = range.to_point(buffer);
13498                range.start.column = 0;
13499                range.end.column = buffer.line_len(range.end.row);
13500                new_selections_by_buffer
13501                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13502                    .or_insert(Vec::new())
13503                    .push(range)
13504            }
13505        }
13506
13507        let proposed_changes_buffers = new_selections_by_buffer
13508            .into_iter()
13509            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13510            .collect::<Vec<_>>();
13511        let proposed_changes_editor = cx.new(|cx| {
13512            ProposedChangesEditor::new(
13513                "Proposed changes",
13514                proposed_changes_buffers,
13515                self.project.clone(),
13516                window,
13517                cx,
13518            )
13519        });
13520
13521        window.defer(cx, move |window, cx| {
13522            workspace.update(cx, |workspace, cx| {
13523                workspace.active_pane().update(cx, |pane, cx| {
13524                    pane.add_item(
13525                        Box::new(proposed_changes_editor),
13526                        true,
13527                        true,
13528                        None,
13529                        window,
13530                        cx,
13531                    );
13532                });
13533            });
13534        });
13535    }
13536
13537    pub fn open_excerpts_in_split(
13538        &mut self,
13539        _: &OpenExcerptsSplit,
13540        window: &mut Window,
13541        cx: &mut Context<Self>,
13542    ) {
13543        self.open_excerpts_common(None, true, window, cx)
13544    }
13545
13546    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13547        self.open_excerpts_common(None, false, window, cx)
13548    }
13549
13550    fn open_excerpts_common(
13551        &mut self,
13552        jump_data: Option<JumpData>,
13553        split: bool,
13554        window: &mut Window,
13555        cx: &mut Context<Self>,
13556    ) {
13557        let Some(workspace) = self.workspace() else {
13558            cx.propagate();
13559            return;
13560        };
13561
13562        if self.buffer.read(cx).is_singleton() {
13563            cx.propagate();
13564            return;
13565        }
13566
13567        let mut new_selections_by_buffer = HashMap::default();
13568        match &jump_data {
13569            Some(JumpData::MultiBufferPoint {
13570                excerpt_id,
13571                position,
13572                anchor,
13573                line_offset_from_top,
13574            }) => {
13575                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13576                if let Some(buffer) = multi_buffer_snapshot
13577                    .buffer_id_for_excerpt(*excerpt_id)
13578                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13579                {
13580                    let buffer_snapshot = buffer.read(cx).snapshot();
13581                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13582                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13583                    } else {
13584                        buffer_snapshot.clip_point(*position, Bias::Left)
13585                    };
13586                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13587                    new_selections_by_buffer.insert(
13588                        buffer,
13589                        (
13590                            vec![jump_to_offset..jump_to_offset],
13591                            Some(*line_offset_from_top),
13592                        ),
13593                    );
13594                }
13595            }
13596            Some(JumpData::MultiBufferRow {
13597                row,
13598                line_offset_from_top,
13599            }) => {
13600                let point = MultiBufferPoint::new(row.0, 0);
13601                if let Some((buffer, buffer_point, _)) =
13602                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13603                {
13604                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13605                    new_selections_by_buffer
13606                        .entry(buffer)
13607                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13608                        .0
13609                        .push(buffer_offset..buffer_offset)
13610                }
13611            }
13612            None => {
13613                let selections = self.selections.all::<usize>(cx);
13614                let multi_buffer = self.buffer.read(cx);
13615                for selection in selections {
13616                    for (buffer, mut range, _) in multi_buffer
13617                        .snapshot(cx)
13618                        .range_to_buffer_ranges(selection.range())
13619                    {
13620                        // When editing branch buffers, jump to the corresponding location
13621                        // in their base buffer.
13622                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13623                        let buffer = buffer_handle.read(cx);
13624                        if let Some(base_buffer) = buffer.base_buffer() {
13625                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13626                            buffer_handle = base_buffer;
13627                        }
13628
13629                        if selection.reversed {
13630                            mem::swap(&mut range.start, &mut range.end);
13631                        }
13632                        new_selections_by_buffer
13633                            .entry(buffer_handle)
13634                            .or_insert((Vec::new(), None))
13635                            .0
13636                            .push(range)
13637                    }
13638                }
13639            }
13640        }
13641
13642        if new_selections_by_buffer.is_empty() {
13643            return;
13644        }
13645
13646        // We defer the pane interaction because we ourselves are a workspace item
13647        // and activating a new item causes the pane to call a method on us reentrantly,
13648        // which panics if we're on the stack.
13649        window.defer(cx, move |window, cx| {
13650            workspace.update(cx, |workspace, cx| {
13651                let pane = if split {
13652                    workspace.adjacent_pane(window, cx)
13653                } else {
13654                    workspace.active_pane().clone()
13655                };
13656
13657                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13658                    let editor = buffer
13659                        .read(cx)
13660                        .file()
13661                        .is_none()
13662                        .then(|| {
13663                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13664                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13665                            // Instead, we try to activate the existing editor in the pane first.
13666                            let (editor, pane_item_index) =
13667                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13668                                    let editor = item.downcast::<Editor>()?;
13669                                    let singleton_buffer =
13670                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13671                                    if singleton_buffer == buffer {
13672                                        Some((editor, i))
13673                                    } else {
13674                                        None
13675                                    }
13676                                })?;
13677                            pane.update(cx, |pane, cx| {
13678                                pane.activate_item(pane_item_index, true, true, window, cx)
13679                            });
13680                            Some(editor)
13681                        })
13682                        .flatten()
13683                        .unwrap_or_else(|| {
13684                            workspace.open_project_item::<Self>(
13685                                pane.clone(),
13686                                buffer,
13687                                true,
13688                                true,
13689                                window,
13690                                cx,
13691                            )
13692                        });
13693
13694                    editor.update(cx, |editor, cx| {
13695                        let autoscroll = match scroll_offset {
13696                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13697                            None => Autoscroll::newest(),
13698                        };
13699                        let nav_history = editor.nav_history.take();
13700                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13701                            s.select_ranges(ranges);
13702                        });
13703                        editor.nav_history = nav_history;
13704                    });
13705                }
13706            })
13707        });
13708    }
13709
13710    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13711        let snapshot = self.buffer.read(cx).read(cx);
13712        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13713        Some(
13714            ranges
13715                .iter()
13716                .map(move |range| {
13717                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13718                })
13719                .collect(),
13720        )
13721    }
13722
13723    fn selection_replacement_ranges(
13724        &self,
13725        range: Range<OffsetUtf16>,
13726        cx: &mut App,
13727    ) -> Vec<Range<OffsetUtf16>> {
13728        let selections = self.selections.all::<OffsetUtf16>(cx);
13729        let newest_selection = selections
13730            .iter()
13731            .max_by_key(|selection| selection.id)
13732            .unwrap();
13733        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13734        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13735        let snapshot = self.buffer.read(cx).read(cx);
13736        selections
13737            .into_iter()
13738            .map(|mut selection| {
13739                selection.start.0 =
13740                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13741                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13742                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13743                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13744            })
13745            .collect()
13746    }
13747
13748    fn report_editor_event(
13749        &self,
13750        event_type: &'static str,
13751        file_extension: Option<String>,
13752        cx: &App,
13753    ) {
13754        if cfg!(any(test, feature = "test-support")) {
13755            return;
13756        }
13757
13758        let Some(project) = &self.project else { return };
13759
13760        // If None, we are in a file without an extension
13761        let file = self
13762            .buffer
13763            .read(cx)
13764            .as_singleton()
13765            .and_then(|b| b.read(cx).file());
13766        let file_extension = file_extension.or(file
13767            .as_ref()
13768            .and_then(|file| Path::new(file.file_name(cx)).extension())
13769            .and_then(|e| e.to_str())
13770            .map(|a| a.to_string()));
13771
13772        let vim_mode = cx
13773            .global::<SettingsStore>()
13774            .raw_user_settings()
13775            .get("vim_mode")
13776            == Some(&serde_json::Value::Bool(true));
13777
13778        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13779            == language::language_settings::InlineCompletionProvider::Copilot;
13780        let copilot_enabled_for_language = self
13781            .buffer
13782            .read(cx)
13783            .settings_at(0, cx)
13784            .show_inline_completions;
13785
13786        let project = project.read(cx);
13787        telemetry::event!(
13788            event_type,
13789            file_extension,
13790            vim_mode,
13791            copilot_enabled,
13792            copilot_enabled_for_language,
13793            is_via_ssh = project.is_via_ssh(),
13794        );
13795    }
13796
13797    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13798    /// with each line being an array of {text, highlight} objects.
13799    fn copy_highlight_json(
13800        &mut self,
13801        _: &CopyHighlightJson,
13802        window: &mut Window,
13803        cx: &mut Context<Self>,
13804    ) {
13805        #[derive(Serialize)]
13806        struct Chunk<'a> {
13807            text: String,
13808            highlight: Option<&'a str>,
13809        }
13810
13811        let snapshot = self.buffer.read(cx).snapshot(cx);
13812        let range = self
13813            .selected_text_range(false, window, cx)
13814            .and_then(|selection| {
13815                if selection.range.is_empty() {
13816                    None
13817                } else {
13818                    Some(selection.range)
13819                }
13820            })
13821            .unwrap_or_else(|| 0..snapshot.len());
13822
13823        let chunks = snapshot.chunks(range, true);
13824        let mut lines = Vec::new();
13825        let mut line: VecDeque<Chunk> = VecDeque::new();
13826
13827        let Some(style) = self.style.as_ref() else {
13828            return;
13829        };
13830
13831        for chunk in chunks {
13832            let highlight = chunk
13833                .syntax_highlight_id
13834                .and_then(|id| id.name(&style.syntax));
13835            let mut chunk_lines = chunk.text.split('\n').peekable();
13836            while let Some(text) = chunk_lines.next() {
13837                let mut merged_with_last_token = false;
13838                if let Some(last_token) = line.back_mut() {
13839                    if last_token.highlight == highlight {
13840                        last_token.text.push_str(text);
13841                        merged_with_last_token = true;
13842                    }
13843                }
13844
13845                if !merged_with_last_token {
13846                    line.push_back(Chunk {
13847                        text: text.into(),
13848                        highlight,
13849                    });
13850                }
13851
13852                if chunk_lines.peek().is_some() {
13853                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13854                        line.pop_front();
13855                    }
13856                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13857                        line.pop_back();
13858                    }
13859
13860                    lines.push(mem::take(&mut line));
13861                }
13862            }
13863        }
13864
13865        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13866            return;
13867        };
13868        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13869    }
13870
13871    pub fn open_context_menu(
13872        &mut self,
13873        _: &OpenContextMenu,
13874        window: &mut Window,
13875        cx: &mut Context<Self>,
13876    ) {
13877        self.request_autoscroll(Autoscroll::newest(), cx);
13878        let position = self.selections.newest_display(cx).start;
13879        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13880    }
13881
13882    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13883        &self.inlay_hint_cache
13884    }
13885
13886    pub fn replay_insert_event(
13887        &mut self,
13888        text: &str,
13889        relative_utf16_range: Option<Range<isize>>,
13890        window: &mut Window,
13891        cx: &mut Context<Self>,
13892    ) {
13893        if !self.input_enabled {
13894            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13895            return;
13896        }
13897        if let Some(relative_utf16_range) = relative_utf16_range {
13898            let selections = self.selections.all::<OffsetUtf16>(cx);
13899            self.change_selections(None, window, cx, |s| {
13900                let new_ranges = selections.into_iter().map(|range| {
13901                    let start = OffsetUtf16(
13902                        range
13903                            .head()
13904                            .0
13905                            .saturating_add_signed(relative_utf16_range.start),
13906                    );
13907                    let end = OffsetUtf16(
13908                        range
13909                            .head()
13910                            .0
13911                            .saturating_add_signed(relative_utf16_range.end),
13912                    );
13913                    start..end
13914                });
13915                s.select_ranges(new_ranges);
13916            });
13917        }
13918
13919        self.handle_input(text, window, cx);
13920    }
13921
13922    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13923        let Some(provider) = self.semantics_provider.as_ref() else {
13924            return false;
13925        };
13926
13927        let mut supports = false;
13928        self.buffer().read(cx).for_each_buffer(|buffer| {
13929            supports |= provider.supports_inlay_hints(buffer, cx);
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: &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: &App) -> bool {
14872        // TODO: make this work for remote projects
14873        self.read(cx)
14874            .language_servers_for_local_buffer(buffer.read(cx), cx)
14875            .any(
14876                |(_, server)| match server.capabilities().inlay_hint_provider {
14877                    Some(lsp::OneOf::Left(enabled)) => enabled,
14878                    Some(lsp::OneOf::Right(_)) => true,
14879                    None => false,
14880                },
14881            )
14882    }
14883
14884    fn inlay_hints(
14885        &self,
14886        buffer_handle: Entity<Buffer>,
14887        range: Range<text::Anchor>,
14888        cx: &mut App,
14889    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14890        Some(self.update(cx, |project, cx| {
14891            project.inlay_hints(buffer_handle, range, cx)
14892        }))
14893    }
14894
14895    fn resolve_inlay_hint(
14896        &self,
14897        hint: InlayHint,
14898        buffer_handle: Entity<Buffer>,
14899        server_id: LanguageServerId,
14900        cx: &mut App,
14901    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14902        Some(self.update(cx, |project, cx| {
14903            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14904        }))
14905    }
14906
14907    fn range_for_rename(
14908        &self,
14909        buffer: &Entity<Buffer>,
14910        position: text::Anchor,
14911        cx: &mut App,
14912    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14913        Some(self.update(cx, |project, cx| {
14914            let buffer = buffer.clone();
14915            let task = project.prepare_rename(buffer.clone(), position, cx);
14916            cx.spawn(|_, mut cx| async move {
14917                Ok(match task.await? {
14918                    PrepareRenameResponse::Success(range) => Some(range),
14919                    PrepareRenameResponse::InvalidPosition => None,
14920                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14921                        // Fallback on using TreeSitter info to determine identifier range
14922                        buffer.update(&mut cx, |buffer, _| {
14923                            let snapshot = buffer.snapshot();
14924                            let (range, kind) = snapshot.surrounding_word(position);
14925                            if kind != Some(CharKind::Word) {
14926                                return None;
14927                            }
14928                            Some(
14929                                snapshot.anchor_before(range.start)
14930                                    ..snapshot.anchor_after(range.end),
14931                            )
14932                        })?
14933                    }
14934                })
14935            })
14936        }))
14937    }
14938
14939    fn perform_rename(
14940        &self,
14941        buffer: &Entity<Buffer>,
14942        position: text::Anchor,
14943        new_name: String,
14944        cx: &mut App,
14945    ) -> Option<Task<Result<ProjectTransaction>>> {
14946        Some(self.update(cx, |project, cx| {
14947            project.perform_rename(buffer.clone(), position, new_name, cx)
14948        }))
14949    }
14950}
14951
14952fn inlay_hint_settings(
14953    location: Anchor,
14954    snapshot: &MultiBufferSnapshot,
14955    cx: &mut Context<Editor>,
14956) -> InlayHintSettings {
14957    let file = snapshot.file_at(location);
14958    let language = snapshot.language_at(location).map(|l| l.name());
14959    language_settings(language, file, cx).inlay_hints
14960}
14961
14962fn consume_contiguous_rows(
14963    contiguous_row_selections: &mut Vec<Selection<Point>>,
14964    selection: &Selection<Point>,
14965    display_map: &DisplaySnapshot,
14966    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14967) -> (MultiBufferRow, MultiBufferRow) {
14968    contiguous_row_selections.push(selection.clone());
14969    let start_row = MultiBufferRow(selection.start.row);
14970    let mut end_row = ending_row(selection, display_map);
14971
14972    while let Some(next_selection) = selections.peek() {
14973        if next_selection.start.row <= end_row.0 {
14974            end_row = ending_row(next_selection, display_map);
14975            contiguous_row_selections.push(selections.next().unwrap().clone());
14976        } else {
14977            break;
14978        }
14979    }
14980    (start_row, end_row)
14981}
14982
14983fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14984    if next_selection.end.column > 0 || next_selection.is_empty() {
14985        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14986    } else {
14987        MultiBufferRow(next_selection.end.row)
14988    }
14989}
14990
14991impl EditorSnapshot {
14992    pub fn remote_selections_in_range<'a>(
14993        &'a self,
14994        range: &'a Range<Anchor>,
14995        collaboration_hub: &dyn CollaborationHub,
14996        cx: &'a App,
14997    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14998        let participant_names = collaboration_hub.user_names(cx);
14999        let participant_indices = collaboration_hub.user_participant_indices(cx);
15000        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15001        let collaborators_by_replica_id = collaborators_by_peer_id
15002            .iter()
15003            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15004            .collect::<HashMap<_, _>>();
15005        self.buffer_snapshot
15006            .selections_in_range(range, false)
15007            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15008                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15009                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15010                let user_name = participant_names.get(&collaborator.user_id).cloned();
15011                Some(RemoteSelection {
15012                    replica_id,
15013                    selection,
15014                    cursor_shape,
15015                    line_mode,
15016                    participant_index,
15017                    peer_id: collaborator.peer_id,
15018                    user_name,
15019                })
15020            })
15021    }
15022
15023    pub fn hunks_for_ranges(
15024        &self,
15025        ranges: impl Iterator<Item = Range<Point>>,
15026    ) -> Vec<MultiBufferDiffHunk> {
15027        let mut hunks = Vec::new();
15028        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15029            HashMap::default();
15030        for query_range in ranges {
15031            let query_rows =
15032                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15033            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15034                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15035            ) {
15036                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15037                // when the caret is just above or just below the deleted hunk.
15038                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15039                let related_to_selection = if allow_adjacent {
15040                    hunk.row_range.overlaps(&query_rows)
15041                        || hunk.row_range.start == query_rows.end
15042                        || hunk.row_range.end == query_rows.start
15043                } else {
15044                    hunk.row_range.overlaps(&query_rows)
15045                };
15046                if related_to_selection {
15047                    if !processed_buffer_rows
15048                        .entry(hunk.buffer_id)
15049                        .or_default()
15050                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15051                    {
15052                        continue;
15053                    }
15054                    hunks.push(hunk);
15055                }
15056            }
15057        }
15058
15059        hunks
15060    }
15061
15062    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15063        self.display_snapshot.buffer_snapshot.language_at(position)
15064    }
15065
15066    pub fn is_focused(&self) -> bool {
15067        self.is_focused
15068    }
15069
15070    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15071        self.placeholder_text.as_ref()
15072    }
15073
15074    pub fn scroll_position(&self) -> gpui::Point<f32> {
15075        self.scroll_anchor.scroll_position(&self.display_snapshot)
15076    }
15077
15078    fn gutter_dimensions(
15079        &self,
15080        font_id: FontId,
15081        font_size: Pixels,
15082        em_width: Pixels,
15083        em_advance: Pixels,
15084        max_line_number_width: Pixels,
15085        cx: &App,
15086    ) -> GutterDimensions {
15087        if !self.show_gutter {
15088            return GutterDimensions::default();
15089        }
15090        let descent = cx.text_system().descent(font_id, font_size);
15091
15092        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15093            matches!(
15094                ProjectSettings::get_global(cx).git.git_gutter,
15095                Some(GitGutterSetting::TrackedFiles)
15096            )
15097        });
15098        let gutter_settings = EditorSettings::get_global(cx).gutter;
15099        let show_line_numbers = self
15100            .show_line_numbers
15101            .unwrap_or(gutter_settings.line_numbers);
15102        let line_gutter_width = if show_line_numbers {
15103            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15104            let min_width_for_number_on_gutter = em_advance * 4.0;
15105            max_line_number_width.max(min_width_for_number_on_gutter)
15106        } else {
15107            0.0.into()
15108        };
15109
15110        let show_code_actions = self
15111            .show_code_actions
15112            .unwrap_or(gutter_settings.code_actions);
15113
15114        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15115
15116        let git_blame_entries_width =
15117            self.git_blame_gutter_max_author_length
15118                .map(|max_author_length| {
15119                    // Length of the author name, but also space for the commit hash,
15120                    // the spacing and the timestamp.
15121                    let max_char_count = max_author_length
15122                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15123                        + 7 // length of commit sha
15124                        + 14 // length of max relative timestamp ("60 minutes ago")
15125                        + 4; // gaps and margins
15126
15127                    em_advance * max_char_count
15128                });
15129
15130        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15131        left_padding += if show_code_actions || show_runnables {
15132            em_width * 3.0
15133        } else if show_git_gutter && show_line_numbers {
15134            em_width * 2.0
15135        } else if show_git_gutter || show_line_numbers {
15136            em_width
15137        } else {
15138            px(0.)
15139        };
15140
15141        let right_padding = if gutter_settings.folds && show_line_numbers {
15142            em_width * 4.0
15143        } else if gutter_settings.folds {
15144            em_width * 3.0
15145        } else if show_line_numbers {
15146            em_width
15147        } else {
15148            px(0.)
15149        };
15150
15151        GutterDimensions {
15152            left_padding,
15153            right_padding,
15154            width: line_gutter_width + left_padding + right_padding,
15155            margin: -descent,
15156            git_blame_entries_width,
15157        }
15158    }
15159
15160    pub fn render_crease_toggle(
15161        &self,
15162        buffer_row: MultiBufferRow,
15163        row_contains_cursor: bool,
15164        editor: Entity<Editor>,
15165        window: &mut Window,
15166        cx: &mut App,
15167    ) -> Option<AnyElement> {
15168        let folded = self.is_line_folded(buffer_row);
15169        let mut is_foldable = false;
15170
15171        if let Some(crease) = self
15172            .crease_snapshot
15173            .query_row(buffer_row, &self.buffer_snapshot)
15174        {
15175            is_foldable = true;
15176            match crease {
15177                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15178                    if let Some(render_toggle) = render_toggle {
15179                        let toggle_callback =
15180                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15181                                if folded {
15182                                    editor.update(cx, |editor, cx| {
15183                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15184                                    });
15185                                } else {
15186                                    editor.update(cx, |editor, cx| {
15187                                        editor.unfold_at(
15188                                            &crate::UnfoldAt { buffer_row },
15189                                            window,
15190                                            cx,
15191                                        )
15192                                    });
15193                                }
15194                            });
15195                        return Some((render_toggle)(
15196                            buffer_row,
15197                            folded,
15198                            toggle_callback,
15199                            window,
15200                            cx,
15201                        ));
15202                    }
15203                }
15204            }
15205        }
15206
15207        is_foldable |= self.starts_indent(buffer_row);
15208
15209        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15210            Some(
15211                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15212                    .toggle_state(folded)
15213                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15214                        if folded {
15215                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15216                        } else {
15217                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15218                        }
15219                    }))
15220                    .into_any_element(),
15221            )
15222        } else {
15223            None
15224        }
15225    }
15226
15227    pub fn render_crease_trailer(
15228        &self,
15229        buffer_row: MultiBufferRow,
15230        window: &mut Window,
15231        cx: &mut App,
15232    ) -> Option<AnyElement> {
15233        let folded = self.is_line_folded(buffer_row);
15234        if let Crease::Inline { render_trailer, .. } = self
15235            .crease_snapshot
15236            .query_row(buffer_row, &self.buffer_snapshot)?
15237        {
15238            let render_trailer = render_trailer.as_ref()?;
15239            Some(render_trailer(buffer_row, folded, window, cx))
15240        } else {
15241            None
15242        }
15243    }
15244}
15245
15246impl Deref for EditorSnapshot {
15247    type Target = DisplaySnapshot;
15248
15249    fn deref(&self) -> &Self::Target {
15250        &self.display_snapshot
15251    }
15252}
15253
15254#[derive(Clone, Debug, PartialEq, Eq)]
15255pub enum EditorEvent {
15256    InputIgnored {
15257        text: Arc<str>,
15258    },
15259    InputHandled {
15260        utf16_range_to_replace: Option<Range<isize>>,
15261        text: Arc<str>,
15262    },
15263    ExcerptsAdded {
15264        buffer: Entity<Buffer>,
15265        predecessor: ExcerptId,
15266        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15267    },
15268    ExcerptsRemoved {
15269        ids: Vec<ExcerptId>,
15270    },
15271    BufferFoldToggled {
15272        ids: Vec<ExcerptId>,
15273        folded: bool,
15274    },
15275    ExcerptsEdited {
15276        ids: Vec<ExcerptId>,
15277    },
15278    ExcerptsExpanded {
15279        ids: Vec<ExcerptId>,
15280    },
15281    BufferEdited,
15282    Edited {
15283        transaction_id: clock::Lamport,
15284    },
15285    Reparsed(BufferId),
15286    Focused,
15287    FocusedIn,
15288    Blurred,
15289    DirtyChanged,
15290    Saved,
15291    TitleChanged,
15292    DiffBaseChanged,
15293    SelectionsChanged {
15294        local: bool,
15295    },
15296    ScrollPositionChanged {
15297        local: bool,
15298        autoscroll: bool,
15299    },
15300    Closed,
15301    TransactionUndone {
15302        transaction_id: clock::Lamport,
15303    },
15304    TransactionBegun {
15305        transaction_id: clock::Lamport,
15306    },
15307    Reloaded,
15308    CursorShapeChanged,
15309}
15310
15311impl EventEmitter<EditorEvent> for Editor {}
15312
15313impl Focusable for Editor {
15314    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15315        self.focus_handle.clone()
15316    }
15317}
15318
15319impl Render for Editor {
15320    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15321        let settings = ThemeSettings::get_global(cx);
15322
15323        let mut text_style = match self.mode {
15324            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15325                color: cx.theme().colors().editor_foreground,
15326                font_family: settings.ui_font.family.clone(),
15327                font_features: settings.ui_font.features.clone(),
15328                font_fallbacks: settings.ui_font.fallbacks.clone(),
15329                font_size: rems(0.875).into(),
15330                font_weight: settings.ui_font.weight,
15331                line_height: relative(settings.buffer_line_height.value()),
15332                ..Default::default()
15333            },
15334            EditorMode::Full => TextStyle {
15335                color: cx.theme().colors().editor_foreground,
15336                font_family: settings.buffer_font.family.clone(),
15337                font_features: settings.buffer_font.features.clone(),
15338                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15339                font_size: settings.buffer_font_size().into(),
15340                font_weight: settings.buffer_font.weight,
15341                line_height: relative(settings.buffer_line_height.value()),
15342                ..Default::default()
15343            },
15344        };
15345        if let Some(text_style_refinement) = &self.text_style_refinement {
15346            text_style.refine(text_style_refinement)
15347        }
15348
15349        let background = match self.mode {
15350            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15351            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15352            EditorMode::Full => cx.theme().colors().editor_background,
15353        };
15354
15355        EditorElement::new(
15356            &cx.entity(),
15357            EditorStyle {
15358                background,
15359                local_player: cx.theme().players().local(),
15360                text: text_style,
15361                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15362                syntax: cx.theme().syntax().clone(),
15363                status: cx.theme().status().clone(),
15364                inlay_hints_style: make_inlay_hints_style(cx),
15365                inline_completion_styles: make_suggestion_styles(cx),
15366                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15367            },
15368        )
15369    }
15370}
15371
15372impl EntityInputHandler for Editor {
15373    fn text_for_range(
15374        &mut self,
15375        range_utf16: Range<usize>,
15376        adjusted_range: &mut Option<Range<usize>>,
15377        _: &mut Window,
15378        cx: &mut Context<Self>,
15379    ) -> Option<String> {
15380        let snapshot = self.buffer.read(cx).read(cx);
15381        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15382        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15383        if (start.0..end.0) != range_utf16 {
15384            adjusted_range.replace(start.0..end.0);
15385        }
15386        Some(snapshot.text_for_range(start..end).collect())
15387    }
15388
15389    fn selected_text_range(
15390        &mut self,
15391        ignore_disabled_input: bool,
15392        _: &mut Window,
15393        cx: &mut Context<Self>,
15394    ) -> Option<UTF16Selection> {
15395        // Prevent the IME menu from appearing when holding down an alphabetic key
15396        // while input is disabled.
15397        if !ignore_disabled_input && !self.input_enabled {
15398            return None;
15399        }
15400
15401        let selection = self.selections.newest::<OffsetUtf16>(cx);
15402        let range = selection.range();
15403
15404        Some(UTF16Selection {
15405            range: range.start.0..range.end.0,
15406            reversed: selection.reversed,
15407        })
15408    }
15409
15410    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15411        let snapshot = self.buffer.read(cx).read(cx);
15412        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15413        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15414    }
15415
15416    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15417        self.clear_highlights::<InputComposition>(cx);
15418        self.ime_transaction.take();
15419    }
15420
15421    fn replace_text_in_range(
15422        &mut self,
15423        range_utf16: Option<Range<usize>>,
15424        text: &str,
15425        window: &mut Window,
15426        cx: &mut Context<Self>,
15427    ) {
15428        if !self.input_enabled {
15429            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15430            return;
15431        }
15432
15433        self.transact(window, cx, |this, window, cx| {
15434            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15435                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15436                Some(this.selection_replacement_ranges(range_utf16, cx))
15437            } else {
15438                this.marked_text_ranges(cx)
15439            };
15440
15441            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15442                let newest_selection_id = this.selections.newest_anchor().id;
15443                this.selections
15444                    .all::<OffsetUtf16>(cx)
15445                    .iter()
15446                    .zip(ranges_to_replace.iter())
15447                    .find_map(|(selection, range)| {
15448                        if selection.id == newest_selection_id {
15449                            Some(
15450                                (range.start.0 as isize - selection.head().0 as isize)
15451                                    ..(range.end.0 as isize - selection.head().0 as isize),
15452                            )
15453                        } else {
15454                            None
15455                        }
15456                    })
15457            });
15458
15459            cx.emit(EditorEvent::InputHandled {
15460                utf16_range_to_replace: range_to_replace,
15461                text: text.into(),
15462            });
15463
15464            if let Some(new_selected_ranges) = new_selected_ranges {
15465                this.change_selections(None, window, cx, |selections| {
15466                    selections.select_ranges(new_selected_ranges)
15467                });
15468                this.backspace(&Default::default(), window, cx);
15469            }
15470
15471            this.handle_input(text, window, cx);
15472        });
15473
15474        if let Some(transaction) = self.ime_transaction {
15475            self.buffer.update(cx, |buffer, cx| {
15476                buffer.group_until_transaction(transaction, cx);
15477            });
15478        }
15479
15480        self.unmark_text(window, cx);
15481    }
15482
15483    fn replace_and_mark_text_in_range(
15484        &mut self,
15485        range_utf16: Option<Range<usize>>,
15486        text: &str,
15487        new_selected_range_utf16: Option<Range<usize>>,
15488        window: &mut Window,
15489        cx: &mut Context<Self>,
15490    ) {
15491        if !self.input_enabled {
15492            return;
15493        }
15494
15495        let transaction = self.transact(window, cx, |this, window, cx| {
15496            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15497                let snapshot = this.buffer.read(cx).read(cx);
15498                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15499                    for marked_range in &mut marked_ranges {
15500                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15501                        marked_range.start.0 += relative_range_utf16.start;
15502                        marked_range.start =
15503                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15504                        marked_range.end =
15505                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15506                    }
15507                }
15508                Some(marked_ranges)
15509            } else if let Some(range_utf16) = range_utf16 {
15510                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15511                Some(this.selection_replacement_ranges(range_utf16, cx))
15512            } else {
15513                None
15514            };
15515
15516            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15517                let newest_selection_id = this.selections.newest_anchor().id;
15518                this.selections
15519                    .all::<OffsetUtf16>(cx)
15520                    .iter()
15521                    .zip(ranges_to_replace.iter())
15522                    .find_map(|(selection, range)| {
15523                        if selection.id == newest_selection_id {
15524                            Some(
15525                                (range.start.0 as isize - selection.head().0 as isize)
15526                                    ..(range.end.0 as isize - selection.head().0 as isize),
15527                            )
15528                        } else {
15529                            None
15530                        }
15531                    })
15532            });
15533
15534            cx.emit(EditorEvent::InputHandled {
15535                utf16_range_to_replace: range_to_replace,
15536                text: text.into(),
15537            });
15538
15539            if let Some(ranges) = ranges_to_replace {
15540                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15541            }
15542
15543            let marked_ranges = {
15544                let snapshot = this.buffer.read(cx).read(cx);
15545                this.selections
15546                    .disjoint_anchors()
15547                    .iter()
15548                    .map(|selection| {
15549                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15550                    })
15551                    .collect::<Vec<_>>()
15552            };
15553
15554            if text.is_empty() {
15555                this.unmark_text(window, cx);
15556            } else {
15557                this.highlight_text::<InputComposition>(
15558                    marked_ranges.clone(),
15559                    HighlightStyle {
15560                        underline: Some(UnderlineStyle {
15561                            thickness: px(1.),
15562                            color: None,
15563                            wavy: false,
15564                        }),
15565                        ..Default::default()
15566                    },
15567                    cx,
15568                );
15569            }
15570
15571            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15572            let use_autoclose = this.use_autoclose;
15573            let use_auto_surround = this.use_auto_surround;
15574            this.set_use_autoclose(false);
15575            this.set_use_auto_surround(false);
15576            this.handle_input(text, window, cx);
15577            this.set_use_autoclose(use_autoclose);
15578            this.set_use_auto_surround(use_auto_surround);
15579
15580            if let Some(new_selected_range) = new_selected_range_utf16 {
15581                let snapshot = this.buffer.read(cx).read(cx);
15582                let new_selected_ranges = marked_ranges
15583                    .into_iter()
15584                    .map(|marked_range| {
15585                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15586                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15587                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15588                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15589                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15590                    })
15591                    .collect::<Vec<_>>();
15592
15593                drop(snapshot);
15594                this.change_selections(None, window, cx, |selections| {
15595                    selections.select_ranges(new_selected_ranges)
15596                });
15597            }
15598        });
15599
15600        self.ime_transaction = self.ime_transaction.or(transaction);
15601        if let Some(transaction) = self.ime_transaction {
15602            self.buffer.update(cx, |buffer, cx| {
15603                buffer.group_until_transaction(transaction, cx);
15604            });
15605        }
15606
15607        if self.text_highlights::<InputComposition>(cx).is_none() {
15608            self.ime_transaction.take();
15609        }
15610    }
15611
15612    fn bounds_for_range(
15613        &mut self,
15614        range_utf16: Range<usize>,
15615        element_bounds: gpui::Bounds<Pixels>,
15616        window: &mut Window,
15617        cx: &mut Context<Self>,
15618    ) -> Option<gpui::Bounds<Pixels>> {
15619        let text_layout_details = self.text_layout_details(window);
15620        let gpui::Point {
15621            x: em_width,
15622            y: line_height,
15623        } = self.character_size(window);
15624
15625        let snapshot = self.snapshot(window, cx);
15626        let scroll_position = snapshot.scroll_position();
15627        let scroll_left = scroll_position.x * em_width;
15628
15629        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15630        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15631            + self.gutter_dimensions.width
15632            + self.gutter_dimensions.margin;
15633        let y = line_height * (start.row().as_f32() - scroll_position.y);
15634
15635        Some(Bounds {
15636            origin: element_bounds.origin + point(x, y),
15637            size: size(em_width, line_height),
15638        })
15639    }
15640}
15641
15642trait SelectionExt {
15643    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15644    fn spanned_rows(
15645        &self,
15646        include_end_if_at_line_start: bool,
15647        map: &DisplaySnapshot,
15648    ) -> Range<MultiBufferRow>;
15649}
15650
15651impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15652    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15653        let start = self
15654            .start
15655            .to_point(&map.buffer_snapshot)
15656            .to_display_point(map);
15657        let end = self
15658            .end
15659            .to_point(&map.buffer_snapshot)
15660            .to_display_point(map);
15661        if self.reversed {
15662            end..start
15663        } else {
15664            start..end
15665        }
15666    }
15667
15668    fn spanned_rows(
15669        &self,
15670        include_end_if_at_line_start: bool,
15671        map: &DisplaySnapshot,
15672    ) -> Range<MultiBufferRow> {
15673        let start = self.start.to_point(&map.buffer_snapshot);
15674        let mut end = self.end.to_point(&map.buffer_snapshot);
15675        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15676            end.row -= 1;
15677        }
15678
15679        let buffer_start = map.prev_line_boundary(start).0;
15680        let buffer_end = map.next_line_boundary(end).0;
15681        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15682    }
15683}
15684
15685impl<T: InvalidationRegion> InvalidationStack<T> {
15686    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15687    where
15688        S: Clone + ToOffset,
15689    {
15690        while let Some(region) = self.last() {
15691            let all_selections_inside_invalidation_ranges =
15692                if selections.len() == region.ranges().len() {
15693                    selections
15694                        .iter()
15695                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15696                        .all(|(selection, invalidation_range)| {
15697                            let head = selection.head().to_offset(buffer);
15698                            invalidation_range.start <= head && invalidation_range.end >= head
15699                        })
15700                } else {
15701                    false
15702                };
15703
15704            if all_selections_inside_invalidation_ranges {
15705                break;
15706            } else {
15707                self.pop();
15708            }
15709        }
15710    }
15711}
15712
15713impl<T> Default for InvalidationStack<T> {
15714    fn default() -> Self {
15715        Self(Default::default())
15716    }
15717}
15718
15719impl<T> Deref for InvalidationStack<T> {
15720    type Target = Vec<T>;
15721
15722    fn deref(&self) -> &Self::Target {
15723        &self.0
15724    }
15725}
15726
15727impl<T> DerefMut for InvalidationStack<T> {
15728    fn deref_mut(&mut self) -> &mut Self::Target {
15729        &mut self.0
15730    }
15731}
15732
15733impl InvalidationRegion for SnippetState {
15734    fn ranges(&self) -> &[Range<Anchor>] {
15735        &self.ranges[self.active_index]
15736    }
15737}
15738
15739pub fn diagnostic_block_renderer(
15740    diagnostic: Diagnostic,
15741    max_message_rows: Option<u8>,
15742    allow_closing: bool,
15743    _is_valid: bool,
15744) -> RenderBlock {
15745    let (text_without_backticks, code_ranges) =
15746        highlight_diagnostic_message(&diagnostic, max_message_rows);
15747
15748    Arc::new(move |cx: &mut BlockContext| {
15749        let group_id: SharedString = cx.block_id.to_string().into();
15750
15751        let mut text_style = cx.window.text_style().clone();
15752        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15753        let theme_settings = ThemeSettings::get_global(cx);
15754        text_style.font_family = theme_settings.buffer_font.family.clone();
15755        text_style.font_style = theme_settings.buffer_font.style;
15756        text_style.font_features = theme_settings.buffer_font.features.clone();
15757        text_style.font_weight = theme_settings.buffer_font.weight;
15758
15759        let multi_line_diagnostic = diagnostic.message.contains('\n');
15760
15761        let buttons = |diagnostic: &Diagnostic| {
15762            if multi_line_diagnostic {
15763                v_flex()
15764            } else {
15765                h_flex()
15766            }
15767            .when(allow_closing, |div| {
15768                div.children(diagnostic.is_primary.then(|| {
15769                    IconButton::new("close-block", IconName::XCircle)
15770                        .icon_color(Color::Muted)
15771                        .size(ButtonSize::Compact)
15772                        .style(ButtonStyle::Transparent)
15773                        .visible_on_hover(group_id.clone())
15774                        .on_click(move |_click, window, cx| {
15775                            window.dispatch_action(Box::new(Cancel), cx)
15776                        })
15777                        .tooltip(|window, cx| {
15778                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15779                        })
15780                }))
15781            })
15782            .child(
15783                IconButton::new("copy-block", IconName::Copy)
15784                    .icon_color(Color::Muted)
15785                    .size(ButtonSize::Compact)
15786                    .style(ButtonStyle::Transparent)
15787                    .visible_on_hover(group_id.clone())
15788                    .on_click({
15789                        let message = diagnostic.message.clone();
15790                        move |_click, _, cx| {
15791                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15792                        }
15793                    })
15794                    .tooltip(Tooltip::text("Copy diagnostic message")),
15795            )
15796        };
15797
15798        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15799            AvailableSpace::min_size(),
15800            cx.window,
15801            cx.app,
15802        );
15803
15804        h_flex()
15805            .id(cx.block_id)
15806            .group(group_id.clone())
15807            .relative()
15808            .size_full()
15809            .block_mouse_down()
15810            .pl(cx.gutter_dimensions.width)
15811            .w(cx.max_width - cx.gutter_dimensions.full_width())
15812            .child(
15813                div()
15814                    .flex()
15815                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15816                    .flex_shrink(),
15817            )
15818            .child(buttons(&diagnostic))
15819            .child(div().flex().flex_shrink_0().child(
15820                StyledText::new(text_without_backticks.clone()).with_highlights(
15821                    &text_style,
15822                    code_ranges.iter().map(|range| {
15823                        (
15824                            range.clone(),
15825                            HighlightStyle {
15826                                font_weight: Some(FontWeight::BOLD),
15827                                ..Default::default()
15828                            },
15829                        )
15830                    }),
15831                ),
15832            ))
15833            .into_any_element()
15834    })
15835}
15836
15837fn inline_completion_edit_text(
15838    current_snapshot: &BufferSnapshot,
15839    edits: &[(Range<Anchor>, String)],
15840    edit_preview: &EditPreview,
15841    include_deletions: bool,
15842    cx: &App,
15843) -> Option<HighlightedEdits> {
15844    let edits = edits
15845        .iter()
15846        .map(|(anchor, text)| {
15847            (
15848                anchor.start.text_anchor..anchor.end.text_anchor,
15849                text.clone(),
15850            )
15851        })
15852        .collect::<Vec<_>>();
15853
15854    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15855}
15856
15857pub fn highlight_diagnostic_message(
15858    diagnostic: &Diagnostic,
15859    mut max_message_rows: Option<u8>,
15860) -> (SharedString, Vec<Range<usize>>) {
15861    let mut text_without_backticks = String::new();
15862    let mut code_ranges = Vec::new();
15863
15864    if let Some(source) = &diagnostic.source {
15865        text_without_backticks.push_str(source);
15866        code_ranges.push(0..source.len());
15867        text_without_backticks.push_str(": ");
15868    }
15869
15870    let mut prev_offset = 0;
15871    let mut in_code_block = false;
15872    let has_row_limit = max_message_rows.is_some();
15873    let mut newline_indices = diagnostic
15874        .message
15875        .match_indices('\n')
15876        .filter(|_| has_row_limit)
15877        .map(|(ix, _)| ix)
15878        .fuse()
15879        .peekable();
15880
15881    for (quote_ix, _) in diagnostic
15882        .message
15883        .match_indices('`')
15884        .chain([(diagnostic.message.len(), "")])
15885    {
15886        let mut first_newline_ix = None;
15887        let mut last_newline_ix = None;
15888        while let Some(newline_ix) = newline_indices.peek() {
15889            if *newline_ix < quote_ix {
15890                if first_newline_ix.is_none() {
15891                    first_newline_ix = Some(*newline_ix);
15892                }
15893                last_newline_ix = Some(*newline_ix);
15894
15895                if let Some(rows_left) = &mut max_message_rows {
15896                    if *rows_left == 0 {
15897                        break;
15898                    } else {
15899                        *rows_left -= 1;
15900                    }
15901                }
15902                let _ = newline_indices.next();
15903            } else {
15904                break;
15905            }
15906        }
15907        let prev_len = text_without_backticks.len();
15908        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15909        text_without_backticks.push_str(new_text);
15910        if in_code_block {
15911            code_ranges.push(prev_len..text_without_backticks.len());
15912        }
15913        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15914        in_code_block = !in_code_block;
15915        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15916            text_without_backticks.push_str("...");
15917            break;
15918        }
15919    }
15920
15921    (text_without_backticks.into(), code_ranges)
15922}
15923
15924fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15925    match severity {
15926        DiagnosticSeverity::ERROR => colors.error,
15927        DiagnosticSeverity::WARNING => colors.warning,
15928        DiagnosticSeverity::INFORMATION => colors.info,
15929        DiagnosticSeverity::HINT => colors.info,
15930        _ => colors.ignored,
15931    }
15932}
15933
15934pub fn styled_runs_for_code_label<'a>(
15935    label: &'a CodeLabel,
15936    syntax_theme: &'a theme::SyntaxTheme,
15937) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15938    let fade_out = HighlightStyle {
15939        fade_out: Some(0.35),
15940        ..Default::default()
15941    };
15942
15943    let mut prev_end = label.filter_range.end;
15944    label
15945        .runs
15946        .iter()
15947        .enumerate()
15948        .flat_map(move |(ix, (range, highlight_id))| {
15949            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15950                style
15951            } else {
15952                return Default::default();
15953            };
15954            let mut muted_style = style;
15955            muted_style.highlight(fade_out);
15956
15957            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15958            if range.start >= label.filter_range.end {
15959                if range.start > prev_end {
15960                    runs.push((prev_end..range.start, fade_out));
15961                }
15962                runs.push((range.clone(), muted_style));
15963            } else if range.end <= label.filter_range.end {
15964                runs.push((range.clone(), style));
15965            } else {
15966                runs.push((range.start..label.filter_range.end, style));
15967                runs.push((label.filter_range.end..range.end, muted_style));
15968            }
15969            prev_end = cmp::max(prev_end, range.end);
15970
15971            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15972                runs.push((prev_end..label.text.len(), fade_out));
15973            }
15974
15975            runs
15976        })
15977}
15978
15979pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15980    let mut prev_index = 0;
15981    let mut prev_codepoint: Option<char> = None;
15982    text.char_indices()
15983        .chain([(text.len(), '\0')])
15984        .filter_map(move |(index, codepoint)| {
15985            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15986            let is_boundary = index == text.len()
15987                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15988                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15989            if is_boundary {
15990                let chunk = &text[prev_index..index];
15991                prev_index = index;
15992                Some(chunk)
15993            } else {
15994                None
15995            }
15996        })
15997}
15998
15999pub trait RangeToAnchorExt: Sized {
16000    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16001
16002    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16003        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16004        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16005    }
16006}
16007
16008impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16009    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16010        let start_offset = self.start.to_offset(snapshot);
16011        let end_offset = self.end.to_offset(snapshot);
16012        if start_offset == end_offset {
16013            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16014        } else {
16015            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16016        }
16017    }
16018}
16019
16020pub trait RowExt {
16021    fn as_f32(&self) -> f32;
16022
16023    fn next_row(&self) -> Self;
16024
16025    fn previous_row(&self) -> Self;
16026
16027    fn minus(&self, other: Self) -> u32;
16028}
16029
16030impl RowExt for DisplayRow {
16031    fn as_f32(&self) -> f32 {
16032        self.0 as f32
16033    }
16034
16035    fn next_row(&self) -> Self {
16036        Self(self.0 + 1)
16037    }
16038
16039    fn previous_row(&self) -> Self {
16040        Self(self.0.saturating_sub(1))
16041    }
16042
16043    fn minus(&self, other: Self) -> u32 {
16044        self.0 - other.0
16045    }
16046}
16047
16048impl RowExt for MultiBufferRow {
16049    fn as_f32(&self) -> f32 {
16050        self.0 as f32
16051    }
16052
16053    fn next_row(&self) -> Self {
16054        Self(self.0 + 1)
16055    }
16056
16057    fn previous_row(&self) -> Self {
16058        Self(self.0.saturating_sub(1))
16059    }
16060
16061    fn minus(&self, other: Self) -> u32 {
16062        self.0 - other.0
16063    }
16064}
16065
16066trait RowRangeExt {
16067    type Row;
16068
16069    fn len(&self) -> usize;
16070
16071    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16072}
16073
16074impl RowRangeExt for Range<MultiBufferRow> {
16075    type Row = MultiBufferRow;
16076
16077    fn len(&self) -> usize {
16078        (self.end.0 - self.start.0) as usize
16079    }
16080
16081    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16082        (self.start.0..self.end.0).map(MultiBufferRow)
16083    }
16084}
16085
16086impl RowRangeExt for Range<DisplayRow> {
16087    type Row = DisplayRow;
16088
16089    fn len(&self) -> usize {
16090        (self.end.0 - self.start.0) as usize
16091    }
16092
16093    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16094        (self.start.0..self.end.0).map(DisplayRow)
16095    }
16096}
16097
16098/// If select range has more than one line, we
16099/// just point the cursor to range.start.
16100fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16101    if range.start.row == range.end.row {
16102        range
16103    } else {
16104        range.start..range.start
16105    }
16106}
16107pub struct KillRing(ClipboardItem);
16108impl Global for KillRing {}
16109
16110const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16111
16112fn all_edits_insertions_or_deletions(
16113    edits: &Vec<(Range<Anchor>, String)>,
16114    snapshot: &MultiBufferSnapshot,
16115) -> bool {
16116    let mut all_insertions = true;
16117    let mut all_deletions = true;
16118
16119    for (range, new_text) in edits.iter() {
16120        let range_is_empty = range.to_offset(&snapshot).is_empty();
16121        let text_is_empty = new_text.is_empty();
16122
16123        if range_is_empty != text_is_empty {
16124            if range_is_empty {
16125                all_deletions = false;
16126            } else {
16127                all_insertions = false;
16128            }
16129        } else {
16130            return false;
16131        }
16132
16133        if !all_insertions && !all_deletions {
16134            return false;
16135        }
16136    }
16137    all_insertions || all_deletions
16138}