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        let reversed = self.selections.oldest::<usize>(cx).reversed;
 8831
 8832        for selection in new_selections.iter_mut() {
 8833            selection.reversed = reversed;
 8834        }
 8835
 8836        select_next_state.done = true;
 8837        self.unfold_ranges(
 8838            &new_selections
 8839                .iter()
 8840                .map(|selection| selection.range())
 8841                .collect::<Vec<_>>(),
 8842            false,
 8843            false,
 8844            cx,
 8845        );
 8846        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 8847            selections.select(new_selections)
 8848        });
 8849
 8850        Ok(())
 8851    }
 8852
 8853    pub fn select_next(
 8854        &mut self,
 8855        action: &SelectNext,
 8856        window: &mut Window,
 8857        cx: &mut Context<Self>,
 8858    ) -> Result<()> {
 8859        self.push_to_selection_history();
 8860        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8861        self.select_next_match_internal(
 8862            &display_map,
 8863            action.replace_newest,
 8864            Some(Autoscroll::newest()),
 8865            window,
 8866            cx,
 8867        )?;
 8868        Ok(())
 8869    }
 8870
 8871    pub fn select_previous(
 8872        &mut self,
 8873        action: &SelectPrevious,
 8874        window: &mut Window,
 8875        cx: &mut Context<Self>,
 8876    ) -> Result<()> {
 8877        self.push_to_selection_history();
 8878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8879        let buffer = &display_map.buffer_snapshot;
 8880        let mut selections = self.selections.all::<usize>(cx);
 8881        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8882            let query = &select_prev_state.query;
 8883            if !select_prev_state.done {
 8884                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8885                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8886                let mut next_selected_range = None;
 8887                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8888                let bytes_before_last_selection =
 8889                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8890                let bytes_after_first_selection =
 8891                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8892                let query_matches = query
 8893                    .stream_find_iter(bytes_before_last_selection)
 8894                    .map(|result| (last_selection.start, result))
 8895                    .chain(
 8896                        query
 8897                            .stream_find_iter(bytes_after_first_selection)
 8898                            .map(|result| (buffer.len(), result)),
 8899                    );
 8900                for (end_offset, query_match) in query_matches {
 8901                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8902                    let offset_range =
 8903                        end_offset - query_match.end()..end_offset - query_match.start();
 8904                    let display_range = offset_range.start.to_display_point(&display_map)
 8905                        ..offset_range.end.to_display_point(&display_map);
 8906
 8907                    if !select_prev_state.wordwise
 8908                        || (!movement::is_inside_word(&display_map, display_range.start)
 8909                            && !movement::is_inside_word(&display_map, display_range.end))
 8910                    {
 8911                        next_selected_range = Some(offset_range);
 8912                        break;
 8913                    }
 8914                }
 8915
 8916                if let Some(next_selected_range) = next_selected_range {
 8917                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8918                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 8919                        if action.replace_newest {
 8920                            s.delete(s.newest_anchor().id);
 8921                        }
 8922                        s.insert_range(next_selected_range);
 8923                    });
 8924                } else {
 8925                    select_prev_state.done = true;
 8926                }
 8927            }
 8928
 8929            self.select_prev_state = Some(select_prev_state);
 8930        } else {
 8931            let mut only_carets = true;
 8932            let mut same_text_selected = true;
 8933            let mut selected_text = None;
 8934
 8935            let mut selections_iter = selections.iter().peekable();
 8936            while let Some(selection) = selections_iter.next() {
 8937                if selection.start != selection.end {
 8938                    only_carets = false;
 8939                }
 8940
 8941                if same_text_selected {
 8942                    if selected_text.is_none() {
 8943                        selected_text =
 8944                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8945                    }
 8946
 8947                    if let Some(next_selection) = selections_iter.peek() {
 8948                        if next_selection.range().len() == selection.range().len() {
 8949                            let next_selected_text = buffer
 8950                                .text_for_range(next_selection.range())
 8951                                .collect::<String>();
 8952                            if Some(next_selected_text) != selected_text {
 8953                                same_text_selected = false;
 8954                                selected_text = None;
 8955                            }
 8956                        } else {
 8957                            same_text_selected = false;
 8958                            selected_text = None;
 8959                        }
 8960                    }
 8961                }
 8962            }
 8963
 8964            if only_carets {
 8965                for selection in &mut selections {
 8966                    let word_range = movement::surrounding_word(
 8967                        &display_map,
 8968                        selection.start.to_display_point(&display_map),
 8969                    );
 8970                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8971                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8972                    selection.goal = SelectionGoal::None;
 8973                    selection.reversed = false;
 8974                }
 8975                if selections.len() == 1 {
 8976                    let selection = selections
 8977                        .last()
 8978                        .expect("ensured that there's only one selection");
 8979                    let query = buffer
 8980                        .text_for_range(selection.start..selection.end)
 8981                        .collect::<String>();
 8982                    let is_empty = query.is_empty();
 8983                    let select_state = SelectNextState {
 8984                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8985                        wordwise: true,
 8986                        done: is_empty,
 8987                    };
 8988                    self.select_prev_state = Some(select_state);
 8989                } else {
 8990                    self.select_prev_state = None;
 8991                }
 8992
 8993                self.unfold_ranges(
 8994                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8995                    false,
 8996                    true,
 8997                    cx,
 8998                );
 8999                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9000                    s.select(selections);
 9001                });
 9002            } else if let Some(selected_text) = selected_text {
 9003                self.select_prev_state = Some(SelectNextState {
 9004                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9005                    wordwise: false,
 9006                    done: false,
 9007                });
 9008                self.select_previous(action, window, cx)?;
 9009            }
 9010        }
 9011        Ok(())
 9012    }
 9013
 9014    pub fn toggle_comments(
 9015        &mut self,
 9016        action: &ToggleComments,
 9017        window: &mut Window,
 9018        cx: &mut Context<Self>,
 9019    ) {
 9020        if self.read_only(cx) {
 9021            return;
 9022        }
 9023        let text_layout_details = &self.text_layout_details(window);
 9024        self.transact(window, cx, |this, window, cx| {
 9025            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9026            let mut edits = Vec::new();
 9027            let mut selection_edit_ranges = Vec::new();
 9028            let mut last_toggled_row = None;
 9029            let snapshot = this.buffer.read(cx).read(cx);
 9030            let empty_str: Arc<str> = Arc::default();
 9031            let mut suffixes_inserted = Vec::new();
 9032            let ignore_indent = action.ignore_indent;
 9033
 9034            fn comment_prefix_range(
 9035                snapshot: &MultiBufferSnapshot,
 9036                row: MultiBufferRow,
 9037                comment_prefix: &str,
 9038                comment_prefix_whitespace: &str,
 9039                ignore_indent: bool,
 9040            ) -> Range<Point> {
 9041                let indent_size = if ignore_indent {
 9042                    0
 9043                } else {
 9044                    snapshot.indent_size_for_line(row).len
 9045                };
 9046
 9047                let start = Point::new(row.0, indent_size);
 9048
 9049                let mut line_bytes = snapshot
 9050                    .bytes_in_range(start..snapshot.max_point())
 9051                    .flatten()
 9052                    .copied();
 9053
 9054                // If this line currently begins with the line comment prefix, then record
 9055                // the range containing the prefix.
 9056                if line_bytes
 9057                    .by_ref()
 9058                    .take(comment_prefix.len())
 9059                    .eq(comment_prefix.bytes())
 9060                {
 9061                    // Include any whitespace that matches the comment prefix.
 9062                    let matching_whitespace_len = line_bytes
 9063                        .zip(comment_prefix_whitespace.bytes())
 9064                        .take_while(|(a, b)| a == b)
 9065                        .count() as u32;
 9066                    let end = Point::new(
 9067                        start.row,
 9068                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9069                    );
 9070                    start..end
 9071                } else {
 9072                    start..start
 9073                }
 9074            }
 9075
 9076            fn comment_suffix_range(
 9077                snapshot: &MultiBufferSnapshot,
 9078                row: MultiBufferRow,
 9079                comment_suffix: &str,
 9080                comment_suffix_has_leading_space: bool,
 9081            ) -> Range<Point> {
 9082                let end = Point::new(row.0, snapshot.line_len(row));
 9083                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9084
 9085                let mut line_end_bytes = snapshot
 9086                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9087                    .flatten()
 9088                    .copied();
 9089
 9090                let leading_space_len = if suffix_start_column > 0
 9091                    && line_end_bytes.next() == Some(b' ')
 9092                    && comment_suffix_has_leading_space
 9093                {
 9094                    1
 9095                } else {
 9096                    0
 9097                };
 9098
 9099                // If this line currently begins with the line comment prefix, then record
 9100                // the range containing the prefix.
 9101                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9102                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9103                    start..end
 9104                } else {
 9105                    end..end
 9106                }
 9107            }
 9108
 9109            // TODO: Handle selections that cross excerpts
 9110            for selection in &mut selections {
 9111                let start_column = snapshot
 9112                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9113                    .len;
 9114                let language = if let Some(language) =
 9115                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9116                {
 9117                    language
 9118                } else {
 9119                    continue;
 9120                };
 9121
 9122                selection_edit_ranges.clear();
 9123
 9124                // If multiple selections contain a given row, avoid processing that
 9125                // row more than once.
 9126                let mut start_row = MultiBufferRow(selection.start.row);
 9127                if last_toggled_row == Some(start_row) {
 9128                    start_row = start_row.next_row();
 9129                }
 9130                let end_row =
 9131                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9132                        MultiBufferRow(selection.end.row - 1)
 9133                    } else {
 9134                        MultiBufferRow(selection.end.row)
 9135                    };
 9136                last_toggled_row = Some(end_row);
 9137
 9138                if start_row > end_row {
 9139                    continue;
 9140                }
 9141
 9142                // If the language has line comments, toggle those.
 9143                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9144
 9145                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9146                if ignore_indent {
 9147                    full_comment_prefixes = full_comment_prefixes
 9148                        .into_iter()
 9149                        .map(|s| Arc::from(s.trim_end()))
 9150                        .collect();
 9151                }
 9152
 9153                if !full_comment_prefixes.is_empty() {
 9154                    let first_prefix = full_comment_prefixes
 9155                        .first()
 9156                        .expect("prefixes is non-empty");
 9157                    let prefix_trimmed_lengths = full_comment_prefixes
 9158                        .iter()
 9159                        .map(|p| p.trim_end_matches(' ').len())
 9160                        .collect::<SmallVec<[usize; 4]>>();
 9161
 9162                    let mut all_selection_lines_are_comments = true;
 9163
 9164                    for row in start_row.0..=end_row.0 {
 9165                        let row = MultiBufferRow(row);
 9166                        if start_row < end_row && snapshot.is_line_blank(row) {
 9167                            continue;
 9168                        }
 9169
 9170                        let prefix_range = full_comment_prefixes
 9171                            .iter()
 9172                            .zip(prefix_trimmed_lengths.iter().copied())
 9173                            .map(|(prefix, trimmed_prefix_len)| {
 9174                                comment_prefix_range(
 9175                                    snapshot.deref(),
 9176                                    row,
 9177                                    &prefix[..trimmed_prefix_len],
 9178                                    &prefix[trimmed_prefix_len..],
 9179                                    ignore_indent,
 9180                                )
 9181                            })
 9182                            .max_by_key(|range| range.end.column - range.start.column)
 9183                            .expect("prefixes is non-empty");
 9184
 9185                        if prefix_range.is_empty() {
 9186                            all_selection_lines_are_comments = false;
 9187                        }
 9188
 9189                        selection_edit_ranges.push(prefix_range);
 9190                    }
 9191
 9192                    if all_selection_lines_are_comments {
 9193                        edits.extend(
 9194                            selection_edit_ranges
 9195                                .iter()
 9196                                .cloned()
 9197                                .map(|range| (range, empty_str.clone())),
 9198                        );
 9199                    } else {
 9200                        let min_column = selection_edit_ranges
 9201                            .iter()
 9202                            .map(|range| range.start.column)
 9203                            .min()
 9204                            .unwrap_or(0);
 9205                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9206                            let position = Point::new(range.start.row, min_column);
 9207                            (position..position, first_prefix.clone())
 9208                        }));
 9209                    }
 9210                } else if let Some((full_comment_prefix, comment_suffix)) =
 9211                    language.block_comment_delimiters()
 9212                {
 9213                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9214                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9215                    let prefix_range = comment_prefix_range(
 9216                        snapshot.deref(),
 9217                        start_row,
 9218                        comment_prefix,
 9219                        comment_prefix_whitespace,
 9220                        ignore_indent,
 9221                    );
 9222                    let suffix_range = comment_suffix_range(
 9223                        snapshot.deref(),
 9224                        end_row,
 9225                        comment_suffix.trim_start_matches(' '),
 9226                        comment_suffix.starts_with(' '),
 9227                    );
 9228
 9229                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9230                        edits.push((
 9231                            prefix_range.start..prefix_range.start,
 9232                            full_comment_prefix.clone(),
 9233                        ));
 9234                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9235                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9236                    } else {
 9237                        edits.push((prefix_range, empty_str.clone()));
 9238                        edits.push((suffix_range, empty_str.clone()));
 9239                    }
 9240                } else {
 9241                    continue;
 9242                }
 9243            }
 9244
 9245            drop(snapshot);
 9246            this.buffer.update(cx, |buffer, cx| {
 9247                buffer.edit(edits, None, cx);
 9248            });
 9249
 9250            // Adjust selections so that they end before any comment suffixes that
 9251            // were inserted.
 9252            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9253            let mut selections = this.selections.all::<Point>(cx);
 9254            let snapshot = this.buffer.read(cx).read(cx);
 9255            for selection in &mut selections {
 9256                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9257                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9258                        Ordering::Less => {
 9259                            suffixes_inserted.next();
 9260                            continue;
 9261                        }
 9262                        Ordering::Greater => break,
 9263                        Ordering::Equal => {
 9264                            if selection.end.column == snapshot.line_len(row) {
 9265                                if selection.is_empty() {
 9266                                    selection.start.column -= suffix_len as u32;
 9267                                }
 9268                                selection.end.column -= suffix_len as u32;
 9269                            }
 9270                            break;
 9271                        }
 9272                    }
 9273                }
 9274            }
 9275
 9276            drop(snapshot);
 9277            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9278                s.select(selections)
 9279            });
 9280
 9281            let selections = this.selections.all::<Point>(cx);
 9282            let selections_on_single_row = selections.windows(2).all(|selections| {
 9283                selections[0].start.row == selections[1].start.row
 9284                    && selections[0].end.row == selections[1].end.row
 9285                    && selections[0].start.row == selections[0].end.row
 9286            });
 9287            let selections_selecting = selections
 9288                .iter()
 9289                .any(|selection| selection.start != selection.end);
 9290            let advance_downwards = action.advance_downwards
 9291                && selections_on_single_row
 9292                && !selections_selecting
 9293                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9294
 9295            if advance_downwards {
 9296                let snapshot = this.buffer.read(cx).snapshot(cx);
 9297
 9298                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9299                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9300                        let mut point = display_point.to_point(display_snapshot);
 9301                        point.row += 1;
 9302                        point = snapshot.clip_point(point, Bias::Left);
 9303                        let display_point = point.to_display_point(display_snapshot);
 9304                        let goal = SelectionGoal::HorizontalPosition(
 9305                            display_snapshot
 9306                                .x_for_display_point(display_point, text_layout_details)
 9307                                .into(),
 9308                        );
 9309                        (display_point, goal)
 9310                    })
 9311                });
 9312            }
 9313        });
 9314    }
 9315
 9316    pub fn select_enclosing_symbol(
 9317        &mut self,
 9318        _: &SelectEnclosingSymbol,
 9319        window: &mut Window,
 9320        cx: &mut Context<Self>,
 9321    ) {
 9322        let buffer = self.buffer.read(cx).snapshot(cx);
 9323        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9324
 9325        fn update_selection(
 9326            selection: &Selection<usize>,
 9327            buffer_snap: &MultiBufferSnapshot,
 9328        ) -> Option<Selection<usize>> {
 9329            let cursor = selection.head();
 9330            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9331            for symbol in symbols.iter().rev() {
 9332                let start = symbol.range.start.to_offset(buffer_snap);
 9333                let end = symbol.range.end.to_offset(buffer_snap);
 9334                let new_range = start..end;
 9335                if start < selection.start || end > selection.end {
 9336                    return Some(Selection {
 9337                        id: selection.id,
 9338                        start: new_range.start,
 9339                        end: new_range.end,
 9340                        goal: SelectionGoal::None,
 9341                        reversed: selection.reversed,
 9342                    });
 9343                }
 9344            }
 9345            None
 9346        }
 9347
 9348        let mut selected_larger_symbol = false;
 9349        let new_selections = old_selections
 9350            .iter()
 9351            .map(|selection| match update_selection(selection, &buffer) {
 9352                Some(new_selection) => {
 9353                    if new_selection.range() != selection.range() {
 9354                        selected_larger_symbol = true;
 9355                    }
 9356                    new_selection
 9357                }
 9358                None => selection.clone(),
 9359            })
 9360            .collect::<Vec<_>>();
 9361
 9362        if selected_larger_symbol {
 9363            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9364                s.select(new_selections);
 9365            });
 9366        }
 9367    }
 9368
 9369    pub fn select_larger_syntax_node(
 9370        &mut self,
 9371        _: &SelectLargerSyntaxNode,
 9372        window: &mut Window,
 9373        cx: &mut Context<Self>,
 9374    ) {
 9375        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9376        let buffer = self.buffer.read(cx).snapshot(cx);
 9377        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9378
 9379        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9380        let mut selected_larger_node = false;
 9381        let new_selections = old_selections
 9382            .iter()
 9383            .map(|selection| {
 9384                let old_range = selection.start..selection.end;
 9385                let mut new_range = old_range.clone();
 9386                let mut new_node = None;
 9387                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9388                {
 9389                    new_node = Some(node);
 9390                    new_range = containing_range;
 9391                    if !display_map.intersects_fold(new_range.start)
 9392                        && !display_map.intersects_fold(new_range.end)
 9393                    {
 9394                        break;
 9395                    }
 9396                }
 9397
 9398                if let Some(node) = new_node {
 9399                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9400                    // nodes. Parent and grandparent are also logged because this operation will not
 9401                    // visit nodes that have the same range as their parent.
 9402                    log::info!("Node: {node:?}");
 9403                    let parent = node.parent();
 9404                    log::info!("Parent: {parent:?}");
 9405                    let grandparent = parent.and_then(|x| x.parent());
 9406                    log::info!("Grandparent: {grandparent:?}");
 9407                }
 9408
 9409                selected_larger_node |= new_range != old_range;
 9410                Selection {
 9411                    id: selection.id,
 9412                    start: new_range.start,
 9413                    end: new_range.end,
 9414                    goal: SelectionGoal::None,
 9415                    reversed: selection.reversed,
 9416                }
 9417            })
 9418            .collect::<Vec<_>>();
 9419
 9420        if selected_larger_node {
 9421            stack.push(old_selections);
 9422            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9423                s.select(new_selections);
 9424            });
 9425        }
 9426        self.select_larger_syntax_node_stack = stack;
 9427    }
 9428
 9429    pub fn select_smaller_syntax_node(
 9430        &mut self,
 9431        _: &SelectSmallerSyntaxNode,
 9432        window: &mut Window,
 9433        cx: &mut Context<Self>,
 9434    ) {
 9435        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9436        if let Some(selections) = stack.pop() {
 9437            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9438                s.select(selections.to_vec());
 9439            });
 9440        }
 9441        self.select_larger_syntax_node_stack = stack;
 9442    }
 9443
 9444    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9445        if !EditorSettings::get_global(cx).gutter.runnables {
 9446            self.clear_tasks();
 9447            return Task::ready(());
 9448        }
 9449        let project = self.project.as_ref().map(Entity::downgrade);
 9450        cx.spawn_in(window, |this, mut cx| async move {
 9451            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9452            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9453                return;
 9454            };
 9455            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9456                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9457            }) else {
 9458                return;
 9459            };
 9460
 9461            let hide_runnables = project
 9462                .update(&mut cx, |project, cx| {
 9463                    // Do not display any test indicators in non-dev server remote projects.
 9464                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9465                })
 9466                .unwrap_or(true);
 9467            if hide_runnables {
 9468                return;
 9469            }
 9470            let new_rows =
 9471                cx.background_executor()
 9472                    .spawn({
 9473                        let snapshot = display_snapshot.clone();
 9474                        async move {
 9475                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9476                        }
 9477                    })
 9478                    .await;
 9479
 9480            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9481            this.update(&mut cx, |this, _| {
 9482                this.clear_tasks();
 9483                for (key, value) in rows {
 9484                    this.insert_tasks(key, value);
 9485                }
 9486            })
 9487            .ok();
 9488        })
 9489    }
 9490    fn fetch_runnable_ranges(
 9491        snapshot: &DisplaySnapshot,
 9492        range: Range<Anchor>,
 9493    ) -> Vec<language::RunnableRange> {
 9494        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9495    }
 9496
 9497    fn runnable_rows(
 9498        project: Entity<Project>,
 9499        snapshot: DisplaySnapshot,
 9500        runnable_ranges: Vec<RunnableRange>,
 9501        mut cx: AsyncWindowContext,
 9502    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9503        runnable_ranges
 9504            .into_iter()
 9505            .filter_map(|mut runnable| {
 9506                let tasks = cx
 9507                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9508                    .ok()?;
 9509                if tasks.is_empty() {
 9510                    return None;
 9511                }
 9512
 9513                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9514
 9515                let row = snapshot
 9516                    .buffer_snapshot
 9517                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9518                    .1
 9519                    .start
 9520                    .row;
 9521
 9522                let context_range =
 9523                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9524                Some((
 9525                    (runnable.buffer_id, row),
 9526                    RunnableTasks {
 9527                        templates: tasks,
 9528                        offset: MultiBufferOffset(runnable.run_range.start),
 9529                        context_range,
 9530                        column: point.column,
 9531                        extra_variables: runnable.extra_captures,
 9532                    },
 9533                ))
 9534            })
 9535            .collect()
 9536    }
 9537
 9538    fn templates_with_tags(
 9539        project: &Entity<Project>,
 9540        runnable: &mut Runnable,
 9541        cx: &mut App,
 9542    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9543        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9544            let (worktree_id, file) = project
 9545                .buffer_for_id(runnable.buffer, cx)
 9546                .and_then(|buffer| buffer.read(cx).file())
 9547                .map(|file| (file.worktree_id(cx), file.clone()))
 9548                .unzip();
 9549
 9550            (
 9551                project.task_store().read(cx).task_inventory().cloned(),
 9552                worktree_id,
 9553                file,
 9554            )
 9555        });
 9556
 9557        let tags = mem::take(&mut runnable.tags);
 9558        let mut tags: Vec<_> = tags
 9559            .into_iter()
 9560            .flat_map(|tag| {
 9561                let tag = tag.0.clone();
 9562                inventory
 9563                    .as_ref()
 9564                    .into_iter()
 9565                    .flat_map(|inventory| {
 9566                        inventory.read(cx).list_tasks(
 9567                            file.clone(),
 9568                            Some(runnable.language.clone()),
 9569                            worktree_id,
 9570                            cx,
 9571                        )
 9572                    })
 9573                    .filter(move |(_, template)| {
 9574                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9575                    })
 9576            })
 9577            .sorted_by_key(|(kind, _)| kind.to_owned())
 9578            .collect();
 9579        if let Some((leading_tag_source, _)) = tags.first() {
 9580            // Strongest source wins; if we have worktree tag binding, prefer that to
 9581            // global and language bindings;
 9582            // if we have a global binding, prefer that to language binding.
 9583            let first_mismatch = tags
 9584                .iter()
 9585                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9586            if let Some(index) = first_mismatch {
 9587                tags.truncate(index);
 9588            }
 9589        }
 9590
 9591        tags
 9592    }
 9593
 9594    pub fn move_to_enclosing_bracket(
 9595        &mut self,
 9596        _: &MoveToEnclosingBracket,
 9597        window: &mut Window,
 9598        cx: &mut Context<Self>,
 9599    ) {
 9600        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9601            s.move_offsets_with(|snapshot, selection| {
 9602                let Some(enclosing_bracket_ranges) =
 9603                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9604                else {
 9605                    return;
 9606                };
 9607
 9608                let mut best_length = usize::MAX;
 9609                let mut best_inside = false;
 9610                let mut best_in_bracket_range = false;
 9611                let mut best_destination = None;
 9612                for (open, close) in enclosing_bracket_ranges {
 9613                    let close = close.to_inclusive();
 9614                    let length = close.end() - open.start;
 9615                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9616                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9617                        || close.contains(&selection.head());
 9618
 9619                    // If best is next to a bracket and current isn't, skip
 9620                    if !in_bracket_range && best_in_bracket_range {
 9621                        continue;
 9622                    }
 9623
 9624                    // Prefer smaller lengths unless best is inside and current isn't
 9625                    if length > best_length && (best_inside || !inside) {
 9626                        continue;
 9627                    }
 9628
 9629                    best_length = length;
 9630                    best_inside = inside;
 9631                    best_in_bracket_range = in_bracket_range;
 9632                    best_destination = Some(
 9633                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9634                            if inside {
 9635                                open.end
 9636                            } else {
 9637                                open.start
 9638                            }
 9639                        } else if inside {
 9640                            *close.start()
 9641                        } else {
 9642                            *close.end()
 9643                        },
 9644                    );
 9645                }
 9646
 9647                if let Some(destination) = best_destination {
 9648                    selection.collapse_to(destination, SelectionGoal::None);
 9649                }
 9650            })
 9651        });
 9652    }
 9653
 9654    pub fn undo_selection(
 9655        &mut self,
 9656        _: &UndoSelection,
 9657        window: &mut Window,
 9658        cx: &mut Context<Self>,
 9659    ) {
 9660        self.end_selection(window, cx);
 9661        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9662        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9663            self.change_selections(None, window, cx, |s| {
 9664                s.select_anchors(entry.selections.to_vec())
 9665            });
 9666            self.select_next_state = entry.select_next_state;
 9667            self.select_prev_state = entry.select_prev_state;
 9668            self.add_selections_state = entry.add_selections_state;
 9669            self.request_autoscroll(Autoscroll::newest(), cx);
 9670        }
 9671        self.selection_history.mode = SelectionHistoryMode::Normal;
 9672    }
 9673
 9674    pub fn redo_selection(
 9675        &mut self,
 9676        _: &RedoSelection,
 9677        window: &mut Window,
 9678        cx: &mut Context<Self>,
 9679    ) {
 9680        self.end_selection(window, cx);
 9681        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9682        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9683            self.change_selections(None, window, cx, |s| {
 9684                s.select_anchors(entry.selections.to_vec())
 9685            });
 9686            self.select_next_state = entry.select_next_state;
 9687            self.select_prev_state = entry.select_prev_state;
 9688            self.add_selections_state = entry.add_selections_state;
 9689            self.request_autoscroll(Autoscroll::newest(), cx);
 9690        }
 9691        self.selection_history.mode = SelectionHistoryMode::Normal;
 9692    }
 9693
 9694    pub fn expand_excerpts(
 9695        &mut self,
 9696        action: &ExpandExcerpts,
 9697        _: &mut Window,
 9698        cx: &mut Context<Self>,
 9699    ) {
 9700        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9701    }
 9702
 9703    pub fn expand_excerpts_down(
 9704        &mut self,
 9705        action: &ExpandExcerptsDown,
 9706        _: &mut Window,
 9707        cx: &mut Context<Self>,
 9708    ) {
 9709        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9710    }
 9711
 9712    pub fn expand_excerpts_up(
 9713        &mut self,
 9714        action: &ExpandExcerptsUp,
 9715        _: &mut Window,
 9716        cx: &mut Context<Self>,
 9717    ) {
 9718        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9719    }
 9720
 9721    pub fn expand_excerpts_for_direction(
 9722        &mut self,
 9723        lines: u32,
 9724        direction: ExpandExcerptDirection,
 9725
 9726        cx: &mut Context<Self>,
 9727    ) {
 9728        let selections = self.selections.disjoint_anchors();
 9729
 9730        let lines = if lines == 0 {
 9731            EditorSettings::get_global(cx).expand_excerpt_lines
 9732        } else {
 9733            lines
 9734        };
 9735
 9736        self.buffer.update(cx, |buffer, cx| {
 9737            let snapshot = buffer.snapshot(cx);
 9738            let mut excerpt_ids = selections
 9739                .iter()
 9740                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
 9741                .collect::<Vec<_>>();
 9742            excerpt_ids.sort();
 9743            excerpt_ids.dedup();
 9744            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9745        })
 9746    }
 9747
 9748    pub fn expand_excerpt(
 9749        &mut self,
 9750        excerpt: ExcerptId,
 9751        direction: ExpandExcerptDirection,
 9752        cx: &mut Context<Self>,
 9753    ) {
 9754        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9755        self.buffer.update(cx, |buffer, cx| {
 9756            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9757        })
 9758    }
 9759
 9760    pub fn go_to_singleton_buffer_point(
 9761        &mut self,
 9762        point: Point,
 9763        window: &mut Window,
 9764        cx: &mut Context<Self>,
 9765    ) {
 9766        self.go_to_singleton_buffer_range(point..point, window, cx);
 9767    }
 9768
 9769    pub fn go_to_singleton_buffer_range(
 9770        &mut self,
 9771        range: Range<Point>,
 9772        window: &mut Window,
 9773        cx: &mut Context<Self>,
 9774    ) {
 9775        let multibuffer = self.buffer().read(cx);
 9776        let Some(buffer) = multibuffer.as_singleton() else {
 9777            return;
 9778        };
 9779        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
 9780            return;
 9781        };
 9782        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
 9783            return;
 9784        };
 9785        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 9786            s.select_anchor_ranges([start..end])
 9787        });
 9788    }
 9789
 9790    fn go_to_diagnostic(
 9791        &mut self,
 9792        _: &GoToDiagnostic,
 9793        window: &mut Window,
 9794        cx: &mut Context<Self>,
 9795    ) {
 9796        self.go_to_diagnostic_impl(Direction::Next, window, cx)
 9797    }
 9798
 9799    fn go_to_prev_diagnostic(
 9800        &mut self,
 9801        _: &GoToPrevDiagnostic,
 9802        window: &mut Window,
 9803        cx: &mut Context<Self>,
 9804    ) {
 9805        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
 9806    }
 9807
 9808    pub fn go_to_diagnostic_impl(
 9809        &mut self,
 9810        direction: Direction,
 9811        window: &mut Window,
 9812        cx: &mut Context<Self>,
 9813    ) {
 9814        let buffer = self.buffer.read(cx).snapshot(cx);
 9815        let selection = self.selections.newest::<usize>(cx);
 9816
 9817        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9818        if direction == Direction::Next {
 9819            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9820                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
 9821                    return;
 9822                };
 9823                self.activate_diagnostics(
 9824                    buffer_id,
 9825                    popover.local_diagnostic.diagnostic.group_id,
 9826                    window,
 9827                    cx,
 9828                );
 9829                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9830                    let primary_range_start = active_diagnostics.primary_range.start;
 9831                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9832                        let mut new_selection = s.newest_anchor().clone();
 9833                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9834                        s.select_anchors(vec![new_selection.clone()]);
 9835                    });
 9836                    self.refresh_inline_completion(false, true, window, cx);
 9837                }
 9838                return;
 9839            }
 9840        }
 9841
 9842        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9843            active_diagnostics
 9844                .primary_range
 9845                .to_offset(&buffer)
 9846                .to_inclusive()
 9847        });
 9848        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9849            if active_primary_range.contains(&selection.head()) {
 9850                *active_primary_range.start()
 9851            } else {
 9852                selection.head()
 9853            }
 9854        } else {
 9855            selection.head()
 9856        };
 9857        let snapshot = self.snapshot(window, cx);
 9858        loop {
 9859            let mut diagnostics;
 9860            if direction == Direction::Prev {
 9861                diagnostics = buffer
 9862                    .diagnostics_in_range::<_, usize>(0..search_start)
 9863                    .collect::<Vec<_>>();
 9864                diagnostics.reverse();
 9865            } else {
 9866                diagnostics = buffer
 9867                    .diagnostics_in_range::<_, usize>(search_start..buffer.len())
 9868                    .collect::<Vec<_>>();
 9869            };
 9870            let group = diagnostics
 9871                .into_iter()
 9872                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
 9873                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9874                // be sorted in a stable way
 9875                // skip until we are at current active diagnostic, if it exists
 9876                .skip_while(|entry| {
 9877                    let is_in_range = match direction {
 9878                        Direction::Prev => entry.range.end > search_start,
 9879                        Direction::Next => entry.range.start < search_start,
 9880                    };
 9881                    is_in_range
 9882                        && self
 9883                            .active_diagnostics
 9884                            .as_ref()
 9885                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9886                })
 9887                .find_map(|entry| {
 9888                    if entry.diagnostic.is_primary
 9889                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9890                        && entry.range.start != entry.range.end
 9891                        // if we match with the active diagnostic, skip it
 9892                        && Some(entry.diagnostic.group_id)
 9893                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9894                    {
 9895                        Some((entry.range, entry.diagnostic.group_id))
 9896                    } else {
 9897                        None
 9898                    }
 9899                });
 9900
 9901            if let Some((primary_range, group_id)) = group {
 9902                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
 9903                    return;
 9904                };
 9905                self.activate_diagnostics(buffer_id, group_id, window, cx);
 9906                if self.active_diagnostics.is_some() {
 9907                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9908                        s.select(vec![Selection {
 9909                            id: selection.id,
 9910                            start: primary_range.start,
 9911                            end: primary_range.start,
 9912                            reversed: false,
 9913                            goal: SelectionGoal::None,
 9914                        }]);
 9915                    });
 9916                    self.refresh_inline_completion(false, true, window, cx);
 9917                }
 9918                break;
 9919            } else {
 9920                // Cycle around to the start of the buffer, potentially moving back to the start of
 9921                // the currently active diagnostic.
 9922                active_primary_range.take();
 9923                if direction == Direction::Prev {
 9924                    if search_start == buffer.len() {
 9925                        break;
 9926                    } else {
 9927                        search_start = buffer.len();
 9928                    }
 9929                } else if search_start == 0 {
 9930                    break;
 9931                } else {
 9932                    search_start = 0;
 9933                }
 9934            }
 9935        }
 9936    }
 9937
 9938    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
 9939        let snapshot = self.snapshot(window, cx);
 9940        let selection = self.selections.newest::<Point>(cx);
 9941        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
 9942    }
 9943
 9944    fn go_to_hunk_after_position(
 9945        &mut self,
 9946        snapshot: &EditorSnapshot,
 9947        position: Point,
 9948        window: &mut Window,
 9949        cx: &mut Context<Editor>,
 9950    ) -> Option<MultiBufferDiffHunk> {
 9951        let mut hunk = snapshot
 9952            .buffer_snapshot
 9953            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
 9954            .find(|hunk| hunk.row_range.start.0 > position.row);
 9955        if hunk.is_none() {
 9956            hunk = snapshot
 9957                .buffer_snapshot
 9958                .diff_hunks_in_range(Point::zero()..position)
 9959                .find(|hunk| hunk.row_range.end.0 < position.row)
 9960        }
 9961        if let Some(hunk) = &hunk {
 9962            let destination = Point::new(hunk.row_range.start.0, 0);
 9963            self.unfold_ranges(&[destination..destination], false, false, cx);
 9964            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9965                s.select_ranges(vec![destination..destination]);
 9966            });
 9967        }
 9968
 9969        hunk
 9970    }
 9971
 9972    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
 9973        let snapshot = self.snapshot(window, cx);
 9974        let selection = self.selections.newest::<Point>(cx);
 9975        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
 9976    }
 9977
 9978    fn go_to_hunk_before_position(
 9979        &mut self,
 9980        snapshot: &EditorSnapshot,
 9981        position: Point,
 9982        window: &mut Window,
 9983        cx: &mut Context<Editor>,
 9984    ) -> Option<MultiBufferDiffHunk> {
 9985        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
 9986        if hunk.is_none() {
 9987            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
 9988        }
 9989        if let Some(hunk) = &hunk {
 9990            let destination = Point::new(hunk.row_range.start.0, 0);
 9991            self.unfold_ranges(&[destination..destination], false, false, cx);
 9992            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9993                s.select_ranges(vec![destination..destination]);
 9994            });
 9995        }
 9996
 9997        hunk
 9998    }
 9999
10000    pub fn go_to_definition(
10001        &mut self,
10002        _: &GoToDefinition,
10003        window: &mut Window,
10004        cx: &mut Context<Self>,
10005    ) -> Task<Result<Navigated>> {
10006        let definition =
10007            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10008        cx.spawn_in(window, |editor, mut cx| async move {
10009            if definition.await? == Navigated::Yes {
10010                return Ok(Navigated::Yes);
10011            }
10012            match editor.update_in(&mut cx, |editor, window, cx| {
10013                editor.find_all_references(&FindAllReferences, window, cx)
10014            })? {
10015                Some(references) => references.await,
10016                None => Ok(Navigated::No),
10017            }
10018        })
10019    }
10020
10021    pub fn go_to_declaration(
10022        &mut self,
10023        _: &GoToDeclaration,
10024        window: &mut Window,
10025        cx: &mut Context<Self>,
10026    ) -> Task<Result<Navigated>> {
10027        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10028    }
10029
10030    pub fn go_to_declaration_split(
10031        &mut self,
10032        _: &GoToDeclaration,
10033        window: &mut Window,
10034        cx: &mut Context<Self>,
10035    ) -> Task<Result<Navigated>> {
10036        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10037    }
10038
10039    pub fn go_to_implementation(
10040        &mut self,
10041        _: &GoToImplementation,
10042        window: &mut Window,
10043        cx: &mut Context<Self>,
10044    ) -> Task<Result<Navigated>> {
10045        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10046    }
10047
10048    pub fn go_to_implementation_split(
10049        &mut self,
10050        _: &GoToImplementationSplit,
10051        window: &mut Window,
10052        cx: &mut Context<Self>,
10053    ) -> Task<Result<Navigated>> {
10054        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10055    }
10056
10057    pub fn go_to_type_definition(
10058        &mut self,
10059        _: &GoToTypeDefinition,
10060        window: &mut Window,
10061        cx: &mut Context<Self>,
10062    ) -> Task<Result<Navigated>> {
10063        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10064    }
10065
10066    pub fn go_to_definition_split(
10067        &mut self,
10068        _: &GoToDefinitionSplit,
10069        window: &mut Window,
10070        cx: &mut Context<Self>,
10071    ) -> Task<Result<Navigated>> {
10072        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10073    }
10074
10075    pub fn go_to_type_definition_split(
10076        &mut self,
10077        _: &GoToTypeDefinitionSplit,
10078        window: &mut Window,
10079        cx: &mut Context<Self>,
10080    ) -> Task<Result<Navigated>> {
10081        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10082    }
10083
10084    fn go_to_definition_of_kind(
10085        &mut self,
10086        kind: GotoDefinitionKind,
10087        split: bool,
10088        window: &mut Window,
10089        cx: &mut Context<Self>,
10090    ) -> Task<Result<Navigated>> {
10091        let Some(provider) = self.semantics_provider.clone() else {
10092            return Task::ready(Ok(Navigated::No));
10093        };
10094        let head = self.selections.newest::<usize>(cx).head();
10095        let buffer = self.buffer.read(cx);
10096        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10097            text_anchor
10098        } else {
10099            return Task::ready(Ok(Navigated::No));
10100        };
10101
10102        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10103            return Task::ready(Ok(Navigated::No));
10104        };
10105
10106        cx.spawn_in(window, |editor, mut cx| async move {
10107            let definitions = definitions.await?;
10108            let navigated = editor
10109                .update_in(&mut cx, |editor, window, cx| {
10110                    editor.navigate_to_hover_links(
10111                        Some(kind),
10112                        definitions
10113                            .into_iter()
10114                            .filter(|location| {
10115                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10116                            })
10117                            .map(HoverLink::Text)
10118                            .collect::<Vec<_>>(),
10119                        split,
10120                        window,
10121                        cx,
10122                    )
10123                })?
10124                .await?;
10125            anyhow::Ok(navigated)
10126        })
10127    }
10128
10129    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10130        let selection = self.selections.newest_anchor();
10131        let head = selection.head();
10132        let tail = selection.tail();
10133
10134        let Some((buffer, start_position)) =
10135            self.buffer.read(cx).text_anchor_for_position(head, cx)
10136        else {
10137            return;
10138        };
10139
10140        let end_position = if head != tail {
10141            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10142                return;
10143            };
10144            Some(pos)
10145        } else {
10146            None
10147        };
10148
10149        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10150            let url = if let Some(end_pos) = end_position {
10151                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10152            } else {
10153                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10154            };
10155
10156            if let Some(url) = url {
10157                editor.update(&mut cx, |_, cx| {
10158                    cx.open_url(&url);
10159                })
10160            } else {
10161                Ok(())
10162            }
10163        });
10164
10165        url_finder.detach();
10166    }
10167
10168    pub fn open_selected_filename(
10169        &mut self,
10170        _: &OpenSelectedFilename,
10171        window: &mut Window,
10172        cx: &mut Context<Self>,
10173    ) {
10174        let Some(workspace) = self.workspace() else {
10175            return;
10176        };
10177
10178        let position = self.selections.newest_anchor().head();
10179
10180        let Some((buffer, buffer_position)) =
10181            self.buffer.read(cx).text_anchor_for_position(position, cx)
10182        else {
10183            return;
10184        };
10185
10186        let project = self.project.clone();
10187
10188        cx.spawn_in(window, |_, mut cx| async move {
10189            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10190
10191            if let Some((_, path)) = result {
10192                workspace
10193                    .update_in(&mut cx, |workspace, window, cx| {
10194                        workspace.open_resolved_path(path, window, cx)
10195                    })?
10196                    .await?;
10197            }
10198            anyhow::Ok(())
10199        })
10200        .detach();
10201    }
10202
10203    pub(crate) fn navigate_to_hover_links(
10204        &mut self,
10205        kind: Option<GotoDefinitionKind>,
10206        mut definitions: Vec<HoverLink>,
10207        split: bool,
10208        window: &mut Window,
10209        cx: &mut Context<Editor>,
10210    ) -> Task<Result<Navigated>> {
10211        // If there is one definition, just open it directly
10212        if definitions.len() == 1 {
10213            let definition = definitions.pop().unwrap();
10214
10215            enum TargetTaskResult {
10216                Location(Option<Location>),
10217                AlreadyNavigated,
10218            }
10219
10220            let target_task = match definition {
10221                HoverLink::Text(link) => {
10222                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10223                }
10224                HoverLink::InlayHint(lsp_location, server_id) => {
10225                    let computation =
10226                        self.compute_target_location(lsp_location, server_id, window, cx);
10227                    cx.background_executor().spawn(async move {
10228                        let location = computation.await?;
10229                        Ok(TargetTaskResult::Location(location))
10230                    })
10231                }
10232                HoverLink::Url(url) => {
10233                    cx.open_url(&url);
10234                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10235                }
10236                HoverLink::File(path) => {
10237                    if let Some(workspace) = self.workspace() {
10238                        cx.spawn_in(window, |_, mut cx| async move {
10239                            workspace
10240                                .update_in(&mut cx, |workspace, window, cx| {
10241                                    workspace.open_resolved_path(path, window, cx)
10242                                })?
10243                                .await
10244                                .map(|_| TargetTaskResult::AlreadyNavigated)
10245                        })
10246                    } else {
10247                        Task::ready(Ok(TargetTaskResult::Location(None)))
10248                    }
10249                }
10250            };
10251            cx.spawn_in(window, |editor, mut cx| async move {
10252                let target = match target_task.await.context("target resolution task")? {
10253                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10254                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10255                    TargetTaskResult::Location(Some(target)) => target,
10256                };
10257
10258                editor.update_in(&mut cx, |editor, window, cx| {
10259                    let Some(workspace) = editor.workspace() else {
10260                        return Navigated::No;
10261                    };
10262                    let pane = workspace.read(cx).active_pane().clone();
10263
10264                    let range = target.range.to_point(target.buffer.read(cx));
10265                    let range = editor.range_for_match(&range);
10266                    let range = collapse_multiline_range(range);
10267
10268                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10269                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10270                    } else {
10271                        window.defer(cx, move |window, cx| {
10272                            let target_editor: Entity<Self> =
10273                                workspace.update(cx, |workspace, cx| {
10274                                    let pane = if split {
10275                                        workspace.adjacent_pane(window, cx)
10276                                    } else {
10277                                        workspace.active_pane().clone()
10278                                    };
10279
10280                                    workspace.open_project_item(
10281                                        pane,
10282                                        target.buffer.clone(),
10283                                        true,
10284                                        true,
10285                                        window,
10286                                        cx,
10287                                    )
10288                                });
10289                            target_editor.update(cx, |target_editor, cx| {
10290                                // When selecting a definition in a different buffer, disable the nav history
10291                                // to avoid creating a history entry at the previous cursor location.
10292                                pane.update(cx, |pane, _| pane.disable_history());
10293                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10294                                pane.update(cx, |pane, _| pane.enable_history());
10295                            });
10296                        });
10297                    }
10298                    Navigated::Yes
10299                })
10300            })
10301        } else if !definitions.is_empty() {
10302            cx.spawn_in(window, |editor, mut cx| async move {
10303                let (title, location_tasks, workspace) = editor
10304                    .update_in(&mut cx, |editor, window, cx| {
10305                        let tab_kind = match kind {
10306                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10307                            _ => "Definitions",
10308                        };
10309                        let title = definitions
10310                            .iter()
10311                            .find_map(|definition| match definition {
10312                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10313                                    let buffer = origin.buffer.read(cx);
10314                                    format!(
10315                                        "{} for {}",
10316                                        tab_kind,
10317                                        buffer
10318                                            .text_for_range(origin.range.clone())
10319                                            .collect::<String>()
10320                                    )
10321                                }),
10322                                HoverLink::InlayHint(_, _) => None,
10323                                HoverLink::Url(_) => None,
10324                                HoverLink::File(_) => None,
10325                            })
10326                            .unwrap_or(tab_kind.to_string());
10327                        let location_tasks = definitions
10328                            .into_iter()
10329                            .map(|definition| match definition {
10330                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10331                                HoverLink::InlayHint(lsp_location, server_id) => editor
10332                                    .compute_target_location(lsp_location, server_id, window, cx),
10333                                HoverLink::Url(_) => Task::ready(Ok(None)),
10334                                HoverLink::File(_) => Task::ready(Ok(None)),
10335                            })
10336                            .collect::<Vec<_>>();
10337                        (title, location_tasks, editor.workspace().clone())
10338                    })
10339                    .context("location tasks preparation")?;
10340
10341                let locations = future::join_all(location_tasks)
10342                    .await
10343                    .into_iter()
10344                    .filter_map(|location| location.transpose())
10345                    .collect::<Result<_>>()
10346                    .context("location tasks")?;
10347
10348                let Some(workspace) = workspace else {
10349                    return Ok(Navigated::No);
10350                };
10351                let opened = workspace
10352                    .update_in(&mut cx, |workspace, window, cx| {
10353                        Self::open_locations_in_multibuffer(
10354                            workspace,
10355                            locations,
10356                            title,
10357                            split,
10358                            MultibufferSelectionMode::First,
10359                            window,
10360                            cx,
10361                        )
10362                    })
10363                    .ok();
10364
10365                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10366            })
10367        } else {
10368            Task::ready(Ok(Navigated::No))
10369        }
10370    }
10371
10372    fn compute_target_location(
10373        &self,
10374        lsp_location: lsp::Location,
10375        server_id: LanguageServerId,
10376        window: &mut Window,
10377        cx: &mut Context<Self>,
10378    ) -> Task<anyhow::Result<Option<Location>>> {
10379        let Some(project) = self.project.clone() else {
10380            return Task::ready(Ok(None));
10381        };
10382
10383        cx.spawn_in(window, move |editor, mut cx| async move {
10384            let location_task = editor.update(&mut cx, |_, cx| {
10385                project.update(cx, |project, cx| {
10386                    let language_server_name = project
10387                        .language_server_statuses(cx)
10388                        .find(|(id, _)| server_id == *id)
10389                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10390                    language_server_name.map(|language_server_name| {
10391                        project.open_local_buffer_via_lsp(
10392                            lsp_location.uri.clone(),
10393                            server_id,
10394                            language_server_name,
10395                            cx,
10396                        )
10397                    })
10398                })
10399            })?;
10400            let location = match location_task {
10401                Some(task) => Some({
10402                    let target_buffer_handle = task.await.context("open local buffer")?;
10403                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10404                        let target_start = target_buffer
10405                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10406                        let target_end = target_buffer
10407                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10408                        target_buffer.anchor_after(target_start)
10409                            ..target_buffer.anchor_before(target_end)
10410                    })?;
10411                    Location {
10412                        buffer: target_buffer_handle,
10413                        range,
10414                    }
10415                }),
10416                None => None,
10417            };
10418            Ok(location)
10419        })
10420    }
10421
10422    pub fn find_all_references(
10423        &mut self,
10424        _: &FindAllReferences,
10425        window: &mut Window,
10426        cx: &mut Context<Self>,
10427    ) -> Option<Task<Result<Navigated>>> {
10428        let selection = self.selections.newest::<usize>(cx);
10429        let multi_buffer = self.buffer.read(cx);
10430        let head = selection.head();
10431
10432        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10433        let head_anchor = multi_buffer_snapshot.anchor_at(
10434            head,
10435            if head < selection.tail() {
10436                Bias::Right
10437            } else {
10438                Bias::Left
10439            },
10440        );
10441
10442        match self
10443            .find_all_references_task_sources
10444            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10445        {
10446            Ok(_) => {
10447                log::info!(
10448                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10449                );
10450                return None;
10451            }
10452            Err(i) => {
10453                self.find_all_references_task_sources.insert(i, head_anchor);
10454            }
10455        }
10456
10457        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10458        let workspace = self.workspace()?;
10459        let project = workspace.read(cx).project().clone();
10460        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10461        Some(cx.spawn_in(window, |editor, mut cx| async move {
10462            let _cleanup = defer({
10463                let mut cx = cx.clone();
10464                move || {
10465                    let _ = editor.update(&mut cx, |editor, _| {
10466                        if let Ok(i) =
10467                            editor
10468                                .find_all_references_task_sources
10469                                .binary_search_by(|anchor| {
10470                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10471                                })
10472                        {
10473                            editor.find_all_references_task_sources.remove(i);
10474                        }
10475                    });
10476                }
10477            });
10478
10479            let locations = references.await?;
10480            if locations.is_empty() {
10481                return anyhow::Ok(Navigated::No);
10482            }
10483
10484            workspace.update_in(&mut cx, |workspace, window, cx| {
10485                let title = locations
10486                    .first()
10487                    .as_ref()
10488                    .map(|location| {
10489                        let buffer = location.buffer.read(cx);
10490                        format!(
10491                            "References to `{}`",
10492                            buffer
10493                                .text_for_range(location.range.clone())
10494                                .collect::<String>()
10495                        )
10496                    })
10497                    .unwrap();
10498                Self::open_locations_in_multibuffer(
10499                    workspace,
10500                    locations,
10501                    title,
10502                    false,
10503                    MultibufferSelectionMode::First,
10504                    window,
10505                    cx,
10506                );
10507                Navigated::Yes
10508            })
10509        }))
10510    }
10511
10512    /// Opens a multibuffer with the given project locations in it
10513    pub fn open_locations_in_multibuffer(
10514        workspace: &mut Workspace,
10515        mut locations: Vec<Location>,
10516        title: String,
10517        split: bool,
10518        multibuffer_selection_mode: MultibufferSelectionMode,
10519        window: &mut Window,
10520        cx: &mut Context<Workspace>,
10521    ) {
10522        // If there are multiple definitions, open them in a multibuffer
10523        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10524        let mut locations = locations.into_iter().peekable();
10525        let mut ranges = Vec::new();
10526        let capability = workspace.project().read(cx).capability();
10527
10528        let excerpt_buffer = cx.new(|cx| {
10529            let mut multibuffer = MultiBuffer::new(capability);
10530            while let Some(location) = locations.next() {
10531                let buffer = location.buffer.read(cx);
10532                let mut ranges_for_buffer = Vec::new();
10533                let range = location.range.to_offset(buffer);
10534                ranges_for_buffer.push(range.clone());
10535
10536                while let Some(next_location) = locations.peek() {
10537                    if next_location.buffer == location.buffer {
10538                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10539                        locations.next();
10540                    } else {
10541                        break;
10542                    }
10543                }
10544
10545                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10546                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10547                    location.buffer.clone(),
10548                    ranges_for_buffer,
10549                    DEFAULT_MULTIBUFFER_CONTEXT,
10550                    cx,
10551                ))
10552            }
10553
10554            multibuffer.with_title(title)
10555        });
10556
10557        let editor = cx.new(|cx| {
10558            Editor::for_multibuffer(
10559                excerpt_buffer,
10560                Some(workspace.project().clone()),
10561                true,
10562                window,
10563                cx,
10564            )
10565        });
10566        editor.update(cx, |editor, cx| {
10567            match multibuffer_selection_mode {
10568                MultibufferSelectionMode::First => {
10569                    if let Some(first_range) = ranges.first() {
10570                        editor.change_selections(None, window, cx, |selections| {
10571                            selections.clear_disjoint();
10572                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10573                        });
10574                    }
10575                    editor.highlight_background::<Self>(
10576                        &ranges,
10577                        |theme| theme.editor_highlighted_line_background,
10578                        cx,
10579                    );
10580                }
10581                MultibufferSelectionMode::All => {
10582                    editor.change_selections(None, window, cx, |selections| {
10583                        selections.clear_disjoint();
10584                        selections.select_anchor_ranges(ranges);
10585                    });
10586                }
10587            }
10588            editor.register_buffers_with_language_servers(cx);
10589        });
10590
10591        let item = Box::new(editor);
10592        let item_id = item.item_id();
10593
10594        if split {
10595            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10596        } else {
10597            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10598                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10599                    pane.close_current_preview_item(window, cx)
10600                } else {
10601                    None
10602                }
10603            });
10604            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10605        }
10606        workspace.active_pane().update(cx, |pane, cx| {
10607            pane.set_preview_item_id(Some(item_id), cx);
10608        });
10609    }
10610
10611    pub fn rename(
10612        &mut self,
10613        _: &Rename,
10614        window: &mut Window,
10615        cx: &mut Context<Self>,
10616    ) -> Option<Task<Result<()>>> {
10617        use language::ToOffset as _;
10618
10619        let provider = self.semantics_provider.clone()?;
10620        let selection = self.selections.newest_anchor().clone();
10621        let (cursor_buffer, cursor_buffer_position) = self
10622            .buffer
10623            .read(cx)
10624            .text_anchor_for_position(selection.head(), cx)?;
10625        let (tail_buffer, cursor_buffer_position_end) = self
10626            .buffer
10627            .read(cx)
10628            .text_anchor_for_position(selection.tail(), cx)?;
10629        if tail_buffer != cursor_buffer {
10630            return None;
10631        }
10632
10633        let snapshot = cursor_buffer.read(cx).snapshot();
10634        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10635        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10636        let prepare_rename = provider
10637            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10638            .unwrap_or_else(|| Task::ready(Ok(None)));
10639        drop(snapshot);
10640
10641        Some(cx.spawn_in(window, |this, mut cx| async move {
10642            let rename_range = if let Some(range) = prepare_rename.await? {
10643                Some(range)
10644            } else {
10645                this.update(&mut cx, |this, cx| {
10646                    let buffer = this.buffer.read(cx).snapshot(cx);
10647                    let mut buffer_highlights = this
10648                        .document_highlights_for_position(selection.head(), &buffer)
10649                        .filter(|highlight| {
10650                            highlight.start.excerpt_id == selection.head().excerpt_id
10651                                && highlight.end.excerpt_id == selection.head().excerpt_id
10652                        });
10653                    buffer_highlights
10654                        .next()
10655                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10656                })?
10657            };
10658            if let Some(rename_range) = rename_range {
10659                this.update_in(&mut cx, |this, window, cx| {
10660                    let snapshot = cursor_buffer.read(cx).snapshot();
10661                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10662                    let cursor_offset_in_rename_range =
10663                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10664                    let cursor_offset_in_rename_range_end =
10665                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10666
10667                    this.take_rename(false, window, cx);
10668                    let buffer = this.buffer.read(cx).read(cx);
10669                    let cursor_offset = selection.head().to_offset(&buffer);
10670                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10671                    let rename_end = rename_start + rename_buffer_range.len();
10672                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10673                    let mut old_highlight_id = None;
10674                    let old_name: Arc<str> = buffer
10675                        .chunks(rename_start..rename_end, true)
10676                        .map(|chunk| {
10677                            if old_highlight_id.is_none() {
10678                                old_highlight_id = chunk.syntax_highlight_id;
10679                            }
10680                            chunk.text
10681                        })
10682                        .collect::<String>()
10683                        .into();
10684
10685                    drop(buffer);
10686
10687                    // Position the selection in the rename editor so that it matches the current selection.
10688                    this.show_local_selections = false;
10689                    let rename_editor = cx.new(|cx| {
10690                        let mut editor = Editor::single_line(window, cx);
10691                        editor.buffer.update(cx, |buffer, cx| {
10692                            buffer.edit([(0..0, old_name.clone())], None, cx)
10693                        });
10694                        let rename_selection_range = match cursor_offset_in_rename_range
10695                            .cmp(&cursor_offset_in_rename_range_end)
10696                        {
10697                            Ordering::Equal => {
10698                                editor.select_all(&SelectAll, window, cx);
10699                                return editor;
10700                            }
10701                            Ordering::Less => {
10702                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10703                            }
10704                            Ordering::Greater => {
10705                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10706                            }
10707                        };
10708                        if rename_selection_range.end > old_name.len() {
10709                            editor.select_all(&SelectAll, window, cx);
10710                        } else {
10711                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10712                                s.select_ranges([rename_selection_range]);
10713                            });
10714                        }
10715                        editor
10716                    });
10717                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10718                        if e == &EditorEvent::Focused {
10719                            cx.emit(EditorEvent::FocusedIn)
10720                        }
10721                    })
10722                    .detach();
10723
10724                    let write_highlights =
10725                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10726                    let read_highlights =
10727                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10728                    let ranges = write_highlights
10729                        .iter()
10730                        .flat_map(|(_, ranges)| ranges.iter())
10731                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10732                        .cloned()
10733                        .collect();
10734
10735                    this.highlight_text::<Rename>(
10736                        ranges,
10737                        HighlightStyle {
10738                            fade_out: Some(0.6),
10739                            ..Default::default()
10740                        },
10741                        cx,
10742                    );
10743                    let rename_focus_handle = rename_editor.focus_handle(cx);
10744                    window.focus(&rename_focus_handle);
10745                    let block_id = this.insert_blocks(
10746                        [BlockProperties {
10747                            style: BlockStyle::Flex,
10748                            placement: BlockPlacement::Below(range.start),
10749                            height: 1,
10750                            render: Arc::new({
10751                                let rename_editor = rename_editor.clone();
10752                                move |cx: &mut BlockContext| {
10753                                    let mut text_style = cx.editor_style.text.clone();
10754                                    if let Some(highlight_style) = old_highlight_id
10755                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10756                                    {
10757                                        text_style = text_style.highlight(highlight_style);
10758                                    }
10759                                    div()
10760                                        .block_mouse_down()
10761                                        .pl(cx.anchor_x)
10762                                        .child(EditorElement::new(
10763                                            &rename_editor,
10764                                            EditorStyle {
10765                                                background: cx.theme().system().transparent,
10766                                                local_player: cx.editor_style.local_player,
10767                                                text: text_style,
10768                                                scrollbar_width: cx.editor_style.scrollbar_width,
10769                                                syntax: cx.editor_style.syntax.clone(),
10770                                                status: cx.editor_style.status.clone(),
10771                                                inlay_hints_style: HighlightStyle {
10772                                                    font_weight: Some(FontWeight::BOLD),
10773                                                    ..make_inlay_hints_style(cx.app)
10774                                                },
10775                                                inline_completion_styles: make_suggestion_styles(
10776                                                    cx.app,
10777                                                ),
10778                                                ..EditorStyle::default()
10779                                            },
10780                                        ))
10781                                        .into_any_element()
10782                                }
10783                            }),
10784                            priority: 0,
10785                        }],
10786                        Some(Autoscroll::fit()),
10787                        cx,
10788                    )[0];
10789                    this.pending_rename = Some(RenameState {
10790                        range,
10791                        old_name,
10792                        editor: rename_editor,
10793                        block_id,
10794                    });
10795                })?;
10796            }
10797
10798            Ok(())
10799        }))
10800    }
10801
10802    pub fn confirm_rename(
10803        &mut self,
10804        _: &ConfirmRename,
10805        window: &mut Window,
10806        cx: &mut Context<Self>,
10807    ) -> Option<Task<Result<()>>> {
10808        let rename = self.take_rename(false, window, cx)?;
10809        let workspace = self.workspace()?.downgrade();
10810        let (buffer, start) = self
10811            .buffer
10812            .read(cx)
10813            .text_anchor_for_position(rename.range.start, cx)?;
10814        let (end_buffer, _) = self
10815            .buffer
10816            .read(cx)
10817            .text_anchor_for_position(rename.range.end, cx)?;
10818        if buffer != end_buffer {
10819            return None;
10820        }
10821
10822        let old_name = rename.old_name;
10823        let new_name = rename.editor.read(cx).text(cx);
10824
10825        let rename = self.semantics_provider.as_ref()?.perform_rename(
10826            &buffer,
10827            start,
10828            new_name.clone(),
10829            cx,
10830        )?;
10831
10832        Some(cx.spawn_in(window, |editor, mut cx| async move {
10833            let project_transaction = rename.await?;
10834            Self::open_project_transaction(
10835                &editor,
10836                workspace,
10837                project_transaction,
10838                format!("Rename: {}{}", old_name, new_name),
10839                cx.clone(),
10840            )
10841            .await?;
10842
10843            editor.update(&mut cx, |editor, cx| {
10844                editor.refresh_document_highlights(cx);
10845            })?;
10846            Ok(())
10847        }))
10848    }
10849
10850    fn take_rename(
10851        &mut self,
10852        moving_cursor: bool,
10853        window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) -> Option<RenameState> {
10856        let rename = self.pending_rename.take()?;
10857        if rename.editor.focus_handle(cx).is_focused(window) {
10858            window.focus(&self.focus_handle);
10859        }
10860
10861        self.remove_blocks(
10862            [rename.block_id].into_iter().collect(),
10863            Some(Autoscroll::fit()),
10864            cx,
10865        );
10866        self.clear_highlights::<Rename>(cx);
10867        self.show_local_selections = true;
10868
10869        if moving_cursor {
10870            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10871                editor.selections.newest::<usize>(cx).head()
10872            });
10873
10874            // Update the selection to match the position of the selection inside
10875            // the rename editor.
10876            let snapshot = self.buffer.read(cx).read(cx);
10877            let rename_range = rename.range.to_offset(&snapshot);
10878            let cursor_in_editor = snapshot
10879                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10880                .min(rename_range.end);
10881            drop(snapshot);
10882
10883            self.change_selections(None, window, cx, |s| {
10884                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10885            });
10886        } else {
10887            self.refresh_document_highlights(cx);
10888        }
10889
10890        Some(rename)
10891    }
10892
10893    pub fn pending_rename(&self) -> Option<&RenameState> {
10894        self.pending_rename.as_ref()
10895    }
10896
10897    fn format(
10898        &mut self,
10899        _: &Format,
10900        window: &mut Window,
10901        cx: &mut Context<Self>,
10902    ) -> Option<Task<Result<()>>> {
10903        let project = match &self.project {
10904            Some(project) => project.clone(),
10905            None => return None,
10906        };
10907
10908        Some(self.perform_format(
10909            project,
10910            FormatTrigger::Manual,
10911            FormatTarget::Buffers,
10912            window,
10913            cx,
10914        ))
10915    }
10916
10917    fn format_selections(
10918        &mut self,
10919        _: &FormatSelections,
10920        window: &mut Window,
10921        cx: &mut Context<Self>,
10922    ) -> Option<Task<Result<()>>> {
10923        let project = match &self.project {
10924            Some(project) => project.clone(),
10925            None => return None,
10926        };
10927
10928        let ranges = self
10929            .selections
10930            .all_adjusted(cx)
10931            .into_iter()
10932            .map(|selection| selection.range())
10933            .collect_vec();
10934
10935        Some(self.perform_format(
10936            project,
10937            FormatTrigger::Manual,
10938            FormatTarget::Ranges(ranges),
10939            window,
10940            cx,
10941        ))
10942    }
10943
10944    fn perform_format(
10945        &mut self,
10946        project: Entity<Project>,
10947        trigger: FormatTrigger,
10948        target: FormatTarget,
10949        window: &mut Window,
10950        cx: &mut Context<Self>,
10951    ) -> Task<Result<()>> {
10952        let buffer = self.buffer.clone();
10953        let (buffers, target) = match target {
10954            FormatTarget::Buffers => {
10955                let mut buffers = buffer.read(cx).all_buffers();
10956                if trigger == FormatTrigger::Save {
10957                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10958                }
10959                (buffers, LspFormatTarget::Buffers)
10960            }
10961            FormatTarget::Ranges(selection_ranges) => {
10962                let multi_buffer = buffer.read(cx);
10963                let snapshot = multi_buffer.read(cx);
10964                let mut buffers = HashSet::default();
10965                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10966                    BTreeMap::new();
10967                for selection_range in selection_ranges {
10968                    for (buffer, buffer_range, _) in
10969                        snapshot.range_to_buffer_ranges(selection_range)
10970                    {
10971                        let buffer_id = buffer.remote_id();
10972                        let start = buffer.anchor_before(buffer_range.start);
10973                        let end = buffer.anchor_after(buffer_range.end);
10974                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10975                        buffer_id_to_ranges
10976                            .entry(buffer_id)
10977                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10978                            .or_insert_with(|| vec![start..end]);
10979                    }
10980                }
10981                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10982            }
10983        };
10984
10985        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10986        let format = project.update(cx, |project, cx| {
10987            project.format(buffers, target, true, trigger, cx)
10988        });
10989
10990        cx.spawn_in(window, |_, mut cx| async move {
10991            let transaction = futures::select_biased! {
10992                () = timeout => {
10993                    log::warn!("timed out waiting for formatting");
10994                    None
10995                }
10996                transaction = format.log_err().fuse() => transaction,
10997            };
10998
10999            buffer
11000                .update(&mut cx, |buffer, cx| {
11001                    if let Some(transaction) = transaction {
11002                        if !buffer.is_singleton() {
11003                            buffer.push_transaction(&transaction.0, cx);
11004                        }
11005                    }
11006
11007                    cx.notify();
11008                })
11009                .ok();
11010
11011            Ok(())
11012        })
11013    }
11014
11015    fn restart_language_server(
11016        &mut self,
11017        _: &RestartLanguageServer,
11018        _: &mut Window,
11019        cx: &mut Context<Self>,
11020    ) {
11021        if let Some(project) = self.project.clone() {
11022            self.buffer.update(cx, |multi_buffer, cx| {
11023                project.update(cx, |project, cx| {
11024                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11025                });
11026            })
11027        }
11028    }
11029
11030    fn cancel_language_server_work(
11031        &mut self,
11032        _: &actions::CancelLanguageServerWork,
11033        _: &mut Window,
11034        cx: &mut Context<Self>,
11035    ) {
11036        if let Some(project) = self.project.clone() {
11037            self.buffer.update(cx, |multi_buffer, cx| {
11038                project.update(cx, |project, cx| {
11039                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11040                });
11041            })
11042        }
11043    }
11044
11045    fn show_character_palette(
11046        &mut self,
11047        _: &ShowCharacterPalette,
11048        window: &mut Window,
11049        _: &mut Context<Self>,
11050    ) {
11051        window.show_character_palette();
11052    }
11053
11054    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11055        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11056            let buffer = self.buffer.read(cx).snapshot(cx);
11057            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11058            let is_valid = buffer
11059                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11060                .any(|entry| {
11061                    entry.diagnostic.is_primary
11062                        && !entry.range.is_empty()
11063                        && entry.range.start == primary_range_start
11064                        && entry.diagnostic.message == active_diagnostics.primary_message
11065                });
11066
11067            if is_valid != active_diagnostics.is_valid {
11068                active_diagnostics.is_valid = is_valid;
11069                let mut new_styles = HashMap::default();
11070                for (block_id, diagnostic) in &active_diagnostics.blocks {
11071                    new_styles.insert(
11072                        *block_id,
11073                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11074                    );
11075                }
11076                self.display_map.update(cx, |display_map, _cx| {
11077                    display_map.replace_blocks(new_styles)
11078                });
11079            }
11080        }
11081    }
11082
11083    fn activate_diagnostics(
11084        &mut self,
11085        buffer_id: BufferId,
11086        group_id: usize,
11087        window: &mut Window,
11088        cx: &mut Context<Self>,
11089    ) {
11090        self.dismiss_diagnostics(cx);
11091        let snapshot = self.snapshot(window, cx);
11092        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11093            let buffer = self.buffer.read(cx).snapshot(cx);
11094
11095            let mut primary_range = None;
11096            let mut primary_message = None;
11097            let diagnostic_group = buffer
11098                .diagnostic_group(buffer_id, group_id)
11099                .filter_map(|entry| {
11100                    let start = entry.range.start;
11101                    let end = entry.range.end;
11102                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11103                        && (start.row == end.row
11104                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11105                    {
11106                        return None;
11107                    }
11108                    if entry.diagnostic.is_primary {
11109                        primary_range = Some(entry.range.clone());
11110                        primary_message = Some(entry.diagnostic.message.clone());
11111                    }
11112                    Some(entry)
11113                })
11114                .collect::<Vec<_>>();
11115            let primary_range = primary_range?;
11116            let primary_message = primary_message?;
11117
11118            let blocks = display_map
11119                .insert_blocks(
11120                    diagnostic_group.iter().map(|entry| {
11121                        let diagnostic = entry.diagnostic.clone();
11122                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11123                        BlockProperties {
11124                            style: BlockStyle::Fixed,
11125                            placement: BlockPlacement::Below(
11126                                buffer.anchor_after(entry.range.start),
11127                            ),
11128                            height: message_height,
11129                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11130                            priority: 0,
11131                        }
11132                    }),
11133                    cx,
11134                )
11135                .into_iter()
11136                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11137                .collect();
11138
11139            Some(ActiveDiagnosticGroup {
11140                primary_range: buffer.anchor_before(primary_range.start)
11141                    ..buffer.anchor_after(primary_range.end),
11142                primary_message,
11143                group_id,
11144                blocks,
11145                is_valid: true,
11146            })
11147        });
11148    }
11149
11150    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11151        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11152            self.display_map.update(cx, |display_map, cx| {
11153                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11154            });
11155            cx.notify();
11156        }
11157    }
11158
11159    pub fn set_selections_from_remote(
11160        &mut self,
11161        selections: Vec<Selection<Anchor>>,
11162        pending_selection: Option<Selection<Anchor>>,
11163        window: &mut Window,
11164        cx: &mut Context<Self>,
11165    ) {
11166        let old_cursor_position = self.selections.newest_anchor().head();
11167        self.selections.change_with(cx, |s| {
11168            s.select_anchors(selections);
11169            if let Some(pending_selection) = pending_selection {
11170                s.set_pending(pending_selection, SelectMode::Character);
11171            } else {
11172                s.clear_pending();
11173            }
11174        });
11175        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11176    }
11177
11178    fn push_to_selection_history(&mut self) {
11179        self.selection_history.push(SelectionHistoryEntry {
11180            selections: self.selections.disjoint_anchors(),
11181            select_next_state: self.select_next_state.clone(),
11182            select_prev_state: self.select_prev_state.clone(),
11183            add_selections_state: self.add_selections_state.clone(),
11184        });
11185    }
11186
11187    pub fn transact(
11188        &mut self,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11192    ) -> Option<TransactionId> {
11193        self.start_transaction_at(Instant::now(), window, cx);
11194        update(self, window, cx);
11195        self.end_transaction_at(Instant::now(), cx)
11196    }
11197
11198    pub fn start_transaction_at(
11199        &mut self,
11200        now: Instant,
11201        window: &mut Window,
11202        cx: &mut Context<Self>,
11203    ) {
11204        self.end_selection(window, cx);
11205        if let Some(tx_id) = self
11206            .buffer
11207            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11208        {
11209            self.selection_history
11210                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11211            cx.emit(EditorEvent::TransactionBegun {
11212                transaction_id: tx_id,
11213            })
11214        }
11215    }
11216
11217    pub fn end_transaction_at(
11218        &mut self,
11219        now: Instant,
11220        cx: &mut Context<Self>,
11221    ) -> Option<TransactionId> {
11222        if let Some(transaction_id) = self
11223            .buffer
11224            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11225        {
11226            if let Some((_, end_selections)) =
11227                self.selection_history.transaction_mut(transaction_id)
11228            {
11229                *end_selections = Some(self.selections.disjoint_anchors());
11230            } else {
11231                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11232            }
11233
11234            cx.emit(EditorEvent::Edited { transaction_id });
11235            Some(transaction_id)
11236        } else {
11237            None
11238        }
11239    }
11240
11241    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11242        if self.selection_mark_mode {
11243            self.change_selections(None, window, cx, |s| {
11244                s.move_with(|_, sel| {
11245                    sel.collapse_to(sel.head(), SelectionGoal::None);
11246                });
11247            })
11248        }
11249        self.selection_mark_mode = true;
11250        cx.notify();
11251    }
11252
11253    pub fn swap_selection_ends(
11254        &mut self,
11255        _: &actions::SwapSelectionEnds,
11256        window: &mut Window,
11257        cx: &mut Context<Self>,
11258    ) {
11259        self.change_selections(None, window, cx, |s| {
11260            s.move_with(|_, sel| {
11261                if sel.start != sel.end {
11262                    sel.reversed = !sel.reversed
11263                }
11264            });
11265        });
11266        self.request_autoscroll(Autoscroll::newest(), cx);
11267        cx.notify();
11268    }
11269
11270    pub fn toggle_fold(
11271        &mut self,
11272        _: &actions::ToggleFold,
11273        window: &mut Window,
11274        cx: &mut Context<Self>,
11275    ) {
11276        if self.is_singleton(cx) {
11277            let selection = self.selections.newest::<Point>(cx);
11278
11279            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11280            let range = if selection.is_empty() {
11281                let point = selection.head().to_display_point(&display_map);
11282                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11283                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11284                    .to_point(&display_map);
11285                start..end
11286            } else {
11287                selection.range()
11288            };
11289            if display_map.folds_in_range(range).next().is_some() {
11290                self.unfold_lines(&Default::default(), window, cx)
11291            } else {
11292                self.fold(&Default::default(), window, cx)
11293            }
11294        } else {
11295            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11296            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11297                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11298                .map(|(snapshot, _, _)| snapshot.remote_id())
11299                .collect();
11300
11301            for buffer_id in buffer_ids {
11302                if self.is_buffer_folded(buffer_id, cx) {
11303                    self.unfold_buffer(buffer_id, cx);
11304                } else {
11305                    self.fold_buffer(buffer_id, cx);
11306                }
11307            }
11308        }
11309    }
11310
11311    pub fn toggle_fold_recursive(
11312        &mut self,
11313        _: &actions::ToggleFoldRecursive,
11314        window: &mut Window,
11315        cx: &mut Context<Self>,
11316    ) {
11317        let selection = self.selections.newest::<Point>(cx);
11318
11319        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11320        let range = if selection.is_empty() {
11321            let point = selection.head().to_display_point(&display_map);
11322            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11323            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11324                .to_point(&display_map);
11325            start..end
11326        } else {
11327            selection.range()
11328        };
11329        if display_map.folds_in_range(range).next().is_some() {
11330            self.unfold_recursive(&Default::default(), window, cx)
11331        } else {
11332            self.fold_recursive(&Default::default(), window, cx)
11333        }
11334    }
11335
11336    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11337        if self.is_singleton(cx) {
11338            let mut to_fold = Vec::new();
11339            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11340            let selections = self.selections.all_adjusted(cx);
11341
11342            for selection in selections {
11343                let range = selection.range().sorted();
11344                let buffer_start_row = range.start.row;
11345
11346                if range.start.row != range.end.row {
11347                    let mut found = false;
11348                    let mut row = range.start.row;
11349                    while row <= range.end.row {
11350                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11351                        {
11352                            found = true;
11353                            row = crease.range().end.row + 1;
11354                            to_fold.push(crease);
11355                        } else {
11356                            row += 1
11357                        }
11358                    }
11359                    if found {
11360                        continue;
11361                    }
11362                }
11363
11364                for row in (0..=range.start.row).rev() {
11365                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11366                        if crease.range().end.row >= buffer_start_row {
11367                            to_fold.push(crease);
11368                            if row <= range.start.row {
11369                                break;
11370                            }
11371                        }
11372                    }
11373                }
11374            }
11375
11376            self.fold_creases(to_fold, true, window, cx);
11377        } else {
11378            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11379
11380            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11381                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11382                .map(|(snapshot, _, _)| snapshot.remote_id())
11383                .collect();
11384            for buffer_id in buffer_ids {
11385                self.fold_buffer(buffer_id, cx);
11386            }
11387        }
11388    }
11389
11390    fn fold_at_level(
11391        &mut self,
11392        fold_at: &FoldAtLevel,
11393        window: &mut Window,
11394        cx: &mut Context<Self>,
11395    ) {
11396        if !self.buffer.read(cx).is_singleton() {
11397            return;
11398        }
11399
11400        let fold_at_level = fold_at.level;
11401        let snapshot = self.buffer.read(cx).snapshot(cx);
11402        let mut to_fold = Vec::new();
11403        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11404
11405        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11406            while start_row < end_row {
11407                match self
11408                    .snapshot(window, cx)
11409                    .crease_for_buffer_row(MultiBufferRow(start_row))
11410                {
11411                    Some(crease) => {
11412                        let nested_start_row = crease.range().start.row + 1;
11413                        let nested_end_row = crease.range().end.row;
11414
11415                        if current_level < fold_at_level {
11416                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11417                        } else if current_level == fold_at_level {
11418                            to_fold.push(crease);
11419                        }
11420
11421                        start_row = nested_end_row + 1;
11422                    }
11423                    None => start_row += 1,
11424                }
11425            }
11426        }
11427
11428        self.fold_creases(to_fold, true, window, cx);
11429    }
11430
11431    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11432        if self.buffer.read(cx).is_singleton() {
11433            let mut fold_ranges = Vec::new();
11434            let snapshot = self.buffer.read(cx).snapshot(cx);
11435
11436            for row in 0..snapshot.max_row().0 {
11437                if let Some(foldable_range) = self
11438                    .snapshot(window, cx)
11439                    .crease_for_buffer_row(MultiBufferRow(row))
11440                {
11441                    fold_ranges.push(foldable_range);
11442                }
11443            }
11444
11445            self.fold_creases(fold_ranges, true, window, cx);
11446        } else {
11447            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11448                editor
11449                    .update_in(&mut cx, |editor, _, cx| {
11450                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11451                            editor.fold_buffer(buffer_id, cx);
11452                        }
11453                    })
11454                    .ok();
11455            });
11456        }
11457    }
11458
11459    pub fn fold_function_bodies(
11460        &mut self,
11461        _: &actions::FoldFunctionBodies,
11462        window: &mut Window,
11463        cx: &mut Context<Self>,
11464    ) {
11465        let snapshot = self.buffer.read(cx).snapshot(cx);
11466
11467        let ranges = snapshot
11468            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11469            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11470            .collect::<Vec<_>>();
11471
11472        let creases = ranges
11473            .into_iter()
11474            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11475            .collect();
11476
11477        self.fold_creases(creases, true, window, cx);
11478    }
11479
11480    pub fn fold_recursive(
11481        &mut self,
11482        _: &actions::FoldRecursive,
11483        window: &mut Window,
11484        cx: &mut Context<Self>,
11485    ) {
11486        let mut to_fold = Vec::new();
11487        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11488        let selections = self.selections.all_adjusted(cx);
11489
11490        for selection in selections {
11491            let range = selection.range().sorted();
11492            let buffer_start_row = range.start.row;
11493
11494            if range.start.row != range.end.row {
11495                let mut found = false;
11496                for row in range.start.row..=range.end.row {
11497                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11498                        found = true;
11499                        to_fold.push(crease);
11500                    }
11501                }
11502                if found {
11503                    continue;
11504                }
11505            }
11506
11507            for row in (0..=range.start.row).rev() {
11508                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11509                    if crease.range().end.row >= buffer_start_row {
11510                        to_fold.push(crease);
11511                    } else {
11512                        break;
11513                    }
11514                }
11515            }
11516        }
11517
11518        self.fold_creases(to_fold, true, window, cx);
11519    }
11520
11521    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11522        let buffer_row = fold_at.buffer_row;
11523        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11524
11525        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11526            let autoscroll = self
11527                .selections
11528                .all::<Point>(cx)
11529                .iter()
11530                .any(|selection| crease.range().overlaps(&selection.range()));
11531
11532            self.fold_creases(vec![crease], autoscroll, window, cx);
11533        }
11534    }
11535
11536    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11537        if self.is_singleton(cx) {
11538            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11539            let buffer = &display_map.buffer_snapshot;
11540            let selections = self.selections.all::<Point>(cx);
11541            let ranges = selections
11542                .iter()
11543                .map(|s| {
11544                    let range = s.display_range(&display_map).sorted();
11545                    let mut start = range.start.to_point(&display_map);
11546                    let mut end = range.end.to_point(&display_map);
11547                    start.column = 0;
11548                    end.column = buffer.line_len(MultiBufferRow(end.row));
11549                    start..end
11550                })
11551                .collect::<Vec<_>>();
11552
11553            self.unfold_ranges(&ranges, true, true, cx);
11554        } else {
11555            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11556            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11557                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11558                .map(|(snapshot, _, _)| snapshot.remote_id())
11559                .collect();
11560            for buffer_id in buffer_ids {
11561                self.unfold_buffer(buffer_id, cx);
11562            }
11563        }
11564    }
11565
11566    pub fn unfold_recursive(
11567        &mut self,
11568        _: &UnfoldRecursive,
11569        _window: &mut Window,
11570        cx: &mut Context<Self>,
11571    ) {
11572        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11573        let selections = self.selections.all::<Point>(cx);
11574        let ranges = selections
11575            .iter()
11576            .map(|s| {
11577                let mut range = s.display_range(&display_map).sorted();
11578                *range.start.column_mut() = 0;
11579                *range.end.column_mut() = display_map.line_len(range.end.row());
11580                let start = range.start.to_point(&display_map);
11581                let end = range.end.to_point(&display_map);
11582                start..end
11583            })
11584            .collect::<Vec<_>>();
11585
11586        self.unfold_ranges(&ranges, true, true, cx);
11587    }
11588
11589    pub fn unfold_at(
11590        &mut self,
11591        unfold_at: &UnfoldAt,
11592        _window: &mut Window,
11593        cx: &mut Context<Self>,
11594    ) {
11595        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11596
11597        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11598            ..Point::new(
11599                unfold_at.buffer_row.0,
11600                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11601            );
11602
11603        let autoscroll = self
11604            .selections
11605            .all::<Point>(cx)
11606            .iter()
11607            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11608
11609        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11610    }
11611
11612    pub fn unfold_all(
11613        &mut self,
11614        _: &actions::UnfoldAll,
11615        _window: &mut Window,
11616        cx: &mut Context<Self>,
11617    ) {
11618        if self.buffer.read(cx).is_singleton() {
11619            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11620            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11621        } else {
11622            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11623                editor
11624                    .update(&mut cx, |editor, cx| {
11625                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11626                            editor.unfold_buffer(buffer_id, cx);
11627                        }
11628                    })
11629                    .ok();
11630            });
11631        }
11632    }
11633
11634    pub fn fold_selected_ranges(
11635        &mut self,
11636        _: &FoldSelectedRanges,
11637        window: &mut Window,
11638        cx: &mut Context<Self>,
11639    ) {
11640        let selections = self.selections.all::<Point>(cx);
11641        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11642        let line_mode = self.selections.line_mode;
11643        let ranges = selections
11644            .into_iter()
11645            .map(|s| {
11646                if line_mode {
11647                    let start = Point::new(s.start.row, 0);
11648                    let end = Point::new(
11649                        s.end.row,
11650                        display_map
11651                            .buffer_snapshot
11652                            .line_len(MultiBufferRow(s.end.row)),
11653                    );
11654                    Crease::simple(start..end, display_map.fold_placeholder.clone())
11655                } else {
11656                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11657                }
11658            })
11659            .collect::<Vec<_>>();
11660        self.fold_creases(ranges, true, window, cx);
11661    }
11662
11663    pub fn fold_ranges<T: ToOffset + Clone>(
11664        &mut self,
11665        ranges: Vec<Range<T>>,
11666        auto_scroll: bool,
11667        window: &mut Window,
11668        cx: &mut Context<Self>,
11669    ) {
11670        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11671        let ranges = ranges
11672            .into_iter()
11673            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11674            .collect::<Vec<_>>();
11675        self.fold_creases(ranges, auto_scroll, window, cx);
11676    }
11677
11678    pub fn fold_creases<T: ToOffset + Clone>(
11679        &mut self,
11680        creases: Vec<Crease<T>>,
11681        auto_scroll: bool,
11682        window: &mut Window,
11683        cx: &mut Context<Self>,
11684    ) {
11685        if creases.is_empty() {
11686            return;
11687        }
11688
11689        let mut buffers_affected = HashSet::default();
11690        let multi_buffer = self.buffer().read(cx);
11691        for crease in &creases {
11692            if let Some((_, buffer, _)) =
11693                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11694            {
11695                buffers_affected.insert(buffer.read(cx).remote_id());
11696            };
11697        }
11698
11699        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11700
11701        if auto_scroll {
11702            self.request_autoscroll(Autoscroll::fit(), cx);
11703        }
11704
11705        cx.notify();
11706
11707        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11708            // Clear diagnostics block when folding a range that contains it.
11709            let snapshot = self.snapshot(window, cx);
11710            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11711                drop(snapshot);
11712                self.active_diagnostics = Some(active_diagnostics);
11713                self.dismiss_diagnostics(cx);
11714            } else {
11715                self.active_diagnostics = Some(active_diagnostics);
11716            }
11717        }
11718
11719        self.scrollbar_marker_state.dirty = true;
11720    }
11721
11722    /// Removes any folds whose ranges intersect any of the given ranges.
11723    pub fn unfold_ranges<T: ToOffset + Clone>(
11724        &mut self,
11725        ranges: &[Range<T>],
11726        inclusive: bool,
11727        auto_scroll: bool,
11728        cx: &mut Context<Self>,
11729    ) {
11730        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11731            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11732        });
11733    }
11734
11735    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11736        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11737            return;
11738        }
11739        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11740            return;
11741        };
11742        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11743        self.display_map
11744            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11745        cx.emit(EditorEvent::BufferFoldToggled {
11746            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11747            folded: true,
11748        });
11749        cx.notify();
11750    }
11751
11752    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11753        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11754            return;
11755        }
11756        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11757            return;
11758        };
11759        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11760        self.display_map.update(cx, |display_map, cx| {
11761            display_map.unfold_buffer(buffer_id, cx);
11762        });
11763        cx.emit(EditorEvent::BufferFoldToggled {
11764            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11765            folded: false,
11766        });
11767        cx.notify();
11768    }
11769
11770    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11771        self.display_map.read(cx).is_buffer_folded(buffer)
11772    }
11773
11774    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11775        self.display_map.read(cx).folded_buffers()
11776    }
11777
11778    /// Removes any folds with the given ranges.
11779    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11780        &mut self,
11781        ranges: &[Range<T>],
11782        type_id: TypeId,
11783        auto_scroll: bool,
11784        cx: &mut Context<Self>,
11785    ) {
11786        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11787            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11788        });
11789    }
11790
11791    fn remove_folds_with<T: ToOffset + Clone>(
11792        &mut self,
11793        ranges: &[Range<T>],
11794        auto_scroll: bool,
11795        cx: &mut Context<Self>,
11796        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11797    ) {
11798        if ranges.is_empty() {
11799            return;
11800        }
11801
11802        let mut buffers_affected = HashSet::default();
11803        let multi_buffer = self.buffer().read(cx);
11804        for range in ranges {
11805            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11806                buffers_affected.insert(buffer.read(cx).remote_id());
11807            };
11808        }
11809
11810        self.display_map.update(cx, update);
11811
11812        if auto_scroll {
11813            self.request_autoscroll(Autoscroll::fit(), cx);
11814        }
11815
11816        cx.notify();
11817        self.scrollbar_marker_state.dirty = true;
11818        self.active_indent_guides_state.dirty = true;
11819    }
11820
11821    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11822        self.display_map.read(cx).fold_placeholder.clone()
11823    }
11824
11825    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11826        self.buffer.update(cx, |buffer, cx| {
11827            buffer.set_all_diff_hunks_expanded(cx);
11828        });
11829    }
11830
11831    pub fn expand_all_diff_hunks(
11832        &mut self,
11833        _: &ExpandAllHunkDiffs,
11834        _window: &mut Window,
11835        cx: &mut Context<Self>,
11836    ) {
11837        self.buffer.update(cx, |buffer, cx| {
11838            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11839        });
11840    }
11841
11842    pub fn toggle_selected_diff_hunks(
11843        &mut self,
11844        _: &ToggleSelectedDiffHunks,
11845        _window: &mut Window,
11846        cx: &mut Context<Self>,
11847    ) {
11848        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11849        self.toggle_diff_hunks_in_ranges(ranges, cx);
11850    }
11851
11852    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11853        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11854        self.buffer
11855            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11856    }
11857
11858    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11859        self.buffer.update(cx, |buffer, cx| {
11860            let ranges = vec![Anchor::min()..Anchor::max()];
11861            if !buffer.all_diff_hunks_expanded()
11862                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11863            {
11864                buffer.collapse_diff_hunks(ranges, cx);
11865                true
11866            } else {
11867                false
11868            }
11869        })
11870    }
11871
11872    fn toggle_diff_hunks_in_ranges(
11873        &mut self,
11874        ranges: Vec<Range<Anchor>>,
11875        cx: &mut Context<'_, Editor>,
11876    ) {
11877        self.buffer.update(cx, |buffer, cx| {
11878            if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11879                buffer.collapse_diff_hunks(ranges, cx)
11880            } else {
11881                buffer.expand_diff_hunks(ranges, cx)
11882            }
11883        })
11884    }
11885
11886    pub(crate) fn apply_all_diff_hunks(
11887        &mut self,
11888        _: &ApplyAllDiffHunks,
11889        window: &mut Window,
11890        cx: &mut Context<Self>,
11891    ) {
11892        let buffers = self.buffer.read(cx).all_buffers();
11893        for branch_buffer in buffers {
11894            branch_buffer.update(cx, |branch_buffer, cx| {
11895                branch_buffer.merge_into_base(Vec::new(), cx);
11896            });
11897        }
11898
11899        if let Some(project) = self.project.clone() {
11900            self.save(true, project, window, cx).detach_and_log_err(cx);
11901        }
11902    }
11903
11904    pub(crate) fn apply_selected_diff_hunks(
11905        &mut self,
11906        _: &ApplyDiffHunk,
11907        window: &mut Window,
11908        cx: &mut Context<Self>,
11909    ) {
11910        let snapshot = self.snapshot(window, cx);
11911        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11912        let mut ranges_by_buffer = HashMap::default();
11913        self.transact(window, cx, |editor, _window, cx| {
11914            for hunk in hunks {
11915                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11916                    ranges_by_buffer
11917                        .entry(buffer.clone())
11918                        .or_insert_with(Vec::new)
11919                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11920                }
11921            }
11922
11923            for (buffer, ranges) in ranges_by_buffer {
11924                buffer.update(cx, |buffer, cx| {
11925                    buffer.merge_into_base(ranges, cx);
11926                });
11927            }
11928        });
11929
11930        if let Some(project) = self.project.clone() {
11931            self.save(true, project, window, cx).detach_and_log_err(cx);
11932        }
11933    }
11934
11935    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11936        if hovered != self.gutter_hovered {
11937            self.gutter_hovered = hovered;
11938            cx.notify();
11939        }
11940    }
11941
11942    pub fn insert_blocks(
11943        &mut self,
11944        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11945        autoscroll: Option<Autoscroll>,
11946        cx: &mut Context<Self>,
11947    ) -> Vec<CustomBlockId> {
11948        let blocks = self
11949            .display_map
11950            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11951        if let Some(autoscroll) = autoscroll {
11952            self.request_autoscroll(autoscroll, cx);
11953        }
11954        cx.notify();
11955        blocks
11956    }
11957
11958    pub fn resize_blocks(
11959        &mut self,
11960        heights: HashMap<CustomBlockId, u32>,
11961        autoscroll: Option<Autoscroll>,
11962        cx: &mut Context<Self>,
11963    ) {
11964        self.display_map
11965            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11966        if let Some(autoscroll) = autoscroll {
11967            self.request_autoscroll(autoscroll, cx);
11968        }
11969        cx.notify();
11970    }
11971
11972    pub fn replace_blocks(
11973        &mut self,
11974        renderers: HashMap<CustomBlockId, RenderBlock>,
11975        autoscroll: Option<Autoscroll>,
11976        cx: &mut Context<Self>,
11977    ) {
11978        self.display_map
11979            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11980        if let Some(autoscroll) = autoscroll {
11981            self.request_autoscroll(autoscroll, cx);
11982        }
11983        cx.notify();
11984    }
11985
11986    pub fn remove_blocks(
11987        &mut self,
11988        block_ids: HashSet<CustomBlockId>,
11989        autoscroll: Option<Autoscroll>,
11990        cx: &mut Context<Self>,
11991    ) {
11992        self.display_map.update(cx, |display_map, cx| {
11993            display_map.remove_blocks(block_ids, cx)
11994        });
11995        if let Some(autoscroll) = autoscroll {
11996            self.request_autoscroll(autoscroll, cx);
11997        }
11998        cx.notify();
11999    }
12000
12001    pub fn row_for_block(
12002        &self,
12003        block_id: CustomBlockId,
12004        cx: &mut Context<Self>,
12005    ) -> Option<DisplayRow> {
12006        self.display_map
12007            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12008    }
12009
12010    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12011        self.focused_block = Some(focused_block);
12012    }
12013
12014    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12015        self.focused_block.take()
12016    }
12017
12018    pub fn insert_creases(
12019        &mut self,
12020        creases: impl IntoIterator<Item = Crease<Anchor>>,
12021        cx: &mut Context<Self>,
12022    ) -> Vec<CreaseId> {
12023        self.display_map
12024            .update(cx, |map, cx| map.insert_creases(creases, cx))
12025    }
12026
12027    pub fn remove_creases(
12028        &mut self,
12029        ids: impl IntoIterator<Item = CreaseId>,
12030        cx: &mut Context<Self>,
12031    ) {
12032        self.display_map
12033            .update(cx, |map, cx| map.remove_creases(ids, cx));
12034    }
12035
12036    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12037        self.display_map
12038            .update(cx, |map, cx| map.snapshot(cx))
12039            .longest_row()
12040    }
12041
12042    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12043        self.display_map
12044            .update(cx, |map, cx| map.snapshot(cx))
12045            .max_point()
12046    }
12047
12048    pub fn text(&self, cx: &App) -> String {
12049        self.buffer.read(cx).read(cx).text()
12050    }
12051
12052    pub fn text_option(&self, cx: &App) -> Option<String> {
12053        let text = self.text(cx);
12054        let text = text.trim();
12055
12056        if text.is_empty() {
12057            return None;
12058        }
12059
12060        Some(text.to_string())
12061    }
12062
12063    pub fn set_text(
12064        &mut self,
12065        text: impl Into<Arc<str>>,
12066        window: &mut Window,
12067        cx: &mut Context<Self>,
12068    ) {
12069        self.transact(window, cx, |this, _, cx| {
12070            this.buffer
12071                .read(cx)
12072                .as_singleton()
12073                .expect("you can only call set_text on editors for singleton buffers")
12074                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12075        });
12076    }
12077
12078    pub fn display_text(&self, cx: &mut App) -> String {
12079        self.display_map
12080            .update(cx, |map, cx| map.snapshot(cx))
12081            .text()
12082    }
12083
12084    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12085        let mut wrap_guides = smallvec::smallvec![];
12086
12087        if self.show_wrap_guides == Some(false) {
12088            return wrap_guides;
12089        }
12090
12091        let settings = self.buffer.read(cx).settings_at(0, cx);
12092        if settings.show_wrap_guides {
12093            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12094                wrap_guides.push((soft_wrap as usize, true));
12095            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12096                wrap_guides.push((soft_wrap as usize, true));
12097            }
12098            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12099        }
12100
12101        wrap_guides
12102    }
12103
12104    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12105        let settings = self.buffer.read(cx).settings_at(0, cx);
12106        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12107        match mode {
12108            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12109                SoftWrap::None
12110            }
12111            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12112            language_settings::SoftWrap::PreferredLineLength => {
12113                SoftWrap::Column(settings.preferred_line_length)
12114            }
12115            language_settings::SoftWrap::Bounded => {
12116                SoftWrap::Bounded(settings.preferred_line_length)
12117            }
12118        }
12119    }
12120
12121    pub fn set_soft_wrap_mode(
12122        &mut self,
12123        mode: language_settings::SoftWrap,
12124
12125        cx: &mut Context<Self>,
12126    ) {
12127        self.soft_wrap_mode_override = Some(mode);
12128        cx.notify();
12129    }
12130
12131    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12132        self.text_style_refinement = Some(style);
12133    }
12134
12135    /// called by the Element so we know what style we were most recently rendered with.
12136    pub(crate) fn set_style(
12137        &mut self,
12138        style: EditorStyle,
12139        window: &mut Window,
12140        cx: &mut Context<Self>,
12141    ) {
12142        let rem_size = window.rem_size();
12143        self.display_map.update(cx, |map, cx| {
12144            map.set_font(
12145                style.text.font(),
12146                style.text.font_size.to_pixels(rem_size),
12147                cx,
12148            )
12149        });
12150        self.style = Some(style);
12151    }
12152
12153    pub fn style(&self) -> Option<&EditorStyle> {
12154        self.style.as_ref()
12155    }
12156
12157    // Called by the element. This method is not designed to be called outside of the editor
12158    // element's layout code because it does not notify when rewrapping is computed synchronously.
12159    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12160        self.display_map
12161            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12162    }
12163
12164    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12165        if self.soft_wrap_mode_override.is_some() {
12166            self.soft_wrap_mode_override.take();
12167        } else {
12168            let soft_wrap = match self.soft_wrap_mode(cx) {
12169                SoftWrap::GitDiff => return,
12170                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12171                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12172                    language_settings::SoftWrap::None
12173                }
12174            };
12175            self.soft_wrap_mode_override = Some(soft_wrap);
12176        }
12177        cx.notify();
12178    }
12179
12180    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12181        let Some(workspace) = self.workspace() else {
12182            return;
12183        };
12184        let fs = workspace.read(cx).app_state().fs.clone();
12185        let current_show = TabBarSettings::get_global(cx).show;
12186        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12187            setting.show = Some(!current_show);
12188        });
12189    }
12190
12191    pub fn toggle_indent_guides(
12192        &mut self,
12193        _: &ToggleIndentGuides,
12194        _: &mut Window,
12195        cx: &mut Context<Self>,
12196    ) {
12197        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12198            self.buffer
12199                .read(cx)
12200                .settings_at(0, cx)
12201                .indent_guides
12202                .enabled
12203        });
12204        self.show_indent_guides = Some(!currently_enabled);
12205        cx.notify();
12206    }
12207
12208    fn should_show_indent_guides(&self) -> Option<bool> {
12209        self.show_indent_guides
12210    }
12211
12212    pub fn toggle_line_numbers(
12213        &mut self,
12214        _: &ToggleLineNumbers,
12215        _: &mut Window,
12216        cx: &mut Context<Self>,
12217    ) {
12218        let mut editor_settings = EditorSettings::get_global(cx).clone();
12219        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12220        EditorSettings::override_global(editor_settings, cx);
12221    }
12222
12223    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12224        self.use_relative_line_numbers
12225            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12226    }
12227
12228    pub fn toggle_relative_line_numbers(
12229        &mut self,
12230        _: &ToggleRelativeLineNumbers,
12231        _: &mut Window,
12232        cx: &mut Context<Self>,
12233    ) {
12234        let is_relative = self.should_use_relative_line_numbers(cx);
12235        self.set_relative_line_number(Some(!is_relative), cx)
12236    }
12237
12238    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12239        self.use_relative_line_numbers = is_relative;
12240        cx.notify();
12241    }
12242
12243    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12244        self.show_gutter = show_gutter;
12245        cx.notify();
12246    }
12247
12248    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12249        self.show_scrollbars = show_scrollbars;
12250        cx.notify();
12251    }
12252
12253    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12254        self.show_line_numbers = Some(show_line_numbers);
12255        cx.notify();
12256    }
12257
12258    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12259        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12260        cx.notify();
12261    }
12262
12263    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12264        self.show_code_actions = Some(show_code_actions);
12265        cx.notify();
12266    }
12267
12268    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12269        self.show_runnables = Some(show_runnables);
12270        cx.notify();
12271    }
12272
12273    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12274        if self.display_map.read(cx).masked != masked {
12275            self.display_map.update(cx, |map, _| map.masked = masked);
12276        }
12277        cx.notify()
12278    }
12279
12280    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12281        self.show_wrap_guides = Some(show_wrap_guides);
12282        cx.notify();
12283    }
12284
12285    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12286        self.show_indent_guides = Some(show_indent_guides);
12287        cx.notify();
12288    }
12289
12290    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12291        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12292            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12293                if let Some(dir) = file.abs_path(cx).parent() {
12294                    return Some(dir.to_owned());
12295                }
12296            }
12297
12298            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12299                return Some(project_path.path.to_path_buf());
12300            }
12301        }
12302
12303        None
12304    }
12305
12306    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12307        self.active_excerpt(cx)?
12308            .1
12309            .read(cx)
12310            .file()
12311            .and_then(|f| f.as_local())
12312    }
12313
12314    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12315        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12316            let project_path = buffer.read(cx).project_path(cx)?;
12317            let project = self.project.as_ref()?.read(cx);
12318            project.absolute_path(&project_path, cx)
12319        })
12320    }
12321
12322    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12323        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12324            let project_path = buffer.read(cx).project_path(cx)?;
12325            let project = self.project.as_ref()?.read(cx);
12326            let entry = project.entry_for_path(&project_path, cx)?;
12327            let path = entry.path.to_path_buf();
12328            Some(path)
12329        })
12330    }
12331
12332    pub fn reveal_in_finder(
12333        &mut self,
12334        _: &RevealInFileManager,
12335        _window: &mut Window,
12336        cx: &mut Context<Self>,
12337    ) {
12338        if let Some(target) = self.target_file(cx) {
12339            cx.reveal_path(&target.abs_path(cx));
12340        }
12341    }
12342
12343    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12344        if let Some(path) = self.target_file_abs_path(cx) {
12345            if let Some(path) = path.to_str() {
12346                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12347            }
12348        }
12349    }
12350
12351    pub fn copy_relative_path(
12352        &mut self,
12353        _: &CopyRelativePath,
12354        _window: &mut Window,
12355        cx: &mut Context<Self>,
12356    ) {
12357        if let Some(path) = self.target_file_path(cx) {
12358            if let Some(path) = path.to_str() {
12359                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12360            }
12361        }
12362    }
12363
12364    pub fn toggle_git_blame(
12365        &mut self,
12366        _: &ToggleGitBlame,
12367        window: &mut Window,
12368        cx: &mut Context<Self>,
12369    ) {
12370        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12371
12372        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12373            self.start_git_blame(true, window, cx);
12374        }
12375
12376        cx.notify();
12377    }
12378
12379    pub fn toggle_git_blame_inline(
12380        &mut self,
12381        _: &ToggleGitBlameInline,
12382        window: &mut Window,
12383        cx: &mut Context<Self>,
12384    ) {
12385        self.toggle_git_blame_inline_internal(true, window, cx);
12386        cx.notify();
12387    }
12388
12389    pub fn git_blame_inline_enabled(&self) -> bool {
12390        self.git_blame_inline_enabled
12391    }
12392
12393    pub fn toggle_selection_menu(
12394        &mut self,
12395        _: &ToggleSelectionMenu,
12396        _: &mut Window,
12397        cx: &mut Context<Self>,
12398    ) {
12399        self.show_selection_menu = self
12400            .show_selection_menu
12401            .map(|show_selections_menu| !show_selections_menu)
12402            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12403
12404        cx.notify();
12405    }
12406
12407    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12408        self.show_selection_menu
12409            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12410    }
12411
12412    fn start_git_blame(
12413        &mut self,
12414        user_triggered: bool,
12415        window: &mut Window,
12416        cx: &mut Context<Self>,
12417    ) {
12418        if let Some(project) = self.project.as_ref() {
12419            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12420                return;
12421            };
12422
12423            if buffer.read(cx).file().is_none() {
12424                return;
12425            }
12426
12427            let focused = self.focus_handle(cx).contains_focused(window, cx);
12428
12429            let project = project.clone();
12430            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12431            self.blame_subscription =
12432                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12433            self.blame = Some(blame);
12434        }
12435    }
12436
12437    fn toggle_git_blame_inline_internal(
12438        &mut self,
12439        user_triggered: bool,
12440        window: &mut Window,
12441        cx: &mut Context<Self>,
12442    ) {
12443        if self.git_blame_inline_enabled {
12444            self.git_blame_inline_enabled = false;
12445            self.show_git_blame_inline = false;
12446            self.show_git_blame_inline_delay_task.take();
12447        } else {
12448            self.git_blame_inline_enabled = true;
12449            self.start_git_blame_inline(user_triggered, window, cx);
12450        }
12451
12452        cx.notify();
12453    }
12454
12455    fn start_git_blame_inline(
12456        &mut self,
12457        user_triggered: bool,
12458        window: &mut Window,
12459        cx: &mut Context<Self>,
12460    ) {
12461        self.start_git_blame(user_triggered, window, cx);
12462
12463        if ProjectSettings::get_global(cx)
12464            .git
12465            .inline_blame_delay()
12466            .is_some()
12467        {
12468            self.start_inline_blame_timer(window, cx);
12469        } else {
12470            self.show_git_blame_inline = true
12471        }
12472    }
12473
12474    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12475        self.blame.as_ref()
12476    }
12477
12478    pub fn show_git_blame_gutter(&self) -> bool {
12479        self.show_git_blame_gutter
12480    }
12481
12482    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12483        self.show_git_blame_gutter && self.has_blame_entries(cx)
12484    }
12485
12486    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12487        self.show_git_blame_inline
12488            && self.focus_handle.is_focused(window)
12489            && !self.newest_selection_head_on_empty_line(cx)
12490            && self.has_blame_entries(cx)
12491    }
12492
12493    fn has_blame_entries(&self, cx: &App) -> bool {
12494        self.blame()
12495            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12496    }
12497
12498    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12499        let cursor_anchor = self.selections.newest_anchor().head();
12500
12501        let snapshot = self.buffer.read(cx).snapshot(cx);
12502        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12503
12504        snapshot.line_len(buffer_row) == 0
12505    }
12506
12507    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12508        let buffer_and_selection = maybe!({
12509            let selection = self.selections.newest::<Point>(cx);
12510            let selection_range = selection.range();
12511
12512            let multi_buffer = self.buffer().read(cx);
12513            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12514            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12515
12516            let (buffer, range, _) = if selection.reversed {
12517                buffer_ranges.first()
12518            } else {
12519                buffer_ranges.last()
12520            }?;
12521
12522            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12523                ..text::ToPoint::to_point(&range.end, &buffer).row;
12524            Some((
12525                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12526                selection,
12527            ))
12528        });
12529
12530        let Some((buffer, selection)) = buffer_and_selection else {
12531            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12532        };
12533
12534        let Some(project) = self.project.as_ref() else {
12535            return Task::ready(Err(anyhow!("editor does not have project")));
12536        };
12537
12538        project.update(cx, |project, cx| {
12539            project.get_permalink_to_line(&buffer, selection, cx)
12540        })
12541    }
12542
12543    pub fn copy_permalink_to_line(
12544        &mut self,
12545        _: &CopyPermalinkToLine,
12546        window: &mut Window,
12547        cx: &mut Context<Self>,
12548    ) {
12549        let permalink_task = self.get_permalink_to_line(cx);
12550        let workspace = self.workspace();
12551
12552        cx.spawn_in(window, |_, mut cx| async move {
12553            match permalink_task.await {
12554                Ok(permalink) => {
12555                    cx.update(|_, cx| {
12556                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12557                    })
12558                    .ok();
12559                }
12560                Err(err) => {
12561                    let message = format!("Failed to copy permalink: {err}");
12562
12563                    Err::<(), anyhow::Error>(err).log_err();
12564
12565                    if let Some(workspace) = workspace {
12566                        workspace
12567                            .update_in(&mut cx, |workspace, _, cx| {
12568                                struct CopyPermalinkToLine;
12569
12570                                workspace.show_toast(
12571                                    Toast::new(
12572                                        NotificationId::unique::<CopyPermalinkToLine>(),
12573                                        message,
12574                                    ),
12575                                    cx,
12576                                )
12577                            })
12578                            .ok();
12579                    }
12580                }
12581            }
12582        })
12583        .detach();
12584    }
12585
12586    pub fn copy_file_location(
12587        &mut self,
12588        _: &CopyFileLocation,
12589        _: &mut Window,
12590        cx: &mut Context<Self>,
12591    ) {
12592        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12593        if let Some(file) = self.target_file(cx) {
12594            if let Some(path) = file.path().to_str() {
12595                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12596            }
12597        }
12598    }
12599
12600    pub fn open_permalink_to_line(
12601        &mut self,
12602        _: &OpenPermalinkToLine,
12603        window: &mut Window,
12604        cx: &mut Context<Self>,
12605    ) {
12606        let permalink_task = self.get_permalink_to_line(cx);
12607        let workspace = self.workspace();
12608
12609        cx.spawn_in(window, |_, mut cx| async move {
12610            match permalink_task.await {
12611                Ok(permalink) => {
12612                    cx.update(|_, cx| {
12613                        cx.open_url(permalink.as_ref());
12614                    })
12615                    .ok();
12616                }
12617                Err(err) => {
12618                    let message = format!("Failed to open permalink: {err}");
12619
12620                    Err::<(), anyhow::Error>(err).log_err();
12621
12622                    if let Some(workspace) = workspace {
12623                        workspace
12624                            .update(&mut cx, |workspace, cx| {
12625                                struct OpenPermalinkToLine;
12626
12627                                workspace.show_toast(
12628                                    Toast::new(
12629                                        NotificationId::unique::<OpenPermalinkToLine>(),
12630                                        message,
12631                                    ),
12632                                    cx,
12633                                )
12634                            })
12635                            .ok();
12636                    }
12637                }
12638            }
12639        })
12640        .detach();
12641    }
12642
12643    pub fn insert_uuid_v4(
12644        &mut self,
12645        _: &InsertUuidV4,
12646        window: &mut Window,
12647        cx: &mut Context<Self>,
12648    ) {
12649        self.insert_uuid(UuidVersion::V4, window, cx);
12650    }
12651
12652    pub fn insert_uuid_v7(
12653        &mut self,
12654        _: &InsertUuidV7,
12655        window: &mut Window,
12656        cx: &mut Context<Self>,
12657    ) {
12658        self.insert_uuid(UuidVersion::V7, window, cx);
12659    }
12660
12661    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12662        self.transact(window, cx, |this, window, cx| {
12663            let edits = this
12664                .selections
12665                .all::<Point>(cx)
12666                .into_iter()
12667                .map(|selection| {
12668                    let uuid = match version {
12669                        UuidVersion::V4 => uuid::Uuid::new_v4(),
12670                        UuidVersion::V7 => uuid::Uuid::now_v7(),
12671                    };
12672
12673                    (selection.range(), uuid.to_string())
12674                });
12675            this.edit(edits, cx);
12676            this.refresh_inline_completion(true, false, window, cx);
12677        });
12678    }
12679
12680    pub fn open_selections_in_multibuffer(
12681        &mut self,
12682        _: &OpenSelectionsInMultibuffer,
12683        window: &mut Window,
12684        cx: &mut Context<Self>,
12685    ) {
12686        let multibuffer = self.buffer.read(cx);
12687
12688        let Some(buffer) = multibuffer.as_singleton() else {
12689            return;
12690        };
12691
12692        let Some(workspace) = self.workspace() else {
12693            return;
12694        };
12695
12696        let locations = self
12697            .selections
12698            .disjoint_anchors()
12699            .iter()
12700            .map(|range| Location {
12701                buffer: buffer.clone(),
12702                range: range.start.text_anchor..range.end.text_anchor,
12703            })
12704            .collect::<Vec<_>>();
12705
12706        let title = multibuffer.title(cx).to_string();
12707
12708        cx.spawn_in(window, |_, mut cx| async move {
12709            workspace.update_in(&mut cx, |workspace, window, cx| {
12710                Self::open_locations_in_multibuffer(
12711                    workspace,
12712                    locations,
12713                    format!("Selections for '{title}'"),
12714                    false,
12715                    MultibufferSelectionMode::All,
12716                    window,
12717                    cx,
12718                );
12719            })
12720        })
12721        .detach();
12722    }
12723
12724    /// Adds a row highlight for the given range. If a row has multiple highlights, the
12725    /// last highlight added will be used.
12726    ///
12727    /// If the range ends at the beginning of a line, then that line will not be highlighted.
12728    pub fn highlight_rows<T: 'static>(
12729        &mut self,
12730        range: Range<Anchor>,
12731        color: Hsla,
12732        should_autoscroll: bool,
12733        cx: &mut Context<Self>,
12734    ) {
12735        let snapshot = self.buffer().read(cx).snapshot(cx);
12736        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12737        let ix = row_highlights.binary_search_by(|highlight| {
12738            Ordering::Equal
12739                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12740                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12741        });
12742
12743        if let Err(mut ix) = ix {
12744            let index = post_inc(&mut self.highlight_order);
12745
12746            // If this range intersects with the preceding highlight, then merge it with
12747            // the preceding highlight. Otherwise insert a new highlight.
12748            let mut merged = false;
12749            if ix > 0 {
12750                let prev_highlight = &mut row_highlights[ix - 1];
12751                if prev_highlight
12752                    .range
12753                    .end
12754                    .cmp(&range.start, &snapshot)
12755                    .is_ge()
12756                {
12757                    ix -= 1;
12758                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12759                        prev_highlight.range.end = range.end;
12760                    }
12761                    merged = true;
12762                    prev_highlight.index = index;
12763                    prev_highlight.color = color;
12764                    prev_highlight.should_autoscroll = should_autoscroll;
12765                }
12766            }
12767
12768            if !merged {
12769                row_highlights.insert(
12770                    ix,
12771                    RowHighlight {
12772                        range: range.clone(),
12773                        index,
12774                        color,
12775                        should_autoscroll,
12776                    },
12777                );
12778            }
12779
12780            // If any of the following highlights intersect with this one, merge them.
12781            while let Some(next_highlight) = row_highlights.get(ix + 1) {
12782                let highlight = &row_highlights[ix];
12783                if next_highlight
12784                    .range
12785                    .start
12786                    .cmp(&highlight.range.end, &snapshot)
12787                    .is_le()
12788                {
12789                    if next_highlight
12790                        .range
12791                        .end
12792                        .cmp(&highlight.range.end, &snapshot)
12793                        .is_gt()
12794                    {
12795                        row_highlights[ix].range.end = next_highlight.range.end;
12796                    }
12797                    row_highlights.remove(ix + 1);
12798                } else {
12799                    break;
12800                }
12801            }
12802        }
12803    }
12804
12805    /// Remove any highlighted row ranges of the given type that intersect the
12806    /// given ranges.
12807    pub fn remove_highlighted_rows<T: 'static>(
12808        &mut self,
12809        ranges_to_remove: Vec<Range<Anchor>>,
12810        cx: &mut Context<Self>,
12811    ) {
12812        let snapshot = self.buffer().read(cx).snapshot(cx);
12813        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12814        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12815        row_highlights.retain(|highlight| {
12816            while let Some(range_to_remove) = ranges_to_remove.peek() {
12817                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12818                    Ordering::Less | Ordering::Equal => {
12819                        ranges_to_remove.next();
12820                    }
12821                    Ordering::Greater => {
12822                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12823                            Ordering::Less | Ordering::Equal => {
12824                                return false;
12825                            }
12826                            Ordering::Greater => break,
12827                        }
12828                    }
12829                }
12830            }
12831
12832            true
12833        })
12834    }
12835
12836    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12837    pub fn clear_row_highlights<T: 'static>(&mut self) {
12838        self.highlighted_rows.remove(&TypeId::of::<T>());
12839    }
12840
12841    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12842    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12843        self.highlighted_rows
12844            .get(&TypeId::of::<T>())
12845            .map_or(&[] as &[_], |vec| vec.as_slice())
12846            .iter()
12847            .map(|highlight| (highlight.range.clone(), highlight.color))
12848    }
12849
12850    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12851    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12852    /// Allows to ignore certain kinds of highlights.
12853    pub fn highlighted_display_rows(
12854        &self,
12855        window: &mut Window,
12856        cx: &mut App,
12857    ) -> BTreeMap<DisplayRow, Hsla> {
12858        let snapshot = self.snapshot(window, cx);
12859        let mut used_highlight_orders = HashMap::default();
12860        self.highlighted_rows
12861            .iter()
12862            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12863            .fold(
12864                BTreeMap::<DisplayRow, Hsla>::new(),
12865                |mut unique_rows, highlight| {
12866                    let start = highlight.range.start.to_display_point(&snapshot);
12867                    let end = highlight.range.end.to_display_point(&snapshot);
12868                    let start_row = start.row().0;
12869                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12870                        && end.column() == 0
12871                    {
12872                        end.row().0.saturating_sub(1)
12873                    } else {
12874                        end.row().0
12875                    };
12876                    for row in start_row..=end_row {
12877                        let used_index =
12878                            used_highlight_orders.entry(row).or_insert(highlight.index);
12879                        if highlight.index >= *used_index {
12880                            *used_index = highlight.index;
12881                            unique_rows.insert(DisplayRow(row), highlight.color);
12882                        }
12883                    }
12884                    unique_rows
12885                },
12886            )
12887    }
12888
12889    pub fn highlighted_display_row_for_autoscroll(
12890        &self,
12891        snapshot: &DisplaySnapshot,
12892    ) -> Option<DisplayRow> {
12893        self.highlighted_rows
12894            .values()
12895            .flat_map(|highlighted_rows| highlighted_rows.iter())
12896            .filter_map(|highlight| {
12897                if highlight.should_autoscroll {
12898                    Some(highlight.range.start.to_display_point(snapshot).row())
12899                } else {
12900                    None
12901                }
12902            })
12903            .min()
12904    }
12905
12906    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12907        self.highlight_background::<SearchWithinRange>(
12908            ranges,
12909            |colors| colors.editor_document_highlight_read_background,
12910            cx,
12911        )
12912    }
12913
12914    pub fn set_breadcrumb_header(&mut self, new_header: String) {
12915        self.breadcrumb_header = Some(new_header);
12916    }
12917
12918    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12919        self.clear_background_highlights::<SearchWithinRange>(cx);
12920    }
12921
12922    pub fn highlight_background<T: 'static>(
12923        &mut self,
12924        ranges: &[Range<Anchor>],
12925        color_fetcher: fn(&ThemeColors) -> Hsla,
12926        cx: &mut Context<Self>,
12927    ) {
12928        self.background_highlights
12929            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12930        self.scrollbar_marker_state.dirty = true;
12931        cx.notify();
12932    }
12933
12934    pub fn clear_background_highlights<T: 'static>(
12935        &mut self,
12936        cx: &mut Context<Self>,
12937    ) -> Option<BackgroundHighlight> {
12938        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12939        if !text_highlights.1.is_empty() {
12940            self.scrollbar_marker_state.dirty = true;
12941            cx.notify();
12942        }
12943        Some(text_highlights)
12944    }
12945
12946    pub fn highlight_gutter<T: 'static>(
12947        &mut self,
12948        ranges: &[Range<Anchor>],
12949        color_fetcher: fn(&App) -> Hsla,
12950        cx: &mut Context<Self>,
12951    ) {
12952        self.gutter_highlights
12953            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12954        cx.notify();
12955    }
12956
12957    pub fn clear_gutter_highlights<T: 'static>(
12958        &mut self,
12959        cx: &mut Context<Self>,
12960    ) -> Option<GutterHighlight> {
12961        cx.notify();
12962        self.gutter_highlights.remove(&TypeId::of::<T>())
12963    }
12964
12965    #[cfg(feature = "test-support")]
12966    pub fn all_text_background_highlights(
12967        &self,
12968        window: &mut Window,
12969        cx: &mut Context<Self>,
12970    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12971        let snapshot = self.snapshot(window, cx);
12972        let buffer = &snapshot.buffer_snapshot;
12973        let start = buffer.anchor_before(0);
12974        let end = buffer.anchor_after(buffer.len());
12975        let theme = cx.theme().colors();
12976        self.background_highlights_in_range(start..end, &snapshot, theme)
12977    }
12978
12979    #[cfg(feature = "test-support")]
12980    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12981        let snapshot = self.buffer().read(cx).snapshot(cx);
12982
12983        let highlights = self
12984            .background_highlights
12985            .get(&TypeId::of::<items::BufferSearchHighlights>());
12986
12987        if let Some((_color, ranges)) = highlights {
12988            ranges
12989                .iter()
12990                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12991                .collect_vec()
12992        } else {
12993            vec![]
12994        }
12995    }
12996
12997    fn document_highlights_for_position<'a>(
12998        &'a self,
12999        position: Anchor,
13000        buffer: &'a MultiBufferSnapshot,
13001    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13002        let read_highlights = self
13003            .background_highlights
13004            .get(&TypeId::of::<DocumentHighlightRead>())
13005            .map(|h| &h.1);
13006        let write_highlights = self
13007            .background_highlights
13008            .get(&TypeId::of::<DocumentHighlightWrite>())
13009            .map(|h| &h.1);
13010        let left_position = position.bias_left(buffer);
13011        let right_position = position.bias_right(buffer);
13012        read_highlights
13013            .into_iter()
13014            .chain(write_highlights)
13015            .flat_map(move |ranges| {
13016                let start_ix = match ranges.binary_search_by(|probe| {
13017                    let cmp = probe.end.cmp(&left_position, buffer);
13018                    if cmp.is_ge() {
13019                        Ordering::Greater
13020                    } else {
13021                        Ordering::Less
13022                    }
13023                }) {
13024                    Ok(i) | Err(i) => i,
13025                };
13026
13027                ranges[start_ix..]
13028                    .iter()
13029                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13030            })
13031    }
13032
13033    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13034        self.background_highlights
13035            .get(&TypeId::of::<T>())
13036            .map_or(false, |(_, highlights)| !highlights.is_empty())
13037    }
13038
13039    pub fn background_highlights_in_range(
13040        &self,
13041        search_range: Range<Anchor>,
13042        display_snapshot: &DisplaySnapshot,
13043        theme: &ThemeColors,
13044    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13045        let mut results = Vec::new();
13046        for (color_fetcher, ranges) in self.background_highlights.values() {
13047            let color = color_fetcher(theme);
13048            let start_ix = match ranges.binary_search_by(|probe| {
13049                let cmp = probe
13050                    .end
13051                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13052                if cmp.is_gt() {
13053                    Ordering::Greater
13054                } else {
13055                    Ordering::Less
13056                }
13057            }) {
13058                Ok(i) | Err(i) => i,
13059            };
13060            for range in &ranges[start_ix..] {
13061                if range
13062                    .start
13063                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13064                    .is_ge()
13065                {
13066                    break;
13067                }
13068
13069                let start = range.start.to_display_point(display_snapshot);
13070                let end = range.end.to_display_point(display_snapshot);
13071                results.push((start..end, color))
13072            }
13073        }
13074        results
13075    }
13076
13077    pub fn background_highlight_row_ranges<T: 'static>(
13078        &self,
13079        search_range: Range<Anchor>,
13080        display_snapshot: &DisplaySnapshot,
13081        count: usize,
13082    ) -> Vec<RangeInclusive<DisplayPoint>> {
13083        let mut results = Vec::new();
13084        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13085            return vec![];
13086        };
13087
13088        let start_ix = match ranges.binary_search_by(|probe| {
13089            let cmp = probe
13090                .end
13091                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13092            if cmp.is_gt() {
13093                Ordering::Greater
13094            } else {
13095                Ordering::Less
13096            }
13097        }) {
13098            Ok(i) | Err(i) => i,
13099        };
13100        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13101            if let (Some(start_display), Some(end_display)) = (start, end) {
13102                results.push(
13103                    start_display.to_display_point(display_snapshot)
13104                        ..=end_display.to_display_point(display_snapshot),
13105                );
13106            }
13107        };
13108        let mut start_row: Option<Point> = None;
13109        let mut end_row: Option<Point> = None;
13110        if ranges.len() > count {
13111            return Vec::new();
13112        }
13113        for range in &ranges[start_ix..] {
13114            if range
13115                .start
13116                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13117                .is_ge()
13118            {
13119                break;
13120            }
13121            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13122            if let Some(current_row) = &end_row {
13123                if end.row == current_row.row {
13124                    continue;
13125                }
13126            }
13127            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13128            if start_row.is_none() {
13129                assert_eq!(end_row, None);
13130                start_row = Some(start);
13131                end_row = Some(end);
13132                continue;
13133            }
13134            if let Some(current_end) = end_row.as_mut() {
13135                if start.row > current_end.row + 1 {
13136                    push_region(start_row, end_row);
13137                    start_row = Some(start);
13138                    end_row = Some(end);
13139                } else {
13140                    // Merge two hunks.
13141                    *current_end = end;
13142                }
13143            } else {
13144                unreachable!();
13145            }
13146        }
13147        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13148        push_region(start_row, end_row);
13149        results
13150    }
13151
13152    pub fn gutter_highlights_in_range(
13153        &self,
13154        search_range: Range<Anchor>,
13155        display_snapshot: &DisplaySnapshot,
13156        cx: &App,
13157    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13158        let mut results = Vec::new();
13159        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13160            let color = color_fetcher(cx);
13161            let start_ix = match ranges.binary_search_by(|probe| {
13162                let cmp = probe
13163                    .end
13164                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13165                if cmp.is_gt() {
13166                    Ordering::Greater
13167                } else {
13168                    Ordering::Less
13169                }
13170            }) {
13171                Ok(i) | Err(i) => i,
13172            };
13173            for range in &ranges[start_ix..] {
13174                if range
13175                    .start
13176                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13177                    .is_ge()
13178                {
13179                    break;
13180                }
13181
13182                let start = range.start.to_display_point(display_snapshot);
13183                let end = range.end.to_display_point(display_snapshot);
13184                results.push((start..end, color))
13185            }
13186        }
13187        results
13188    }
13189
13190    /// Get the text ranges corresponding to the redaction query
13191    pub fn redacted_ranges(
13192        &self,
13193        search_range: Range<Anchor>,
13194        display_snapshot: &DisplaySnapshot,
13195        cx: &App,
13196    ) -> Vec<Range<DisplayPoint>> {
13197        display_snapshot
13198            .buffer_snapshot
13199            .redacted_ranges(search_range, |file| {
13200                if let Some(file) = file {
13201                    file.is_private()
13202                        && EditorSettings::get(
13203                            Some(SettingsLocation {
13204                                worktree_id: file.worktree_id(cx),
13205                                path: file.path().as_ref(),
13206                            }),
13207                            cx,
13208                        )
13209                        .redact_private_values
13210                } else {
13211                    false
13212                }
13213            })
13214            .map(|range| {
13215                range.start.to_display_point(display_snapshot)
13216                    ..range.end.to_display_point(display_snapshot)
13217            })
13218            .collect()
13219    }
13220
13221    pub fn highlight_text<T: 'static>(
13222        &mut self,
13223        ranges: Vec<Range<Anchor>>,
13224        style: HighlightStyle,
13225        cx: &mut Context<Self>,
13226    ) {
13227        self.display_map.update(cx, |map, _| {
13228            map.highlight_text(TypeId::of::<T>(), ranges, style)
13229        });
13230        cx.notify();
13231    }
13232
13233    pub(crate) fn highlight_inlays<T: 'static>(
13234        &mut self,
13235        highlights: Vec<InlayHighlight>,
13236        style: HighlightStyle,
13237        cx: &mut Context<Self>,
13238    ) {
13239        self.display_map.update(cx, |map, _| {
13240            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13241        });
13242        cx.notify();
13243    }
13244
13245    pub fn text_highlights<'a, T: 'static>(
13246        &'a self,
13247        cx: &'a App,
13248    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13249        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13250    }
13251
13252    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13253        let cleared = self
13254            .display_map
13255            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13256        if cleared {
13257            cx.notify();
13258        }
13259    }
13260
13261    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13262        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13263            && self.focus_handle.is_focused(window)
13264    }
13265
13266    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13267        self.show_cursor_when_unfocused = is_enabled;
13268        cx.notify();
13269    }
13270
13271    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13272        self.project
13273            .as_ref()
13274            .map(|project| project.read(cx).lsp_store())
13275    }
13276
13277    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13278        cx.notify();
13279    }
13280
13281    fn on_buffer_event(
13282        &mut self,
13283        multibuffer: &Entity<MultiBuffer>,
13284        event: &multi_buffer::Event,
13285        window: &mut Window,
13286        cx: &mut Context<Self>,
13287    ) {
13288        match event {
13289            multi_buffer::Event::Edited {
13290                singleton_buffer_edited,
13291                edited_buffer: buffer_edited,
13292            } => {
13293                self.scrollbar_marker_state.dirty = true;
13294                self.active_indent_guides_state.dirty = true;
13295                self.refresh_active_diagnostics(cx);
13296                self.refresh_code_actions(window, cx);
13297                if self.has_active_inline_completion() {
13298                    self.update_visible_inline_completion(window, cx);
13299                }
13300                if let Some(buffer) = buffer_edited {
13301                    let buffer_id = buffer.read(cx).remote_id();
13302                    if !self.registered_buffers.contains_key(&buffer_id) {
13303                        if let Some(lsp_store) = self.lsp_store(cx) {
13304                            lsp_store.update(cx, |lsp_store, cx| {
13305                                self.registered_buffers.insert(
13306                                    buffer_id,
13307                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13308                                );
13309                            })
13310                        }
13311                    }
13312                }
13313                cx.emit(EditorEvent::BufferEdited);
13314                cx.emit(SearchEvent::MatchesInvalidated);
13315                if *singleton_buffer_edited {
13316                    if let Some(project) = &self.project {
13317                        let project = project.read(cx);
13318                        #[allow(clippy::mutable_key_type)]
13319                        let languages_affected = multibuffer
13320                            .read(cx)
13321                            .all_buffers()
13322                            .into_iter()
13323                            .filter_map(|buffer| {
13324                                let buffer = buffer.read(cx);
13325                                let language = buffer.language()?;
13326                                if project.is_local()
13327                                    && project
13328                                        .language_servers_for_local_buffer(buffer, cx)
13329                                        .count()
13330                                        == 0
13331                                {
13332                                    None
13333                                } else {
13334                                    Some(language)
13335                                }
13336                            })
13337                            .cloned()
13338                            .collect::<HashSet<_>>();
13339                        if !languages_affected.is_empty() {
13340                            self.refresh_inlay_hints(
13341                                InlayHintRefreshReason::BufferEdited(languages_affected),
13342                                cx,
13343                            );
13344                        }
13345                    }
13346                }
13347
13348                let Some(project) = &self.project else { return };
13349                let (telemetry, is_via_ssh) = {
13350                    let project = project.read(cx);
13351                    let telemetry = project.client().telemetry().clone();
13352                    let is_via_ssh = project.is_via_ssh();
13353                    (telemetry, is_via_ssh)
13354                };
13355                refresh_linked_ranges(self, window, cx);
13356                telemetry.log_edit_event("editor", is_via_ssh);
13357            }
13358            multi_buffer::Event::ExcerptsAdded {
13359                buffer,
13360                predecessor,
13361                excerpts,
13362            } => {
13363                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13364                let buffer_id = buffer.read(cx).remote_id();
13365                if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13366                    if let Some(project) = &self.project {
13367                        get_unstaged_changes_for_buffers(
13368                            project,
13369                            [buffer.clone()],
13370                            self.buffer.clone(),
13371                            cx,
13372                        );
13373                    }
13374                }
13375                cx.emit(EditorEvent::ExcerptsAdded {
13376                    buffer: buffer.clone(),
13377                    predecessor: *predecessor,
13378                    excerpts: excerpts.clone(),
13379                });
13380                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13381            }
13382            multi_buffer::Event::ExcerptsRemoved { ids } => {
13383                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13384                let buffer = self.buffer.read(cx);
13385                self.registered_buffers
13386                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13387                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13388            }
13389            multi_buffer::Event::ExcerptsEdited { ids } => {
13390                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13391            }
13392            multi_buffer::Event::ExcerptsExpanded { ids } => {
13393                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13394                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13395            }
13396            multi_buffer::Event::Reparsed(buffer_id) => {
13397                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13398
13399                cx.emit(EditorEvent::Reparsed(*buffer_id));
13400            }
13401            multi_buffer::Event::DiffHunksToggled => {
13402                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13403            }
13404            multi_buffer::Event::LanguageChanged(buffer_id) => {
13405                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13406                cx.emit(EditorEvent::Reparsed(*buffer_id));
13407                cx.notify();
13408            }
13409            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13410            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13411            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13412                cx.emit(EditorEvent::TitleChanged)
13413            }
13414            // multi_buffer::Event::DiffBaseChanged => {
13415            //     self.scrollbar_marker_state.dirty = true;
13416            //     cx.emit(EditorEvent::DiffBaseChanged);
13417            //     cx.notify();
13418            // }
13419            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13420            multi_buffer::Event::DiagnosticsUpdated => {
13421                self.refresh_active_diagnostics(cx);
13422                self.scrollbar_marker_state.dirty = true;
13423                cx.notify();
13424            }
13425            _ => {}
13426        };
13427    }
13428
13429    fn on_display_map_changed(
13430        &mut self,
13431        _: Entity<DisplayMap>,
13432        _: &mut Window,
13433        cx: &mut Context<Self>,
13434    ) {
13435        cx.notify();
13436    }
13437
13438    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13439        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13440        self.refresh_inline_completion(true, false, window, cx);
13441        self.refresh_inlay_hints(
13442            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13443                self.selections.newest_anchor().head(),
13444                &self.buffer.read(cx).snapshot(cx),
13445                cx,
13446            )),
13447            cx,
13448        );
13449
13450        let old_cursor_shape = self.cursor_shape;
13451
13452        {
13453            let editor_settings = EditorSettings::get_global(cx);
13454            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13455            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13456            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13457        }
13458
13459        if old_cursor_shape != self.cursor_shape {
13460            cx.emit(EditorEvent::CursorShapeChanged);
13461        }
13462
13463        let project_settings = ProjectSettings::get_global(cx);
13464        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13465
13466        if self.mode == EditorMode::Full {
13467            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13468            if self.git_blame_inline_enabled != inline_blame_enabled {
13469                self.toggle_git_blame_inline_internal(false, window, cx);
13470            }
13471        }
13472
13473        cx.notify();
13474    }
13475
13476    pub fn set_searchable(&mut self, searchable: bool) {
13477        self.searchable = searchable;
13478    }
13479
13480    pub fn searchable(&self) -> bool {
13481        self.searchable
13482    }
13483
13484    fn open_proposed_changes_editor(
13485        &mut self,
13486        _: &OpenProposedChangesEditor,
13487        window: &mut Window,
13488        cx: &mut Context<Self>,
13489    ) {
13490        let Some(workspace) = self.workspace() else {
13491            cx.propagate();
13492            return;
13493        };
13494
13495        let selections = self.selections.all::<usize>(cx);
13496        let multi_buffer = self.buffer.read(cx);
13497        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13498        let mut new_selections_by_buffer = HashMap::default();
13499        for selection in selections {
13500            for (buffer, range, _) in
13501                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13502            {
13503                let mut range = range.to_point(buffer);
13504                range.start.column = 0;
13505                range.end.column = buffer.line_len(range.end.row);
13506                new_selections_by_buffer
13507                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13508                    .or_insert(Vec::new())
13509                    .push(range)
13510            }
13511        }
13512
13513        let proposed_changes_buffers = new_selections_by_buffer
13514            .into_iter()
13515            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13516            .collect::<Vec<_>>();
13517        let proposed_changes_editor = cx.new(|cx| {
13518            ProposedChangesEditor::new(
13519                "Proposed changes",
13520                proposed_changes_buffers,
13521                self.project.clone(),
13522                window,
13523                cx,
13524            )
13525        });
13526
13527        window.defer(cx, move |window, cx| {
13528            workspace.update(cx, |workspace, cx| {
13529                workspace.active_pane().update(cx, |pane, cx| {
13530                    pane.add_item(
13531                        Box::new(proposed_changes_editor),
13532                        true,
13533                        true,
13534                        None,
13535                        window,
13536                        cx,
13537                    );
13538                });
13539            });
13540        });
13541    }
13542
13543    pub fn open_excerpts_in_split(
13544        &mut self,
13545        _: &OpenExcerptsSplit,
13546        window: &mut Window,
13547        cx: &mut Context<Self>,
13548    ) {
13549        self.open_excerpts_common(None, true, window, cx)
13550    }
13551
13552    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13553        self.open_excerpts_common(None, false, window, cx)
13554    }
13555
13556    fn open_excerpts_common(
13557        &mut self,
13558        jump_data: Option<JumpData>,
13559        split: bool,
13560        window: &mut Window,
13561        cx: &mut Context<Self>,
13562    ) {
13563        let Some(workspace) = self.workspace() else {
13564            cx.propagate();
13565            return;
13566        };
13567
13568        if self.buffer.read(cx).is_singleton() {
13569            cx.propagate();
13570            return;
13571        }
13572
13573        let mut new_selections_by_buffer = HashMap::default();
13574        match &jump_data {
13575            Some(JumpData::MultiBufferPoint {
13576                excerpt_id,
13577                position,
13578                anchor,
13579                line_offset_from_top,
13580            }) => {
13581                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13582                if let Some(buffer) = multi_buffer_snapshot
13583                    .buffer_id_for_excerpt(*excerpt_id)
13584                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13585                {
13586                    let buffer_snapshot = buffer.read(cx).snapshot();
13587                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13588                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13589                    } else {
13590                        buffer_snapshot.clip_point(*position, Bias::Left)
13591                    };
13592                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13593                    new_selections_by_buffer.insert(
13594                        buffer,
13595                        (
13596                            vec![jump_to_offset..jump_to_offset],
13597                            Some(*line_offset_from_top),
13598                        ),
13599                    );
13600                }
13601            }
13602            Some(JumpData::MultiBufferRow {
13603                row,
13604                line_offset_from_top,
13605            }) => {
13606                let point = MultiBufferPoint::new(row.0, 0);
13607                if let Some((buffer, buffer_point, _)) =
13608                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13609                {
13610                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13611                    new_selections_by_buffer
13612                        .entry(buffer)
13613                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13614                        .0
13615                        .push(buffer_offset..buffer_offset)
13616                }
13617            }
13618            None => {
13619                let selections = self.selections.all::<usize>(cx);
13620                let multi_buffer = self.buffer.read(cx);
13621                for selection in selections {
13622                    for (buffer, mut range, _) in multi_buffer
13623                        .snapshot(cx)
13624                        .range_to_buffer_ranges(selection.range())
13625                    {
13626                        // When editing branch buffers, jump to the corresponding location
13627                        // in their base buffer.
13628                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13629                        let buffer = buffer_handle.read(cx);
13630                        if let Some(base_buffer) = buffer.base_buffer() {
13631                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13632                            buffer_handle = base_buffer;
13633                        }
13634
13635                        if selection.reversed {
13636                            mem::swap(&mut range.start, &mut range.end);
13637                        }
13638                        new_selections_by_buffer
13639                            .entry(buffer_handle)
13640                            .or_insert((Vec::new(), None))
13641                            .0
13642                            .push(range)
13643                    }
13644                }
13645            }
13646        }
13647
13648        if new_selections_by_buffer.is_empty() {
13649            return;
13650        }
13651
13652        // We defer the pane interaction because we ourselves are a workspace item
13653        // and activating a new item causes the pane to call a method on us reentrantly,
13654        // which panics if we're on the stack.
13655        window.defer(cx, move |window, cx| {
13656            workspace.update(cx, |workspace, cx| {
13657                let pane = if split {
13658                    workspace.adjacent_pane(window, cx)
13659                } else {
13660                    workspace.active_pane().clone()
13661                };
13662
13663                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13664                    let editor = buffer
13665                        .read(cx)
13666                        .file()
13667                        .is_none()
13668                        .then(|| {
13669                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13670                            // so `workspace.open_project_item` will never find them, always opening a new editor.
13671                            // Instead, we try to activate the existing editor in the pane first.
13672                            let (editor, pane_item_index) =
13673                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
13674                                    let editor = item.downcast::<Editor>()?;
13675                                    let singleton_buffer =
13676                                        editor.read(cx).buffer().read(cx).as_singleton()?;
13677                                    if singleton_buffer == buffer {
13678                                        Some((editor, i))
13679                                    } else {
13680                                        None
13681                                    }
13682                                })?;
13683                            pane.update(cx, |pane, cx| {
13684                                pane.activate_item(pane_item_index, true, true, window, cx)
13685                            });
13686                            Some(editor)
13687                        })
13688                        .flatten()
13689                        .unwrap_or_else(|| {
13690                            workspace.open_project_item::<Self>(
13691                                pane.clone(),
13692                                buffer,
13693                                true,
13694                                true,
13695                                window,
13696                                cx,
13697                            )
13698                        });
13699
13700                    editor.update(cx, |editor, cx| {
13701                        let autoscroll = match scroll_offset {
13702                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13703                            None => Autoscroll::newest(),
13704                        };
13705                        let nav_history = editor.nav_history.take();
13706                        editor.change_selections(Some(autoscroll), window, cx, |s| {
13707                            s.select_ranges(ranges);
13708                        });
13709                        editor.nav_history = nav_history;
13710                    });
13711                }
13712            })
13713        });
13714    }
13715
13716    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13717        let snapshot = self.buffer.read(cx).read(cx);
13718        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13719        Some(
13720            ranges
13721                .iter()
13722                .map(move |range| {
13723                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13724                })
13725                .collect(),
13726        )
13727    }
13728
13729    fn selection_replacement_ranges(
13730        &self,
13731        range: Range<OffsetUtf16>,
13732        cx: &mut App,
13733    ) -> Vec<Range<OffsetUtf16>> {
13734        let selections = self.selections.all::<OffsetUtf16>(cx);
13735        let newest_selection = selections
13736            .iter()
13737            .max_by_key(|selection| selection.id)
13738            .unwrap();
13739        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13740        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13741        let snapshot = self.buffer.read(cx).read(cx);
13742        selections
13743            .into_iter()
13744            .map(|mut selection| {
13745                selection.start.0 =
13746                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
13747                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13748                snapshot.clip_offset_utf16(selection.start, Bias::Left)
13749                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13750            })
13751            .collect()
13752    }
13753
13754    fn report_editor_event(
13755        &self,
13756        event_type: &'static str,
13757        file_extension: Option<String>,
13758        cx: &App,
13759    ) {
13760        if cfg!(any(test, feature = "test-support")) {
13761            return;
13762        }
13763
13764        let Some(project) = &self.project else { return };
13765
13766        // If None, we are in a file without an extension
13767        let file = self
13768            .buffer
13769            .read(cx)
13770            .as_singleton()
13771            .and_then(|b| b.read(cx).file());
13772        let file_extension = file_extension.or(file
13773            .as_ref()
13774            .and_then(|file| Path::new(file.file_name(cx)).extension())
13775            .and_then(|e| e.to_str())
13776            .map(|a| a.to_string()));
13777
13778        let vim_mode = cx
13779            .global::<SettingsStore>()
13780            .raw_user_settings()
13781            .get("vim_mode")
13782            == Some(&serde_json::Value::Bool(true));
13783
13784        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13785            == language::language_settings::InlineCompletionProvider::Copilot;
13786        let copilot_enabled_for_language = self
13787            .buffer
13788            .read(cx)
13789            .settings_at(0, cx)
13790            .show_inline_completions;
13791
13792        let project = project.read(cx);
13793        telemetry::event!(
13794            event_type,
13795            file_extension,
13796            vim_mode,
13797            copilot_enabled,
13798            copilot_enabled_for_language,
13799            is_via_ssh = project.is_via_ssh(),
13800        );
13801    }
13802
13803    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13804    /// with each line being an array of {text, highlight} objects.
13805    fn copy_highlight_json(
13806        &mut self,
13807        _: &CopyHighlightJson,
13808        window: &mut Window,
13809        cx: &mut Context<Self>,
13810    ) {
13811        #[derive(Serialize)]
13812        struct Chunk<'a> {
13813            text: String,
13814            highlight: Option<&'a str>,
13815        }
13816
13817        let snapshot = self.buffer.read(cx).snapshot(cx);
13818        let range = self
13819            .selected_text_range(false, window, cx)
13820            .and_then(|selection| {
13821                if selection.range.is_empty() {
13822                    None
13823                } else {
13824                    Some(selection.range)
13825                }
13826            })
13827            .unwrap_or_else(|| 0..snapshot.len());
13828
13829        let chunks = snapshot.chunks(range, true);
13830        let mut lines = Vec::new();
13831        let mut line: VecDeque<Chunk> = VecDeque::new();
13832
13833        let Some(style) = self.style.as_ref() else {
13834            return;
13835        };
13836
13837        for chunk in chunks {
13838            let highlight = chunk
13839                .syntax_highlight_id
13840                .and_then(|id| id.name(&style.syntax));
13841            let mut chunk_lines = chunk.text.split('\n').peekable();
13842            while let Some(text) = chunk_lines.next() {
13843                let mut merged_with_last_token = false;
13844                if let Some(last_token) = line.back_mut() {
13845                    if last_token.highlight == highlight {
13846                        last_token.text.push_str(text);
13847                        merged_with_last_token = true;
13848                    }
13849                }
13850
13851                if !merged_with_last_token {
13852                    line.push_back(Chunk {
13853                        text: text.into(),
13854                        highlight,
13855                    });
13856                }
13857
13858                if chunk_lines.peek().is_some() {
13859                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
13860                        line.pop_front();
13861                    }
13862                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
13863                        line.pop_back();
13864                    }
13865
13866                    lines.push(mem::take(&mut line));
13867                }
13868            }
13869        }
13870
13871        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13872            return;
13873        };
13874        cx.write_to_clipboard(ClipboardItem::new_string(lines));
13875    }
13876
13877    pub fn open_context_menu(
13878        &mut self,
13879        _: &OpenContextMenu,
13880        window: &mut Window,
13881        cx: &mut Context<Self>,
13882    ) {
13883        self.request_autoscroll(Autoscroll::newest(), cx);
13884        let position = self.selections.newest_display(cx).start;
13885        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13886    }
13887
13888    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13889        &self.inlay_hint_cache
13890    }
13891
13892    pub fn replay_insert_event(
13893        &mut self,
13894        text: &str,
13895        relative_utf16_range: Option<Range<isize>>,
13896        window: &mut Window,
13897        cx: &mut Context<Self>,
13898    ) {
13899        if !self.input_enabled {
13900            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13901            return;
13902        }
13903        if let Some(relative_utf16_range) = relative_utf16_range {
13904            let selections = self.selections.all::<OffsetUtf16>(cx);
13905            self.change_selections(None, window, cx, |s| {
13906                let new_ranges = selections.into_iter().map(|range| {
13907                    let start = OffsetUtf16(
13908                        range
13909                            .head()
13910                            .0
13911                            .saturating_add_signed(relative_utf16_range.start),
13912                    );
13913                    let end = OffsetUtf16(
13914                        range
13915                            .head()
13916                            .0
13917                            .saturating_add_signed(relative_utf16_range.end),
13918                    );
13919                    start..end
13920                });
13921                s.select_ranges(new_ranges);
13922            });
13923        }
13924
13925        self.handle_input(text, window, cx);
13926    }
13927
13928    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
13929        let Some(provider) = self.semantics_provider.as_ref() else {
13930            return false;
13931        };
13932
13933        let mut supports = false;
13934        self.buffer().read(cx).for_each_buffer(|buffer| {
13935            supports |= provider.supports_inlay_hints(buffer, cx);
13936        });
13937        supports
13938    }
13939    pub fn is_focused(&self, window: &mut Window) -> bool {
13940        self.focus_handle.is_focused(window)
13941    }
13942
13943    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13944        cx.emit(EditorEvent::Focused);
13945
13946        if let Some(descendant) = self
13947            .last_focused_descendant
13948            .take()
13949            .and_then(|descendant| descendant.upgrade())
13950        {
13951            window.focus(&descendant);
13952        } else {
13953            if let Some(blame) = self.blame.as_ref() {
13954                blame.update(cx, GitBlame::focus)
13955            }
13956
13957            self.blink_manager.update(cx, BlinkManager::enable);
13958            self.show_cursor_names(window, cx);
13959            self.buffer.update(cx, |buffer, cx| {
13960                buffer.finalize_last_transaction(cx);
13961                if self.leader_peer_id.is_none() {
13962                    buffer.set_active_selections(
13963                        &self.selections.disjoint_anchors(),
13964                        self.selections.line_mode,
13965                        self.cursor_shape,
13966                        cx,
13967                    );
13968                }
13969            });
13970        }
13971    }
13972
13973    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13974        cx.emit(EditorEvent::FocusedIn)
13975    }
13976
13977    fn handle_focus_out(
13978        &mut self,
13979        event: FocusOutEvent,
13980        _window: &mut Window,
13981        _cx: &mut Context<Self>,
13982    ) {
13983        if event.blurred != self.focus_handle {
13984            self.last_focused_descendant = Some(event.blurred);
13985        }
13986    }
13987
13988    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13989        self.blink_manager.update(cx, BlinkManager::disable);
13990        self.buffer
13991            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13992
13993        if let Some(blame) = self.blame.as_ref() {
13994            blame.update(cx, GitBlame::blur)
13995        }
13996        if !self.hover_state.focused(window, cx) {
13997            hide_hover(self, cx);
13998        }
13999
14000        self.hide_context_menu(window, cx);
14001        cx.emit(EditorEvent::Blurred);
14002        cx.notify();
14003    }
14004
14005    pub fn register_action<A: Action>(
14006        &mut self,
14007        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14008    ) -> Subscription {
14009        let id = self.next_editor_action_id.post_inc();
14010        let listener = Arc::new(listener);
14011        self.editor_actions.borrow_mut().insert(
14012            id,
14013            Box::new(move |window, _| {
14014                let listener = listener.clone();
14015                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14016                    let action = action.downcast_ref().unwrap();
14017                    if phase == DispatchPhase::Bubble {
14018                        listener(action, window, cx)
14019                    }
14020                })
14021            }),
14022        );
14023
14024        let editor_actions = self.editor_actions.clone();
14025        Subscription::new(move || {
14026            editor_actions.borrow_mut().remove(&id);
14027        })
14028    }
14029
14030    pub fn file_header_size(&self) -> u32 {
14031        FILE_HEADER_HEIGHT
14032    }
14033
14034    pub fn revert(
14035        &mut self,
14036        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14037        window: &mut Window,
14038        cx: &mut Context<Self>,
14039    ) {
14040        self.buffer().update(cx, |multi_buffer, cx| {
14041            for (buffer_id, changes) in revert_changes {
14042                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14043                    buffer.update(cx, |buffer, cx| {
14044                        buffer.edit(
14045                            changes.into_iter().map(|(range, text)| {
14046                                (range, text.to_string().map(Arc::<str>::from))
14047                            }),
14048                            None,
14049                            cx,
14050                        );
14051                    });
14052                }
14053            }
14054        });
14055        self.change_selections(None, window, cx, |selections| selections.refresh());
14056    }
14057
14058    pub fn to_pixel_point(
14059        &self,
14060        source: multi_buffer::Anchor,
14061        editor_snapshot: &EditorSnapshot,
14062        window: &mut Window,
14063    ) -> Option<gpui::Point<Pixels>> {
14064        let source_point = source.to_display_point(editor_snapshot);
14065        self.display_to_pixel_point(source_point, editor_snapshot, window)
14066    }
14067
14068    pub fn display_to_pixel_point(
14069        &self,
14070        source: DisplayPoint,
14071        editor_snapshot: &EditorSnapshot,
14072        window: &mut Window,
14073    ) -> Option<gpui::Point<Pixels>> {
14074        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14075        let text_layout_details = self.text_layout_details(window);
14076        let scroll_top = text_layout_details
14077            .scroll_anchor
14078            .scroll_position(editor_snapshot)
14079            .y;
14080
14081        if source.row().as_f32() < scroll_top.floor() {
14082            return None;
14083        }
14084        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14085        let source_y = line_height * (source.row().as_f32() - scroll_top);
14086        Some(gpui::Point::new(source_x, source_y))
14087    }
14088
14089    pub fn has_active_completions_menu(&self) -> bool {
14090        self.context_menu.borrow().as_ref().map_or(false, |menu| {
14091            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14092        })
14093    }
14094
14095    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14096        self.addons
14097            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14098    }
14099
14100    pub fn unregister_addon<T: Addon>(&mut self) {
14101        self.addons.remove(&std::any::TypeId::of::<T>());
14102    }
14103
14104    pub fn addon<T: Addon>(&self) -> Option<&T> {
14105        let type_id = std::any::TypeId::of::<T>();
14106        self.addons
14107            .get(&type_id)
14108            .and_then(|item| item.to_any().downcast_ref::<T>())
14109    }
14110
14111    fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14112        let text_layout_details = self.text_layout_details(window);
14113        let style = &text_layout_details.editor_style;
14114        let font_id = window.text_system().resolve_font(&style.text.font());
14115        let font_size = style.text.font_size.to_pixels(window.rem_size());
14116        let line_height = style.text.line_height_in_pixels(window.rem_size());
14117
14118        let em_width = window
14119            .text_system()
14120            .typographic_bounds(font_id, font_size, 'm')
14121            .unwrap()
14122            .size
14123            .width;
14124
14125        gpui::Point::new(em_width, line_height)
14126    }
14127}
14128
14129fn get_unstaged_changes_for_buffers(
14130    project: &Entity<Project>,
14131    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14132    buffer: Entity<MultiBuffer>,
14133    cx: &mut App,
14134) {
14135    let mut tasks = Vec::new();
14136    project.update(cx, |project, cx| {
14137        for buffer in buffers {
14138            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14139        }
14140    });
14141    cx.spawn(|mut cx| async move {
14142        let change_sets = futures::future::join_all(tasks).await;
14143        buffer
14144            .update(&mut cx, |buffer, cx| {
14145                for change_set in change_sets {
14146                    if let Some(change_set) = change_set.log_err() {
14147                        buffer.add_change_set(change_set, cx);
14148                    }
14149                }
14150            })
14151            .ok();
14152    })
14153    .detach();
14154}
14155
14156fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14157    let tab_size = tab_size.get() as usize;
14158    let mut width = offset;
14159
14160    for ch in text.chars() {
14161        width += if ch == '\t' {
14162            tab_size - (width % tab_size)
14163        } else {
14164            1
14165        };
14166    }
14167
14168    width - offset
14169}
14170
14171#[cfg(test)]
14172mod tests {
14173    use super::*;
14174
14175    #[test]
14176    fn test_string_size_with_expanded_tabs() {
14177        let nz = |val| NonZeroU32::new(val).unwrap();
14178        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14179        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14180        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14181        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14182        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14183        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14184        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14185        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14186    }
14187}
14188
14189/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14190struct WordBreakingTokenizer<'a> {
14191    input: &'a str,
14192}
14193
14194impl<'a> WordBreakingTokenizer<'a> {
14195    fn new(input: &'a str) -> Self {
14196        Self { input }
14197    }
14198}
14199
14200fn is_char_ideographic(ch: char) -> bool {
14201    use unicode_script::Script::*;
14202    use unicode_script::UnicodeScript;
14203    matches!(ch.script(), Han | Tangut | Yi)
14204}
14205
14206fn is_grapheme_ideographic(text: &str) -> bool {
14207    text.chars().any(is_char_ideographic)
14208}
14209
14210fn is_grapheme_whitespace(text: &str) -> bool {
14211    text.chars().any(|x| x.is_whitespace())
14212}
14213
14214fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14215    text.chars().next().map_or(false, |ch| {
14216        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14217    })
14218}
14219
14220#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14221struct WordBreakToken<'a> {
14222    token: &'a str,
14223    grapheme_len: usize,
14224    is_whitespace: bool,
14225}
14226
14227impl<'a> Iterator for WordBreakingTokenizer<'a> {
14228    /// Yields a span, the count of graphemes in the token, and whether it was
14229    /// whitespace. Note that it also breaks at word boundaries.
14230    type Item = WordBreakToken<'a>;
14231
14232    fn next(&mut self) -> Option<Self::Item> {
14233        use unicode_segmentation::UnicodeSegmentation;
14234        if self.input.is_empty() {
14235            return None;
14236        }
14237
14238        let mut iter = self.input.graphemes(true).peekable();
14239        let mut offset = 0;
14240        let mut graphemes = 0;
14241        if let Some(first_grapheme) = iter.next() {
14242            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14243            offset += first_grapheme.len();
14244            graphemes += 1;
14245            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14246                if let Some(grapheme) = iter.peek().copied() {
14247                    if should_stay_with_preceding_ideograph(grapheme) {
14248                        offset += grapheme.len();
14249                        graphemes += 1;
14250                    }
14251                }
14252            } else {
14253                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14254                let mut next_word_bound = words.peek().copied();
14255                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14256                    next_word_bound = words.next();
14257                }
14258                while let Some(grapheme) = iter.peek().copied() {
14259                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14260                        break;
14261                    };
14262                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14263                        break;
14264                    };
14265                    offset += grapheme.len();
14266                    graphemes += 1;
14267                    iter.next();
14268                }
14269            }
14270            let token = &self.input[..offset];
14271            self.input = &self.input[offset..];
14272            if is_whitespace {
14273                Some(WordBreakToken {
14274                    token: " ",
14275                    grapheme_len: 1,
14276                    is_whitespace: true,
14277                })
14278            } else {
14279                Some(WordBreakToken {
14280                    token,
14281                    grapheme_len: graphemes,
14282                    is_whitespace: false,
14283                })
14284            }
14285        } else {
14286            None
14287        }
14288    }
14289}
14290
14291#[test]
14292fn test_word_breaking_tokenizer() {
14293    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14294        ("", &[]),
14295        ("  ", &[(" ", 1, true)]),
14296        ("Ʒ", &[("Ʒ", 1, false)]),
14297        ("Ǽ", &[("Ǽ", 1, false)]),
14298        ("", &[("", 1, false)]),
14299        ("⋑⋑", &[("⋑⋑", 2, false)]),
14300        (
14301            "原理,进而",
14302            &[
14303                ("", 1, false),
14304                ("理,", 2, false),
14305                ("", 1, false),
14306                ("", 1, false),
14307            ],
14308        ),
14309        (
14310            "hello world",
14311            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14312        ),
14313        (
14314            "hello, world",
14315            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14316        ),
14317        (
14318            "  hello world",
14319            &[
14320                (" ", 1, true),
14321                ("hello", 5, false),
14322                (" ", 1, true),
14323                ("world", 5, false),
14324            ],
14325        ),
14326        (
14327            "这是什么 \n 钢笔",
14328            &[
14329                ("", 1, false),
14330                ("", 1, false),
14331                ("", 1, false),
14332                ("", 1, false),
14333                (" ", 1, true),
14334                ("", 1, false),
14335                ("", 1, false),
14336            ],
14337        ),
14338        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14339    ];
14340
14341    for (input, result) in tests {
14342        assert_eq!(
14343            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14344            result
14345                .iter()
14346                .copied()
14347                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14348                    token,
14349                    grapheme_len,
14350                    is_whitespace,
14351                })
14352                .collect::<Vec<_>>()
14353        );
14354    }
14355}
14356
14357fn wrap_with_prefix(
14358    line_prefix: String,
14359    unwrapped_text: String,
14360    wrap_column: usize,
14361    tab_size: NonZeroU32,
14362) -> String {
14363    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14364    let mut wrapped_text = String::new();
14365    let mut current_line = line_prefix.clone();
14366
14367    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14368    let mut current_line_len = line_prefix_len;
14369    for WordBreakToken {
14370        token,
14371        grapheme_len,
14372        is_whitespace,
14373    } in tokenizer
14374    {
14375        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14376            wrapped_text.push_str(current_line.trim_end());
14377            wrapped_text.push('\n');
14378            current_line.truncate(line_prefix.len());
14379            current_line_len = line_prefix_len;
14380            if !is_whitespace {
14381                current_line.push_str(token);
14382                current_line_len += grapheme_len;
14383            }
14384        } else if !is_whitespace {
14385            current_line.push_str(token);
14386            current_line_len += grapheme_len;
14387        } else if current_line_len != line_prefix_len {
14388            current_line.push(' ');
14389            current_line_len += 1;
14390        }
14391    }
14392
14393    if !current_line.is_empty() {
14394        wrapped_text.push_str(&current_line);
14395    }
14396    wrapped_text
14397}
14398
14399#[test]
14400fn test_wrap_with_prefix() {
14401    assert_eq!(
14402        wrap_with_prefix(
14403            "# ".to_string(),
14404            "abcdefg".to_string(),
14405            4,
14406            NonZeroU32::new(4).unwrap()
14407        ),
14408        "# abcdefg"
14409    );
14410    assert_eq!(
14411        wrap_with_prefix(
14412            "".to_string(),
14413            "\thello world".to_string(),
14414            8,
14415            NonZeroU32::new(4).unwrap()
14416        ),
14417        "hello\nworld"
14418    );
14419    assert_eq!(
14420        wrap_with_prefix(
14421            "// ".to_string(),
14422            "xx \nyy zz aa bb cc".to_string(),
14423            12,
14424            NonZeroU32::new(4).unwrap()
14425        ),
14426        "// xx yy zz\n// aa bb cc"
14427    );
14428    assert_eq!(
14429        wrap_with_prefix(
14430            String::new(),
14431            "这是什么 \n 钢笔".to_string(),
14432            3,
14433            NonZeroU32::new(4).unwrap()
14434        ),
14435        "这是什\n么 钢\n"
14436    );
14437}
14438
14439pub trait CollaborationHub {
14440    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14441    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14442    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14443}
14444
14445impl CollaborationHub for Entity<Project> {
14446    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14447        self.read(cx).collaborators()
14448    }
14449
14450    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14451        self.read(cx).user_store().read(cx).participant_indices()
14452    }
14453
14454    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14455        let this = self.read(cx);
14456        let user_ids = this.collaborators().values().map(|c| c.user_id);
14457        this.user_store().read_with(cx, |user_store, cx| {
14458            user_store.participant_names(user_ids, cx)
14459        })
14460    }
14461}
14462
14463pub trait SemanticsProvider {
14464    fn hover(
14465        &self,
14466        buffer: &Entity<Buffer>,
14467        position: text::Anchor,
14468        cx: &mut App,
14469    ) -> Option<Task<Vec<project::Hover>>>;
14470
14471    fn inlay_hints(
14472        &self,
14473        buffer_handle: Entity<Buffer>,
14474        range: Range<text::Anchor>,
14475        cx: &mut App,
14476    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14477
14478    fn resolve_inlay_hint(
14479        &self,
14480        hint: InlayHint,
14481        buffer_handle: Entity<Buffer>,
14482        server_id: LanguageServerId,
14483        cx: &mut App,
14484    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14485
14486    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14487
14488    fn document_highlights(
14489        &self,
14490        buffer: &Entity<Buffer>,
14491        position: text::Anchor,
14492        cx: &mut App,
14493    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14494
14495    fn definitions(
14496        &self,
14497        buffer: &Entity<Buffer>,
14498        position: text::Anchor,
14499        kind: GotoDefinitionKind,
14500        cx: &mut App,
14501    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14502
14503    fn range_for_rename(
14504        &self,
14505        buffer: &Entity<Buffer>,
14506        position: text::Anchor,
14507        cx: &mut App,
14508    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14509
14510    fn perform_rename(
14511        &self,
14512        buffer: &Entity<Buffer>,
14513        position: text::Anchor,
14514        new_name: String,
14515        cx: &mut App,
14516    ) -> Option<Task<Result<ProjectTransaction>>>;
14517}
14518
14519pub trait CompletionProvider {
14520    fn completions(
14521        &self,
14522        buffer: &Entity<Buffer>,
14523        buffer_position: text::Anchor,
14524        trigger: CompletionContext,
14525        window: &mut Window,
14526        cx: &mut Context<Editor>,
14527    ) -> Task<Result<Vec<Completion>>>;
14528
14529    fn resolve_completions(
14530        &self,
14531        buffer: Entity<Buffer>,
14532        completion_indices: Vec<usize>,
14533        completions: Rc<RefCell<Box<[Completion]>>>,
14534        cx: &mut Context<Editor>,
14535    ) -> Task<Result<bool>>;
14536
14537    fn apply_additional_edits_for_completion(
14538        &self,
14539        _buffer: Entity<Buffer>,
14540        _completions: Rc<RefCell<Box<[Completion]>>>,
14541        _completion_index: usize,
14542        _push_to_history: bool,
14543        _cx: &mut Context<Editor>,
14544    ) -> Task<Result<Option<language::Transaction>>> {
14545        Task::ready(Ok(None))
14546    }
14547
14548    fn is_completion_trigger(
14549        &self,
14550        buffer: &Entity<Buffer>,
14551        position: language::Anchor,
14552        text: &str,
14553        trigger_in_words: bool,
14554        cx: &mut Context<Editor>,
14555    ) -> bool;
14556
14557    fn sort_completions(&self) -> bool {
14558        true
14559    }
14560}
14561
14562pub trait CodeActionProvider {
14563    fn id(&self) -> Arc<str>;
14564
14565    fn code_actions(
14566        &self,
14567        buffer: &Entity<Buffer>,
14568        range: Range<text::Anchor>,
14569        window: &mut Window,
14570        cx: &mut App,
14571    ) -> Task<Result<Vec<CodeAction>>>;
14572
14573    fn apply_code_action(
14574        &self,
14575        buffer_handle: Entity<Buffer>,
14576        action: CodeAction,
14577        excerpt_id: ExcerptId,
14578        push_to_history: bool,
14579        window: &mut Window,
14580        cx: &mut App,
14581    ) -> Task<Result<ProjectTransaction>>;
14582}
14583
14584impl CodeActionProvider for Entity<Project> {
14585    fn id(&self) -> Arc<str> {
14586        "project".into()
14587    }
14588
14589    fn code_actions(
14590        &self,
14591        buffer: &Entity<Buffer>,
14592        range: Range<text::Anchor>,
14593        _window: &mut Window,
14594        cx: &mut App,
14595    ) -> Task<Result<Vec<CodeAction>>> {
14596        self.update(cx, |project, cx| {
14597            project.code_actions(buffer, range, None, cx)
14598        })
14599    }
14600
14601    fn apply_code_action(
14602        &self,
14603        buffer_handle: Entity<Buffer>,
14604        action: CodeAction,
14605        _excerpt_id: ExcerptId,
14606        push_to_history: bool,
14607        _window: &mut Window,
14608        cx: &mut App,
14609    ) -> Task<Result<ProjectTransaction>> {
14610        self.update(cx, |project, cx| {
14611            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14612        })
14613    }
14614}
14615
14616fn snippet_completions(
14617    project: &Project,
14618    buffer: &Entity<Buffer>,
14619    buffer_position: text::Anchor,
14620    cx: &mut App,
14621) -> Task<Result<Vec<Completion>>> {
14622    let language = buffer.read(cx).language_at(buffer_position);
14623    let language_name = language.as_ref().map(|language| language.lsp_id());
14624    let snippet_store = project.snippets().read(cx);
14625    let snippets = snippet_store.snippets_for(language_name, cx);
14626
14627    if snippets.is_empty() {
14628        return Task::ready(Ok(vec![]));
14629    }
14630    let snapshot = buffer.read(cx).text_snapshot();
14631    let chars: String = snapshot
14632        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14633        .collect();
14634
14635    let scope = language.map(|language| language.default_scope());
14636    let executor = cx.background_executor().clone();
14637
14638    cx.background_executor().spawn(async move {
14639        let classifier = CharClassifier::new(scope).for_completion(true);
14640        let mut last_word = chars
14641            .chars()
14642            .take_while(|c| classifier.is_word(*c))
14643            .collect::<String>();
14644        last_word = last_word.chars().rev().collect();
14645
14646        if last_word.is_empty() {
14647            return Ok(vec![]);
14648        }
14649
14650        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14651        let to_lsp = |point: &text::Anchor| {
14652            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14653            point_to_lsp(end)
14654        };
14655        let lsp_end = to_lsp(&buffer_position);
14656
14657        let candidates = snippets
14658            .iter()
14659            .enumerate()
14660            .flat_map(|(ix, snippet)| {
14661                snippet
14662                    .prefix
14663                    .iter()
14664                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14665            })
14666            .collect::<Vec<StringMatchCandidate>>();
14667
14668        let mut matches = fuzzy::match_strings(
14669            &candidates,
14670            &last_word,
14671            last_word.chars().any(|c| c.is_uppercase()),
14672            100,
14673            &Default::default(),
14674            executor,
14675        )
14676        .await;
14677
14678        // Remove all candidates where the query's start does not match the start of any word in the candidate
14679        if let Some(query_start) = last_word.chars().next() {
14680            matches.retain(|string_match| {
14681                split_words(&string_match.string).any(|word| {
14682                    // Check that the first codepoint of the word as lowercase matches the first
14683                    // codepoint of the query as lowercase
14684                    word.chars()
14685                        .flat_map(|codepoint| codepoint.to_lowercase())
14686                        .zip(query_start.to_lowercase())
14687                        .all(|(word_cp, query_cp)| word_cp == query_cp)
14688                })
14689            });
14690        }
14691
14692        let matched_strings = matches
14693            .into_iter()
14694            .map(|m| m.string)
14695            .collect::<HashSet<_>>();
14696
14697        let result: Vec<Completion> = snippets
14698            .into_iter()
14699            .filter_map(|snippet| {
14700                let matching_prefix = snippet
14701                    .prefix
14702                    .iter()
14703                    .find(|prefix| matched_strings.contains(*prefix))?;
14704                let start = as_offset - last_word.len();
14705                let start = snapshot.anchor_before(start);
14706                let range = start..buffer_position;
14707                let lsp_start = to_lsp(&start);
14708                let lsp_range = lsp::Range {
14709                    start: lsp_start,
14710                    end: lsp_end,
14711                };
14712                Some(Completion {
14713                    old_range: range,
14714                    new_text: snippet.body.clone(),
14715                    resolved: false,
14716                    label: CodeLabel {
14717                        text: matching_prefix.clone(),
14718                        runs: vec![],
14719                        filter_range: 0..matching_prefix.len(),
14720                    },
14721                    server_id: LanguageServerId(usize::MAX),
14722                    documentation: snippet.description.clone().map(Documentation::SingleLine),
14723                    lsp_completion: lsp::CompletionItem {
14724                        label: snippet.prefix.first().unwrap().clone(),
14725                        kind: Some(CompletionItemKind::SNIPPET),
14726                        label_details: snippet.description.as_ref().map(|description| {
14727                            lsp::CompletionItemLabelDetails {
14728                                detail: Some(description.clone()),
14729                                description: None,
14730                            }
14731                        }),
14732                        insert_text_format: Some(InsertTextFormat::SNIPPET),
14733                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14734                            lsp::InsertReplaceEdit {
14735                                new_text: snippet.body.clone(),
14736                                insert: lsp_range,
14737                                replace: lsp_range,
14738                            },
14739                        )),
14740                        filter_text: Some(snippet.body.clone()),
14741                        sort_text: Some(char::MAX.to_string()),
14742                        ..Default::default()
14743                    },
14744                    confirm: None,
14745                })
14746            })
14747            .collect();
14748
14749        Ok(result)
14750    })
14751}
14752
14753impl CompletionProvider for Entity<Project> {
14754    fn completions(
14755        &self,
14756        buffer: &Entity<Buffer>,
14757        buffer_position: text::Anchor,
14758        options: CompletionContext,
14759        _window: &mut Window,
14760        cx: &mut Context<Editor>,
14761    ) -> Task<Result<Vec<Completion>>> {
14762        self.update(cx, |project, cx| {
14763            let snippets = snippet_completions(project, buffer, buffer_position, cx);
14764            let project_completions = project.completions(buffer, buffer_position, options, cx);
14765            cx.background_executor().spawn(async move {
14766                let mut completions = project_completions.await?;
14767                let snippets_completions = snippets.await?;
14768                completions.extend(snippets_completions);
14769                Ok(completions)
14770            })
14771        })
14772    }
14773
14774    fn resolve_completions(
14775        &self,
14776        buffer: Entity<Buffer>,
14777        completion_indices: Vec<usize>,
14778        completions: Rc<RefCell<Box<[Completion]>>>,
14779        cx: &mut Context<Editor>,
14780    ) -> Task<Result<bool>> {
14781        self.update(cx, |project, cx| {
14782            project.lsp_store().update(cx, |lsp_store, cx| {
14783                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14784            })
14785        })
14786    }
14787
14788    fn apply_additional_edits_for_completion(
14789        &self,
14790        buffer: Entity<Buffer>,
14791        completions: Rc<RefCell<Box<[Completion]>>>,
14792        completion_index: usize,
14793        push_to_history: bool,
14794        cx: &mut Context<Editor>,
14795    ) -> Task<Result<Option<language::Transaction>>> {
14796        self.update(cx, |project, cx| {
14797            project.lsp_store().update(cx, |lsp_store, cx| {
14798                lsp_store.apply_additional_edits_for_completion(
14799                    buffer,
14800                    completions,
14801                    completion_index,
14802                    push_to_history,
14803                    cx,
14804                )
14805            })
14806        })
14807    }
14808
14809    fn is_completion_trigger(
14810        &self,
14811        buffer: &Entity<Buffer>,
14812        position: language::Anchor,
14813        text: &str,
14814        trigger_in_words: bool,
14815        cx: &mut Context<Editor>,
14816    ) -> bool {
14817        let mut chars = text.chars();
14818        let char = if let Some(char) = chars.next() {
14819            char
14820        } else {
14821            return false;
14822        };
14823        if chars.next().is_some() {
14824            return false;
14825        }
14826
14827        let buffer = buffer.read(cx);
14828        let snapshot = buffer.snapshot();
14829        if !snapshot.settings_at(position, cx).show_completions_on_input {
14830            return false;
14831        }
14832        let classifier = snapshot.char_classifier_at(position).for_completion(true);
14833        if trigger_in_words && classifier.is_word(char) {
14834            return true;
14835        }
14836
14837        buffer.completion_triggers().contains(text)
14838    }
14839}
14840
14841impl SemanticsProvider for Entity<Project> {
14842    fn hover(
14843        &self,
14844        buffer: &Entity<Buffer>,
14845        position: text::Anchor,
14846        cx: &mut App,
14847    ) -> Option<Task<Vec<project::Hover>>> {
14848        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14849    }
14850
14851    fn document_highlights(
14852        &self,
14853        buffer: &Entity<Buffer>,
14854        position: text::Anchor,
14855        cx: &mut App,
14856    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14857        Some(self.update(cx, |project, cx| {
14858            project.document_highlights(buffer, position, cx)
14859        }))
14860    }
14861
14862    fn definitions(
14863        &self,
14864        buffer: &Entity<Buffer>,
14865        position: text::Anchor,
14866        kind: GotoDefinitionKind,
14867        cx: &mut App,
14868    ) -> Option<Task<Result<Vec<LocationLink>>>> {
14869        Some(self.update(cx, |project, cx| match kind {
14870            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14871            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14872            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14873            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14874        }))
14875    }
14876
14877    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
14878        // TODO: make this work for remote projects
14879        self.read(cx)
14880            .language_servers_for_local_buffer(buffer.read(cx), cx)
14881            .any(
14882                |(_, server)| match server.capabilities().inlay_hint_provider {
14883                    Some(lsp::OneOf::Left(enabled)) => enabled,
14884                    Some(lsp::OneOf::Right(_)) => true,
14885                    None => false,
14886                },
14887            )
14888    }
14889
14890    fn inlay_hints(
14891        &self,
14892        buffer_handle: Entity<Buffer>,
14893        range: Range<text::Anchor>,
14894        cx: &mut App,
14895    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14896        Some(self.update(cx, |project, cx| {
14897            project.inlay_hints(buffer_handle, range, cx)
14898        }))
14899    }
14900
14901    fn resolve_inlay_hint(
14902        &self,
14903        hint: InlayHint,
14904        buffer_handle: Entity<Buffer>,
14905        server_id: LanguageServerId,
14906        cx: &mut App,
14907    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14908        Some(self.update(cx, |project, cx| {
14909            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14910        }))
14911    }
14912
14913    fn range_for_rename(
14914        &self,
14915        buffer: &Entity<Buffer>,
14916        position: text::Anchor,
14917        cx: &mut App,
14918    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14919        Some(self.update(cx, |project, cx| {
14920            let buffer = buffer.clone();
14921            let task = project.prepare_rename(buffer.clone(), position, cx);
14922            cx.spawn(|_, mut cx| async move {
14923                Ok(match task.await? {
14924                    PrepareRenameResponse::Success(range) => Some(range),
14925                    PrepareRenameResponse::InvalidPosition => None,
14926                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14927                        // Fallback on using TreeSitter info to determine identifier range
14928                        buffer.update(&mut cx, |buffer, _| {
14929                            let snapshot = buffer.snapshot();
14930                            let (range, kind) = snapshot.surrounding_word(position);
14931                            if kind != Some(CharKind::Word) {
14932                                return None;
14933                            }
14934                            Some(
14935                                snapshot.anchor_before(range.start)
14936                                    ..snapshot.anchor_after(range.end),
14937                            )
14938                        })?
14939                    }
14940                })
14941            })
14942        }))
14943    }
14944
14945    fn perform_rename(
14946        &self,
14947        buffer: &Entity<Buffer>,
14948        position: text::Anchor,
14949        new_name: String,
14950        cx: &mut App,
14951    ) -> Option<Task<Result<ProjectTransaction>>> {
14952        Some(self.update(cx, |project, cx| {
14953            project.perform_rename(buffer.clone(), position, new_name, cx)
14954        }))
14955    }
14956}
14957
14958fn inlay_hint_settings(
14959    location: Anchor,
14960    snapshot: &MultiBufferSnapshot,
14961    cx: &mut Context<Editor>,
14962) -> InlayHintSettings {
14963    let file = snapshot.file_at(location);
14964    let language = snapshot.language_at(location).map(|l| l.name());
14965    language_settings(language, file, cx).inlay_hints
14966}
14967
14968fn consume_contiguous_rows(
14969    contiguous_row_selections: &mut Vec<Selection<Point>>,
14970    selection: &Selection<Point>,
14971    display_map: &DisplaySnapshot,
14972    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14973) -> (MultiBufferRow, MultiBufferRow) {
14974    contiguous_row_selections.push(selection.clone());
14975    let start_row = MultiBufferRow(selection.start.row);
14976    let mut end_row = ending_row(selection, display_map);
14977
14978    while let Some(next_selection) = selections.peek() {
14979        if next_selection.start.row <= end_row.0 {
14980            end_row = ending_row(next_selection, display_map);
14981            contiguous_row_selections.push(selections.next().unwrap().clone());
14982        } else {
14983            break;
14984        }
14985    }
14986    (start_row, end_row)
14987}
14988
14989fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14990    if next_selection.end.column > 0 || next_selection.is_empty() {
14991        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14992    } else {
14993        MultiBufferRow(next_selection.end.row)
14994    }
14995}
14996
14997impl EditorSnapshot {
14998    pub fn remote_selections_in_range<'a>(
14999        &'a self,
15000        range: &'a Range<Anchor>,
15001        collaboration_hub: &dyn CollaborationHub,
15002        cx: &'a App,
15003    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15004        let participant_names = collaboration_hub.user_names(cx);
15005        let participant_indices = collaboration_hub.user_participant_indices(cx);
15006        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15007        let collaborators_by_replica_id = collaborators_by_peer_id
15008            .iter()
15009            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15010            .collect::<HashMap<_, _>>();
15011        self.buffer_snapshot
15012            .selections_in_range(range, false)
15013            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15014                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15015                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15016                let user_name = participant_names.get(&collaborator.user_id).cloned();
15017                Some(RemoteSelection {
15018                    replica_id,
15019                    selection,
15020                    cursor_shape,
15021                    line_mode,
15022                    participant_index,
15023                    peer_id: collaborator.peer_id,
15024                    user_name,
15025                })
15026            })
15027    }
15028
15029    pub fn hunks_for_ranges(
15030        &self,
15031        ranges: impl Iterator<Item = Range<Point>>,
15032    ) -> Vec<MultiBufferDiffHunk> {
15033        let mut hunks = Vec::new();
15034        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15035            HashMap::default();
15036        for query_range in ranges {
15037            let query_rows =
15038                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15039            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15040                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15041            ) {
15042                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15043                // when the caret is just above or just below the deleted hunk.
15044                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15045                let related_to_selection = if allow_adjacent {
15046                    hunk.row_range.overlaps(&query_rows)
15047                        || hunk.row_range.start == query_rows.end
15048                        || hunk.row_range.end == query_rows.start
15049                } else {
15050                    hunk.row_range.overlaps(&query_rows)
15051                };
15052                if related_to_selection {
15053                    if !processed_buffer_rows
15054                        .entry(hunk.buffer_id)
15055                        .or_default()
15056                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15057                    {
15058                        continue;
15059                    }
15060                    hunks.push(hunk);
15061                }
15062            }
15063        }
15064
15065        hunks
15066    }
15067
15068    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15069        self.display_snapshot.buffer_snapshot.language_at(position)
15070    }
15071
15072    pub fn is_focused(&self) -> bool {
15073        self.is_focused
15074    }
15075
15076    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15077        self.placeholder_text.as_ref()
15078    }
15079
15080    pub fn scroll_position(&self) -> gpui::Point<f32> {
15081        self.scroll_anchor.scroll_position(&self.display_snapshot)
15082    }
15083
15084    fn gutter_dimensions(
15085        &self,
15086        font_id: FontId,
15087        font_size: Pixels,
15088        em_width: Pixels,
15089        em_advance: Pixels,
15090        max_line_number_width: Pixels,
15091        cx: &App,
15092    ) -> GutterDimensions {
15093        if !self.show_gutter {
15094            return GutterDimensions::default();
15095        }
15096        let descent = cx.text_system().descent(font_id, font_size);
15097
15098        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15099            matches!(
15100                ProjectSettings::get_global(cx).git.git_gutter,
15101                Some(GitGutterSetting::TrackedFiles)
15102            )
15103        });
15104        let gutter_settings = EditorSettings::get_global(cx).gutter;
15105        let show_line_numbers = self
15106            .show_line_numbers
15107            .unwrap_or(gutter_settings.line_numbers);
15108        let line_gutter_width = if show_line_numbers {
15109            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15110            let min_width_for_number_on_gutter = em_advance * 4.0;
15111            max_line_number_width.max(min_width_for_number_on_gutter)
15112        } else {
15113            0.0.into()
15114        };
15115
15116        let show_code_actions = self
15117            .show_code_actions
15118            .unwrap_or(gutter_settings.code_actions);
15119
15120        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15121
15122        let git_blame_entries_width =
15123            self.git_blame_gutter_max_author_length
15124                .map(|max_author_length| {
15125                    // Length of the author name, but also space for the commit hash,
15126                    // the spacing and the timestamp.
15127                    let max_char_count = max_author_length
15128                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15129                        + 7 // length of commit sha
15130                        + 14 // length of max relative timestamp ("60 minutes ago")
15131                        + 4; // gaps and margins
15132
15133                    em_advance * max_char_count
15134                });
15135
15136        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15137        left_padding += if show_code_actions || show_runnables {
15138            em_width * 3.0
15139        } else if show_git_gutter && show_line_numbers {
15140            em_width * 2.0
15141        } else if show_git_gutter || show_line_numbers {
15142            em_width
15143        } else {
15144            px(0.)
15145        };
15146
15147        let right_padding = if gutter_settings.folds && show_line_numbers {
15148            em_width * 4.0
15149        } else if gutter_settings.folds {
15150            em_width * 3.0
15151        } else if show_line_numbers {
15152            em_width
15153        } else {
15154            px(0.)
15155        };
15156
15157        GutterDimensions {
15158            left_padding,
15159            right_padding,
15160            width: line_gutter_width + left_padding + right_padding,
15161            margin: -descent,
15162            git_blame_entries_width,
15163        }
15164    }
15165
15166    pub fn render_crease_toggle(
15167        &self,
15168        buffer_row: MultiBufferRow,
15169        row_contains_cursor: bool,
15170        editor: Entity<Editor>,
15171        window: &mut Window,
15172        cx: &mut App,
15173    ) -> Option<AnyElement> {
15174        let folded = self.is_line_folded(buffer_row);
15175        let mut is_foldable = false;
15176
15177        if let Some(crease) = self
15178            .crease_snapshot
15179            .query_row(buffer_row, &self.buffer_snapshot)
15180        {
15181            is_foldable = true;
15182            match crease {
15183                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15184                    if let Some(render_toggle) = render_toggle {
15185                        let toggle_callback =
15186                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15187                                if folded {
15188                                    editor.update(cx, |editor, cx| {
15189                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15190                                    });
15191                                } else {
15192                                    editor.update(cx, |editor, cx| {
15193                                        editor.unfold_at(
15194                                            &crate::UnfoldAt { buffer_row },
15195                                            window,
15196                                            cx,
15197                                        )
15198                                    });
15199                                }
15200                            });
15201                        return Some((render_toggle)(
15202                            buffer_row,
15203                            folded,
15204                            toggle_callback,
15205                            window,
15206                            cx,
15207                        ));
15208                    }
15209                }
15210            }
15211        }
15212
15213        is_foldable |= self.starts_indent(buffer_row);
15214
15215        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15216            Some(
15217                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15218                    .toggle_state(folded)
15219                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15220                        if folded {
15221                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15222                        } else {
15223                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15224                        }
15225                    }))
15226                    .into_any_element(),
15227            )
15228        } else {
15229            None
15230        }
15231    }
15232
15233    pub fn render_crease_trailer(
15234        &self,
15235        buffer_row: MultiBufferRow,
15236        window: &mut Window,
15237        cx: &mut App,
15238    ) -> Option<AnyElement> {
15239        let folded = self.is_line_folded(buffer_row);
15240        if let Crease::Inline { render_trailer, .. } = self
15241            .crease_snapshot
15242            .query_row(buffer_row, &self.buffer_snapshot)?
15243        {
15244            let render_trailer = render_trailer.as_ref()?;
15245            Some(render_trailer(buffer_row, folded, window, cx))
15246        } else {
15247            None
15248        }
15249    }
15250}
15251
15252impl Deref for EditorSnapshot {
15253    type Target = DisplaySnapshot;
15254
15255    fn deref(&self) -> &Self::Target {
15256        &self.display_snapshot
15257    }
15258}
15259
15260#[derive(Clone, Debug, PartialEq, Eq)]
15261pub enum EditorEvent {
15262    InputIgnored {
15263        text: Arc<str>,
15264    },
15265    InputHandled {
15266        utf16_range_to_replace: Option<Range<isize>>,
15267        text: Arc<str>,
15268    },
15269    ExcerptsAdded {
15270        buffer: Entity<Buffer>,
15271        predecessor: ExcerptId,
15272        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15273    },
15274    ExcerptsRemoved {
15275        ids: Vec<ExcerptId>,
15276    },
15277    BufferFoldToggled {
15278        ids: Vec<ExcerptId>,
15279        folded: bool,
15280    },
15281    ExcerptsEdited {
15282        ids: Vec<ExcerptId>,
15283    },
15284    ExcerptsExpanded {
15285        ids: Vec<ExcerptId>,
15286    },
15287    BufferEdited,
15288    Edited {
15289        transaction_id: clock::Lamport,
15290    },
15291    Reparsed(BufferId),
15292    Focused,
15293    FocusedIn,
15294    Blurred,
15295    DirtyChanged,
15296    Saved,
15297    TitleChanged,
15298    DiffBaseChanged,
15299    SelectionsChanged {
15300        local: bool,
15301    },
15302    ScrollPositionChanged {
15303        local: bool,
15304        autoscroll: bool,
15305    },
15306    Closed,
15307    TransactionUndone {
15308        transaction_id: clock::Lamport,
15309    },
15310    TransactionBegun {
15311        transaction_id: clock::Lamport,
15312    },
15313    Reloaded,
15314    CursorShapeChanged,
15315}
15316
15317impl EventEmitter<EditorEvent> for Editor {}
15318
15319impl Focusable for Editor {
15320    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15321        self.focus_handle.clone()
15322    }
15323}
15324
15325impl Render for Editor {
15326    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15327        let settings = ThemeSettings::get_global(cx);
15328
15329        let mut text_style = match self.mode {
15330            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15331                color: cx.theme().colors().editor_foreground,
15332                font_family: settings.ui_font.family.clone(),
15333                font_features: settings.ui_font.features.clone(),
15334                font_fallbacks: settings.ui_font.fallbacks.clone(),
15335                font_size: rems(0.875).into(),
15336                font_weight: settings.ui_font.weight,
15337                line_height: relative(settings.buffer_line_height.value()),
15338                ..Default::default()
15339            },
15340            EditorMode::Full => TextStyle {
15341                color: cx.theme().colors().editor_foreground,
15342                font_family: settings.buffer_font.family.clone(),
15343                font_features: settings.buffer_font.features.clone(),
15344                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15345                font_size: settings.buffer_font_size().into(),
15346                font_weight: settings.buffer_font.weight,
15347                line_height: relative(settings.buffer_line_height.value()),
15348                ..Default::default()
15349            },
15350        };
15351        if let Some(text_style_refinement) = &self.text_style_refinement {
15352            text_style.refine(text_style_refinement)
15353        }
15354
15355        let background = match self.mode {
15356            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15357            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15358            EditorMode::Full => cx.theme().colors().editor_background,
15359        };
15360
15361        EditorElement::new(
15362            &cx.entity(),
15363            EditorStyle {
15364                background,
15365                local_player: cx.theme().players().local(),
15366                text: text_style,
15367                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15368                syntax: cx.theme().syntax().clone(),
15369                status: cx.theme().status().clone(),
15370                inlay_hints_style: make_inlay_hints_style(cx),
15371                inline_completion_styles: make_suggestion_styles(cx),
15372                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15373            },
15374        )
15375    }
15376}
15377
15378impl EntityInputHandler for Editor {
15379    fn text_for_range(
15380        &mut self,
15381        range_utf16: Range<usize>,
15382        adjusted_range: &mut Option<Range<usize>>,
15383        _: &mut Window,
15384        cx: &mut Context<Self>,
15385    ) -> Option<String> {
15386        let snapshot = self.buffer.read(cx).read(cx);
15387        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15388        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15389        if (start.0..end.0) != range_utf16 {
15390            adjusted_range.replace(start.0..end.0);
15391        }
15392        Some(snapshot.text_for_range(start..end).collect())
15393    }
15394
15395    fn selected_text_range(
15396        &mut self,
15397        ignore_disabled_input: bool,
15398        _: &mut Window,
15399        cx: &mut Context<Self>,
15400    ) -> Option<UTF16Selection> {
15401        // Prevent the IME menu from appearing when holding down an alphabetic key
15402        // while input is disabled.
15403        if !ignore_disabled_input && !self.input_enabled {
15404            return None;
15405        }
15406
15407        let selection = self.selections.newest::<OffsetUtf16>(cx);
15408        let range = selection.range();
15409
15410        Some(UTF16Selection {
15411            range: range.start.0..range.end.0,
15412            reversed: selection.reversed,
15413        })
15414    }
15415
15416    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15417        let snapshot = self.buffer.read(cx).read(cx);
15418        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15419        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15420    }
15421
15422    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15423        self.clear_highlights::<InputComposition>(cx);
15424        self.ime_transaction.take();
15425    }
15426
15427    fn replace_text_in_range(
15428        &mut self,
15429        range_utf16: Option<Range<usize>>,
15430        text: &str,
15431        window: &mut Window,
15432        cx: &mut Context<Self>,
15433    ) {
15434        if !self.input_enabled {
15435            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15436            return;
15437        }
15438
15439        self.transact(window, cx, |this, window, cx| {
15440            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15441                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15442                Some(this.selection_replacement_ranges(range_utf16, cx))
15443            } else {
15444                this.marked_text_ranges(cx)
15445            };
15446
15447            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15448                let newest_selection_id = this.selections.newest_anchor().id;
15449                this.selections
15450                    .all::<OffsetUtf16>(cx)
15451                    .iter()
15452                    .zip(ranges_to_replace.iter())
15453                    .find_map(|(selection, range)| {
15454                        if selection.id == newest_selection_id {
15455                            Some(
15456                                (range.start.0 as isize - selection.head().0 as isize)
15457                                    ..(range.end.0 as isize - selection.head().0 as isize),
15458                            )
15459                        } else {
15460                            None
15461                        }
15462                    })
15463            });
15464
15465            cx.emit(EditorEvent::InputHandled {
15466                utf16_range_to_replace: range_to_replace,
15467                text: text.into(),
15468            });
15469
15470            if let Some(new_selected_ranges) = new_selected_ranges {
15471                this.change_selections(None, window, cx, |selections| {
15472                    selections.select_ranges(new_selected_ranges)
15473                });
15474                this.backspace(&Default::default(), window, cx);
15475            }
15476
15477            this.handle_input(text, window, cx);
15478        });
15479
15480        if let Some(transaction) = self.ime_transaction {
15481            self.buffer.update(cx, |buffer, cx| {
15482                buffer.group_until_transaction(transaction, cx);
15483            });
15484        }
15485
15486        self.unmark_text(window, cx);
15487    }
15488
15489    fn replace_and_mark_text_in_range(
15490        &mut self,
15491        range_utf16: Option<Range<usize>>,
15492        text: &str,
15493        new_selected_range_utf16: Option<Range<usize>>,
15494        window: &mut Window,
15495        cx: &mut Context<Self>,
15496    ) {
15497        if !self.input_enabled {
15498            return;
15499        }
15500
15501        let transaction = self.transact(window, cx, |this, window, cx| {
15502            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15503                let snapshot = this.buffer.read(cx).read(cx);
15504                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15505                    for marked_range in &mut marked_ranges {
15506                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15507                        marked_range.start.0 += relative_range_utf16.start;
15508                        marked_range.start =
15509                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15510                        marked_range.end =
15511                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15512                    }
15513                }
15514                Some(marked_ranges)
15515            } else if let Some(range_utf16) = range_utf16 {
15516                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15517                Some(this.selection_replacement_ranges(range_utf16, cx))
15518            } else {
15519                None
15520            };
15521
15522            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15523                let newest_selection_id = this.selections.newest_anchor().id;
15524                this.selections
15525                    .all::<OffsetUtf16>(cx)
15526                    .iter()
15527                    .zip(ranges_to_replace.iter())
15528                    .find_map(|(selection, range)| {
15529                        if selection.id == newest_selection_id {
15530                            Some(
15531                                (range.start.0 as isize - selection.head().0 as isize)
15532                                    ..(range.end.0 as isize - selection.head().0 as isize),
15533                            )
15534                        } else {
15535                            None
15536                        }
15537                    })
15538            });
15539
15540            cx.emit(EditorEvent::InputHandled {
15541                utf16_range_to_replace: range_to_replace,
15542                text: text.into(),
15543            });
15544
15545            if let Some(ranges) = ranges_to_replace {
15546                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15547            }
15548
15549            let marked_ranges = {
15550                let snapshot = this.buffer.read(cx).read(cx);
15551                this.selections
15552                    .disjoint_anchors()
15553                    .iter()
15554                    .map(|selection| {
15555                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15556                    })
15557                    .collect::<Vec<_>>()
15558            };
15559
15560            if text.is_empty() {
15561                this.unmark_text(window, cx);
15562            } else {
15563                this.highlight_text::<InputComposition>(
15564                    marked_ranges.clone(),
15565                    HighlightStyle {
15566                        underline: Some(UnderlineStyle {
15567                            thickness: px(1.),
15568                            color: None,
15569                            wavy: false,
15570                        }),
15571                        ..Default::default()
15572                    },
15573                    cx,
15574                );
15575            }
15576
15577            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15578            let use_autoclose = this.use_autoclose;
15579            let use_auto_surround = this.use_auto_surround;
15580            this.set_use_autoclose(false);
15581            this.set_use_auto_surround(false);
15582            this.handle_input(text, window, cx);
15583            this.set_use_autoclose(use_autoclose);
15584            this.set_use_auto_surround(use_auto_surround);
15585
15586            if let Some(new_selected_range) = new_selected_range_utf16 {
15587                let snapshot = this.buffer.read(cx).read(cx);
15588                let new_selected_ranges = marked_ranges
15589                    .into_iter()
15590                    .map(|marked_range| {
15591                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15592                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15593                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15594                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15595                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15596                    })
15597                    .collect::<Vec<_>>();
15598
15599                drop(snapshot);
15600                this.change_selections(None, window, cx, |selections| {
15601                    selections.select_ranges(new_selected_ranges)
15602                });
15603            }
15604        });
15605
15606        self.ime_transaction = self.ime_transaction.or(transaction);
15607        if let Some(transaction) = self.ime_transaction {
15608            self.buffer.update(cx, |buffer, cx| {
15609                buffer.group_until_transaction(transaction, cx);
15610            });
15611        }
15612
15613        if self.text_highlights::<InputComposition>(cx).is_none() {
15614            self.ime_transaction.take();
15615        }
15616    }
15617
15618    fn bounds_for_range(
15619        &mut self,
15620        range_utf16: Range<usize>,
15621        element_bounds: gpui::Bounds<Pixels>,
15622        window: &mut Window,
15623        cx: &mut Context<Self>,
15624    ) -> Option<gpui::Bounds<Pixels>> {
15625        let text_layout_details = self.text_layout_details(window);
15626        let gpui::Point {
15627            x: em_width,
15628            y: line_height,
15629        } = self.character_size(window);
15630
15631        let snapshot = self.snapshot(window, cx);
15632        let scroll_position = snapshot.scroll_position();
15633        let scroll_left = scroll_position.x * em_width;
15634
15635        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15636        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15637            + self.gutter_dimensions.width
15638            + self.gutter_dimensions.margin;
15639        let y = line_height * (start.row().as_f32() - scroll_position.y);
15640
15641        Some(Bounds {
15642            origin: element_bounds.origin + point(x, y),
15643            size: size(em_width, line_height),
15644        })
15645    }
15646}
15647
15648trait SelectionExt {
15649    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15650    fn spanned_rows(
15651        &self,
15652        include_end_if_at_line_start: bool,
15653        map: &DisplaySnapshot,
15654    ) -> Range<MultiBufferRow>;
15655}
15656
15657impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15658    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15659        let start = self
15660            .start
15661            .to_point(&map.buffer_snapshot)
15662            .to_display_point(map);
15663        let end = self
15664            .end
15665            .to_point(&map.buffer_snapshot)
15666            .to_display_point(map);
15667        if self.reversed {
15668            end..start
15669        } else {
15670            start..end
15671        }
15672    }
15673
15674    fn spanned_rows(
15675        &self,
15676        include_end_if_at_line_start: bool,
15677        map: &DisplaySnapshot,
15678    ) -> Range<MultiBufferRow> {
15679        let start = self.start.to_point(&map.buffer_snapshot);
15680        let mut end = self.end.to_point(&map.buffer_snapshot);
15681        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15682            end.row -= 1;
15683        }
15684
15685        let buffer_start = map.prev_line_boundary(start).0;
15686        let buffer_end = map.next_line_boundary(end).0;
15687        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15688    }
15689}
15690
15691impl<T: InvalidationRegion> InvalidationStack<T> {
15692    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15693    where
15694        S: Clone + ToOffset,
15695    {
15696        while let Some(region) = self.last() {
15697            let all_selections_inside_invalidation_ranges =
15698                if selections.len() == region.ranges().len() {
15699                    selections
15700                        .iter()
15701                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15702                        .all(|(selection, invalidation_range)| {
15703                            let head = selection.head().to_offset(buffer);
15704                            invalidation_range.start <= head && invalidation_range.end >= head
15705                        })
15706                } else {
15707                    false
15708                };
15709
15710            if all_selections_inside_invalidation_ranges {
15711                break;
15712            } else {
15713                self.pop();
15714            }
15715        }
15716    }
15717}
15718
15719impl<T> Default for InvalidationStack<T> {
15720    fn default() -> Self {
15721        Self(Default::default())
15722    }
15723}
15724
15725impl<T> Deref for InvalidationStack<T> {
15726    type Target = Vec<T>;
15727
15728    fn deref(&self) -> &Self::Target {
15729        &self.0
15730    }
15731}
15732
15733impl<T> DerefMut for InvalidationStack<T> {
15734    fn deref_mut(&mut self) -> &mut Self::Target {
15735        &mut self.0
15736    }
15737}
15738
15739impl InvalidationRegion for SnippetState {
15740    fn ranges(&self) -> &[Range<Anchor>] {
15741        &self.ranges[self.active_index]
15742    }
15743}
15744
15745pub fn diagnostic_block_renderer(
15746    diagnostic: Diagnostic,
15747    max_message_rows: Option<u8>,
15748    allow_closing: bool,
15749    _is_valid: bool,
15750) -> RenderBlock {
15751    let (text_without_backticks, code_ranges) =
15752        highlight_diagnostic_message(&diagnostic, max_message_rows);
15753
15754    Arc::new(move |cx: &mut BlockContext| {
15755        let group_id: SharedString = cx.block_id.to_string().into();
15756
15757        let mut text_style = cx.window.text_style().clone();
15758        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15759        let theme_settings = ThemeSettings::get_global(cx);
15760        text_style.font_family = theme_settings.buffer_font.family.clone();
15761        text_style.font_style = theme_settings.buffer_font.style;
15762        text_style.font_features = theme_settings.buffer_font.features.clone();
15763        text_style.font_weight = theme_settings.buffer_font.weight;
15764
15765        let multi_line_diagnostic = diagnostic.message.contains('\n');
15766
15767        let buttons = |diagnostic: &Diagnostic| {
15768            if multi_line_diagnostic {
15769                v_flex()
15770            } else {
15771                h_flex()
15772            }
15773            .when(allow_closing, |div| {
15774                div.children(diagnostic.is_primary.then(|| {
15775                    IconButton::new("close-block", IconName::XCircle)
15776                        .icon_color(Color::Muted)
15777                        .size(ButtonSize::Compact)
15778                        .style(ButtonStyle::Transparent)
15779                        .visible_on_hover(group_id.clone())
15780                        .on_click(move |_click, window, cx| {
15781                            window.dispatch_action(Box::new(Cancel), cx)
15782                        })
15783                        .tooltip(|window, cx| {
15784                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15785                        })
15786                }))
15787            })
15788            .child(
15789                IconButton::new("copy-block", IconName::Copy)
15790                    .icon_color(Color::Muted)
15791                    .size(ButtonSize::Compact)
15792                    .style(ButtonStyle::Transparent)
15793                    .visible_on_hover(group_id.clone())
15794                    .on_click({
15795                        let message = diagnostic.message.clone();
15796                        move |_click, _, cx| {
15797                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15798                        }
15799                    })
15800                    .tooltip(Tooltip::text("Copy diagnostic message")),
15801            )
15802        };
15803
15804        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15805            AvailableSpace::min_size(),
15806            cx.window,
15807            cx.app,
15808        );
15809
15810        h_flex()
15811            .id(cx.block_id)
15812            .group(group_id.clone())
15813            .relative()
15814            .size_full()
15815            .block_mouse_down()
15816            .pl(cx.gutter_dimensions.width)
15817            .w(cx.max_width - cx.gutter_dimensions.full_width())
15818            .child(
15819                div()
15820                    .flex()
15821                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15822                    .flex_shrink(),
15823            )
15824            .child(buttons(&diagnostic))
15825            .child(div().flex().flex_shrink_0().child(
15826                StyledText::new(text_without_backticks.clone()).with_highlights(
15827                    &text_style,
15828                    code_ranges.iter().map(|range| {
15829                        (
15830                            range.clone(),
15831                            HighlightStyle {
15832                                font_weight: Some(FontWeight::BOLD),
15833                                ..Default::default()
15834                            },
15835                        )
15836                    }),
15837                ),
15838            ))
15839            .into_any_element()
15840    })
15841}
15842
15843fn inline_completion_edit_text(
15844    current_snapshot: &BufferSnapshot,
15845    edits: &[(Range<Anchor>, String)],
15846    edit_preview: &EditPreview,
15847    include_deletions: bool,
15848    cx: &App,
15849) -> Option<HighlightedEdits> {
15850    let edits = edits
15851        .iter()
15852        .map(|(anchor, text)| {
15853            (
15854                anchor.start.text_anchor..anchor.end.text_anchor,
15855                text.clone(),
15856            )
15857        })
15858        .collect::<Vec<_>>();
15859
15860    Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15861}
15862
15863pub fn highlight_diagnostic_message(
15864    diagnostic: &Diagnostic,
15865    mut max_message_rows: Option<u8>,
15866) -> (SharedString, Vec<Range<usize>>) {
15867    let mut text_without_backticks = String::new();
15868    let mut code_ranges = Vec::new();
15869
15870    if let Some(source) = &diagnostic.source {
15871        text_without_backticks.push_str(source);
15872        code_ranges.push(0..source.len());
15873        text_without_backticks.push_str(": ");
15874    }
15875
15876    let mut prev_offset = 0;
15877    let mut in_code_block = false;
15878    let has_row_limit = max_message_rows.is_some();
15879    let mut newline_indices = diagnostic
15880        .message
15881        .match_indices('\n')
15882        .filter(|_| has_row_limit)
15883        .map(|(ix, _)| ix)
15884        .fuse()
15885        .peekable();
15886
15887    for (quote_ix, _) in diagnostic
15888        .message
15889        .match_indices('`')
15890        .chain([(diagnostic.message.len(), "")])
15891    {
15892        let mut first_newline_ix = None;
15893        let mut last_newline_ix = None;
15894        while let Some(newline_ix) = newline_indices.peek() {
15895            if *newline_ix < quote_ix {
15896                if first_newline_ix.is_none() {
15897                    first_newline_ix = Some(*newline_ix);
15898                }
15899                last_newline_ix = Some(*newline_ix);
15900
15901                if let Some(rows_left) = &mut max_message_rows {
15902                    if *rows_left == 0 {
15903                        break;
15904                    } else {
15905                        *rows_left -= 1;
15906                    }
15907                }
15908                let _ = newline_indices.next();
15909            } else {
15910                break;
15911            }
15912        }
15913        let prev_len = text_without_backticks.len();
15914        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15915        text_without_backticks.push_str(new_text);
15916        if in_code_block {
15917            code_ranges.push(prev_len..text_without_backticks.len());
15918        }
15919        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15920        in_code_block = !in_code_block;
15921        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15922            text_without_backticks.push_str("...");
15923            break;
15924        }
15925    }
15926
15927    (text_without_backticks.into(), code_ranges)
15928}
15929
15930fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15931    match severity {
15932        DiagnosticSeverity::ERROR => colors.error,
15933        DiagnosticSeverity::WARNING => colors.warning,
15934        DiagnosticSeverity::INFORMATION => colors.info,
15935        DiagnosticSeverity::HINT => colors.info,
15936        _ => colors.ignored,
15937    }
15938}
15939
15940pub fn styled_runs_for_code_label<'a>(
15941    label: &'a CodeLabel,
15942    syntax_theme: &'a theme::SyntaxTheme,
15943) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15944    let fade_out = HighlightStyle {
15945        fade_out: Some(0.35),
15946        ..Default::default()
15947    };
15948
15949    let mut prev_end = label.filter_range.end;
15950    label
15951        .runs
15952        .iter()
15953        .enumerate()
15954        .flat_map(move |(ix, (range, highlight_id))| {
15955            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15956                style
15957            } else {
15958                return Default::default();
15959            };
15960            let mut muted_style = style;
15961            muted_style.highlight(fade_out);
15962
15963            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15964            if range.start >= label.filter_range.end {
15965                if range.start > prev_end {
15966                    runs.push((prev_end..range.start, fade_out));
15967                }
15968                runs.push((range.clone(), muted_style));
15969            } else if range.end <= label.filter_range.end {
15970                runs.push((range.clone(), style));
15971            } else {
15972                runs.push((range.start..label.filter_range.end, style));
15973                runs.push((label.filter_range.end..range.end, muted_style));
15974            }
15975            prev_end = cmp::max(prev_end, range.end);
15976
15977            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15978                runs.push((prev_end..label.text.len(), fade_out));
15979            }
15980
15981            runs
15982        })
15983}
15984
15985pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15986    let mut prev_index = 0;
15987    let mut prev_codepoint: Option<char> = None;
15988    text.char_indices()
15989        .chain([(text.len(), '\0')])
15990        .filter_map(move |(index, codepoint)| {
15991            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15992            let is_boundary = index == text.len()
15993                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15994                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15995            if is_boundary {
15996                let chunk = &text[prev_index..index];
15997                prev_index = index;
15998                Some(chunk)
15999            } else {
16000                None
16001            }
16002        })
16003}
16004
16005pub trait RangeToAnchorExt: Sized {
16006    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16007
16008    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16009        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16010        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16011    }
16012}
16013
16014impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16015    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16016        let start_offset = self.start.to_offset(snapshot);
16017        let end_offset = self.end.to_offset(snapshot);
16018        if start_offset == end_offset {
16019            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16020        } else {
16021            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16022        }
16023    }
16024}
16025
16026pub trait RowExt {
16027    fn as_f32(&self) -> f32;
16028
16029    fn next_row(&self) -> Self;
16030
16031    fn previous_row(&self) -> Self;
16032
16033    fn minus(&self, other: Self) -> u32;
16034}
16035
16036impl RowExt for DisplayRow {
16037    fn as_f32(&self) -> f32 {
16038        self.0 as f32
16039    }
16040
16041    fn next_row(&self) -> Self {
16042        Self(self.0 + 1)
16043    }
16044
16045    fn previous_row(&self) -> Self {
16046        Self(self.0.saturating_sub(1))
16047    }
16048
16049    fn minus(&self, other: Self) -> u32 {
16050        self.0 - other.0
16051    }
16052}
16053
16054impl RowExt for MultiBufferRow {
16055    fn as_f32(&self) -> f32 {
16056        self.0 as f32
16057    }
16058
16059    fn next_row(&self) -> Self {
16060        Self(self.0 + 1)
16061    }
16062
16063    fn previous_row(&self) -> Self {
16064        Self(self.0.saturating_sub(1))
16065    }
16066
16067    fn minus(&self, other: Self) -> u32 {
16068        self.0 - other.0
16069    }
16070}
16071
16072trait RowRangeExt {
16073    type Row;
16074
16075    fn len(&self) -> usize;
16076
16077    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16078}
16079
16080impl RowRangeExt for Range<MultiBufferRow> {
16081    type Row = MultiBufferRow;
16082
16083    fn len(&self) -> usize {
16084        (self.end.0 - self.start.0) as usize
16085    }
16086
16087    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16088        (self.start.0..self.end.0).map(MultiBufferRow)
16089    }
16090}
16091
16092impl RowRangeExt for Range<DisplayRow> {
16093    type Row = DisplayRow;
16094
16095    fn len(&self) -> usize {
16096        (self.end.0 - self.start.0) as usize
16097    }
16098
16099    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16100        (self.start.0..self.end.0).map(DisplayRow)
16101    }
16102}
16103
16104/// If select range has more than one line, we
16105/// just point the cursor to range.start.
16106fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16107    if range.start.row == range.end.row {
16108        range
16109    } else {
16110        range.start..range.start
16111    }
16112}
16113pub struct KillRing(ClipboardItem);
16114impl Global for KillRing {}
16115
16116const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16117
16118fn all_edits_insertions_or_deletions(
16119    edits: &Vec<(Range<Anchor>, String)>,
16120    snapshot: &MultiBufferSnapshot,
16121) -> bool {
16122    let mut all_insertions = true;
16123    let mut all_deletions = true;
16124
16125    for (range, new_text) in edits.iter() {
16126        let range_is_empty = range.to_offset(&snapshot).is_empty();
16127        let text_is_empty = new_text.is_empty();
16128
16129        if range_is_empty != text_is_empty {
16130            if range_is_empty {
16131                all_deletions = false;
16132            } else {
16133                all_insertions = false;
16134            }
16135        } else {
16136            return false;
16137        }
16138
16139        if !all_insertions && !all_deletions {
16140            return false;
16141        }
16142    }
16143    all_insertions || all_deletions
16144}