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 hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   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, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  164use ui::{
  165    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  166    PopoverMenuHandle, Tooltip,
  167};
  168use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  169use workspace::item::{ItemHandle, PreviewTabsSettings};
  170use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  171use workspace::{
  172    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  173};
  174use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  175
  176use crate::hover_links::{find_url, find_url_from_range};
  177use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  178
  179pub const FILE_HEADER_HEIGHT: u32 = 2;
  180pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  181pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  182pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  183const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  184const MAX_LINE_LEN: usize = 1024;
  185const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  186const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  187pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  188#[doc(hidden)]
  189pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  190
  191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  193
  194pub fn render_parsed_markdown(
  195    element_id: impl Into<ElementId>,
  196    parsed: &language::ParsedMarkdown,
  197    editor_style: &EditorStyle,
  198    workspace: Option<WeakView<Workspace>>,
  199    cx: &mut WindowContext,
  200) -> InteractiveText {
  201    let code_span_background_color = cx
  202        .theme()
  203        .colors()
  204        .editor_document_highlight_read_background;
  205
  206    let highlights = gpui::combine_highlights(
  207        parsed.highlights.iter().filter_map(|(range, highlight)| {
  208            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  209            Some((range.clone(), highlight))
  210        }),
  211        parsed
  212            .regions
  213            .iter()
  214            .zip(&parsed.region_ranges)
  215            .filter_map(|(region, range)| {
  216                if region.code {
  217                    Some((
  218                        range.clone(),
  219                        HighlightStyle {
  220                            background_color: Some(code_span_background_color),
  221                            ..Default::default()
  222                        },
  223                    ))
  224                } else {
  225                    None
  226                }
  227            }),
  228    );
  229
  230    let mut links = Vec::new();
  231    let mut link_ranges = Vec::new();
  232    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  233        if let Some(link) = region.link.clone() {
  234            links.push(link);
  235            link_ranges.push(range.clone());
  236        }
  237    }
  238
  239    InteractiveText::new(
  240        element_id,
  241        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  242    )
  243    .on_click(link_ranges, move |clicked_range_ix, cx| {
  244        match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace.open_abs_path(path.clone(), false, cx).detach();
  250                    });
  251                }
  252            }
  253        }
  254    })
  255}
  256
  257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  258pub enum InlayId {
  259    InlineCompletion(usize),
  260    Hint(usize),
  261}
  262
  263impl InlayId {
  264    fn id(&self) -> usize {
  265        match self {
  266            Self::InlineCompletion(id) => *id,
  267            Self::Hint(id) => *id,
  268        }
  269    }
  270}
  271
  272enum DiffRowHighlight {}
  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 AppContext) {
  294    EditorSettings::register(cx);
  295}
  296
  297pub fn init(cx: &mut AppContext) {
  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_views(
  305        |workspace: &mut Workspace, _cx: &mut ViewContext<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(Default::default(), app_state, cx, |workspace, cx| {
  317                Editor::new_file(workspace, &Default::default(), cx)
  318            })
  319            .detach();
  320        }
  321    });
  322    cx.on_action(move |_: &workspace::NewWindow, cx| {
  323        let app_state = workspace::AppState::global(cx);
  324        if let Some(app_state) = app_state.upgrade() {
  325            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  326                Editor::new_file(workspace, &Default::default(), cx)
  327            })
  328            .detach();
  329        }
  330    });
  331    git::project_diff::init(cx);
  332}
  333
  334pub struct SearchWithinRange;
  335
  336trait InvalidationRegion {
  337    fn ranges(&self) -> &[Range<Anchor>];
  338}
  339
  340#[derive(Clone, Debug, PartialEq)]
  341pub enum SelectPhase {
  342    Begin {
  343        position: DisplayPoint,
  344        add: bool,
  345        click_count: usize,
  346    },
  347    BeginColumnar {
  348        position: DisplayPoint,
  349        reset: bool,
  350        goal_column: u32,
  351    },
  352    Extend {
  353        position: DisplayPoint,
  354        click_count: usize,
  355    },
  356    Update {
  357        position: DisplayPoint,
  358        goal_column: u32,
  359        scroll_delta: gpui::Point<f32>,
  360    },
  361    End,
  362}
  363
  364#[derive(Clone, Debug)]
  365pub enum SelectMode {
  366    Character,
  367    Word(Range<Anchor>),
  368    Line(Range<Anchor>),
  369    All,
  370}
  371
  372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  373pub enum EditorMode {
  374    SingleLine { auto_width: bool },
  375    AutoHeight { max_lines: usize },
  376    Full,
  377}
  378
  379#[derive(Copy, Clone, Debug)]
  380pub enum SoftWrap {
  381    /// Prefer not to wrap at all.
  382    ///
  383    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  384    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  385    GitDiff,
  386    /// Prefer a single line generally, unless an overly long line is encountered.
  387    None,
  388    /// Soft wrap lines that exceed the editor width.
  389    EditorWidth,
  390    /// Soft wrap lines at the preferred line length.
  391    Column(u32),
  392    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  393    Bounded(u32),
  394}
  395
  396#[derive(Clone)]
  397pub struct EditorStyle {
  398    pub background: Hsla,
  399    pub local_player: PlayerColor,
  400    pub text: TextStyle,
  401    pub scrollbar_width: Pixels,
  402    pub syntax: Arc<SyntaxTheme>,
  403    pub status: StatusColors,
  404    pub inlay_hints_style: HighlightStyle,
  405    pub inline_completion_styles: InlineCompletionStyles,
  406    pub unnecessary_code_fade: f32,
  407}
  408
  409impl Default for EditorStyle {
  410    fn default() -> Self {
  411        Self {
  412            background: Hsla::default(),
  413            local_player: PlayerColor::default(),
  414            text: TextStyle::default(),
  415            scrollbar_width: Pixels::default(),
  416            syntax: Default::default(),
  417            // HACK: Status colors don't have a real default.
  418            // We should look into removing the status colors from the editor
  419            // style and retrieve them directly from the theme.
  420            status: StatusColors::dark(),
  421            inlay_hints_style: HighlightStyle::default(),
  422            inline_completion_styles: InlineCompletionStyles {
  423                insertion: HighlightStyle::default(),
  424                whitespace: HighlightStyle::default(),
  425            },
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = language_settings::language_settings(None, None, cx)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  444    InlineCompletionStyles {
  445        insertion: HighlightStyle {
  446            color: Some(cx.theme().status().predictive),
  447            ..HighlightStyle::default()
  448        },
  449        whitespace: HighlightStyle {
  450            background_color: Some(cx.theme().status().created_background),
  451            ..HighlightStyle::default()
  452        },
  453    }
  454}
  455
  456type CompletionId = usize;
  457
  458#[derive(Debug, Clone)]
  459enum InlineCompletionMenuHint {
  460    Loading,
  461    Loaded { text: InlineCompletionText },
  462    None,
  463}
  464
  465impl InlineCompletionMenuHint {
  466    pub fn label(&self) -> &'static str {
  467        match self {
  468            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  469                "Edit Prediction"
  470            }
  471            InlineCompletionMenuHint::None => "No Prediction",
  472        }
  473    }
  474}
  475
  476#[derive(Clone, Debug)]
  477enum InlineCompletionText {
  478    Move(SharedString),
  479    Edit {
  480        text: SharedString,
  481        highlights: Vec<(Range<usize>, HighlightStyle)>,
  482    },
  483}
  484
  485enum InlineCompletion {
  486    Edit(Vec<(Range<Anchor>, String)>),
  487    Move(Anchor),
  488}
  489
  490struct InlineCompletionState {
  491    inlay_ids: Vec<InlayId>,
  492    completion: InlineCompletion,
  493    invalidation_range: Range<Anchor>,
  494}
  495
  496enum InlineCompletionHighlight {}
  497
  498#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  499struct EditorActionId(usize);
  500
  501impl EditorActionId {
  502    pub fn post_inc(&mut self) -> Self {
  503        let answer = self.0;
  504
  505        *self = Self(answer + 1);
  506
  507        Self(answer)
  508    }
  509}
  510
  511// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  512// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  513
  514type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  515type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  516
  517#[derive(Default)]
  518struct ScrollbarMarkerState {
  519    scrollbar_size: Size<Pixels>,
  520    dirty: bool,
  521    markers: Arc<[PaintQuad]>,
  522    pending_refresh: Option<Task<Result<()>>>,
  523}
  524
  525impl ScrollbarMarkerState {
  526    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  527        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  528    }
  529}
  530
  531#[derive(Clone, Debug)]
  532struct RunnableTasks {
  533    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  534    offset: MultiBufferOffset,
  535    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  536    column: u32,
  537    // Values of all named captures, including those starting with '_'
  538    extra_variables: HashMap<String, String>,
  539    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  540    context_range: Range<BufferOffset>,
  541}
  542
  543impl RunnableTasks {
  544    fn resolve<'a>(
  545        &'a self,
  546        cx: &'a task::TaskContext,
  547    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  548        self.templates.iter().filter_map(|(kind, template)| {
  549            template
  550                .resolve_task(&kind.to_id_base(), cx)
  551                .map(|task| (kind.clone(), task))
  552        })
  553    }
  554}
  555
  556#[derive(Clone)]
  557struct ResolvedTasks {
  558    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  559    position: Anchor,
  560}
  561#[derive(Copy, Clone, Debug)]
  562struct MultiBufferOffset(usize);
  563#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  564struct BufferOffset(usize);
  565
  566// Addons allow storing per-editor state in other crates (e.g. Vim)
  567pub trait Addon: 'static {
  568    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  569
  570    fn to_any(&self) -> &dyn std::any::Any;
  571}
  572
  573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  574pub enum IsVimMode {
  575    Yes,
  576    No,
  577}
  578
  579/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  580///
  581/// See the [module level documentation](self) for more information.
  582pub struct Editor {
  583    focus_handle: FocusHandle,
  584    last_focused_descendant: Option<WeakFocusHandle>,
  585    /// The text buffer being edited
  586    buffer: Model<MultiBuffer>,
  587    /// Map of how text in the buffer should be displayed.
  588    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  589    pub display_map: Model<DisplayMap>,
  590    pub selections: SelectionsCollection,
  591    pub scroll_manager: ScrollManager,
  592    /// When inline assist editors are linked, they all render cursors because
  593    /// typing enters text into each of them, even the ones that aren't focused.
  594    pub(crate) show_cursor_when_unfocused: bool,
  595    columnar_selection_tail: Option<Anchor>,
  596    add_selections_state: Option<AddSelectionsState>,
  597    select_next_state: Option<SelectNextState>,
  598    select_prev_state: Option<SelectNextState>,
  599    selection_history: SelectionHistory,
  600    autoclose_regions: Vec<AutocloseRegion>,
  601    snippet_stack: InvalidationStack<SnippetState>,
  602    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  603    ime_transaction: Option<TransactionId>,
  604    active_diagnostics: Option<ActiveDiagnosticGroup>,
  605    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  606
  607    project: Option<Model<Project>>,
  608    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  609    completion_provider: Option<Box<dyn CompletionProvider>>,
  610    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  611    blink_manager: Model<BlinkManager>,
  612    show_cursor_names: bool,
  613    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  614    pub show_local_selections: bool,
  615    mode: EditorMode,
  616    show_breadcrumbs: bool,
  617    show_gutter: bool,
  618    show_scrollbars: bool,
  619    show_line_numbers: Option<bool>,
  620    use_relative_line_numbers: Option<bool>,
  621    show_git_diff_gutter: Option<bool>,
  622    show_code_actions: Option<bool>,
  623    show_runnables: Option<bool>,
  624    show_wrap_guides: Option<bool>,
  625    show_indent_guides: Option<bool>,
  626    placeholder_text: Option<Arc<str>>,
  627    highlight_order: usize,
  628    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  629    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  630    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  631    scrollbar_marker_state: ScrollbarMarkerState,
  632    active_indent_guides_state: ActiveIndentGuidesState,
  633    nav_history: Option<ItemNavHistory>,
  634    context_menu: RefCell<Option<CodeContextMenu>>,
  635    mouse_context_menu: Option<MouseContextMenu>,
  636    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  637    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  638    signature_help_state: SignatureHelpState,
  639    auto_signature_help: Option<bool>,
  640    find_all_references_task_sources: Vec<Anchor>,
  641    next_completion_id: CompletionId,
  642    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  643    code_actions_task: Option<Task<Result<()>>>,
  644    document_highlights_task: Option<Task<()>>,
  645    linked_editing_range_task: Option<Task<Option<()>>>,
  646    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  647    pending_rename: Option<RenameState>,
  648    searchable: bool,
  649    cursor_shape: CursorShape,
  650    current_line_highlight: Option<CurrentLineHighlight>,
  651    collapse_matches: bool,
  652    autoindent_mode: Option<AutoindentMode>,
  653    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  654    input_enabled: bool,
  655    use_modal_editing: bool,
  656    read_only: bool,
  657    leader_peer_id: Option<PeerId>,
  658    remote_id: Option<ViewId>,
  659    hover_state: HoverState,
  660    gutter_hovered: bool,
  661    hovered_link_state: Option<HoveredLinkState>,
  662    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  663    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  664    active_inline_completion: Option<InlineCompletionState>,
  665    // enable_inline_completions is a switch that Vim can use to disable
  666    // inline completions based on its mode.
  667    enable_inline_completions: bool,
  668    show_inline_completions_override: Option<bool>,
  669    inlay_hint_cache: InlayHintCache,
  670    diff_map: DiffMap,
  671    next_inlay_id: usize,
  672    _subscriptions: Vec<Subscription>,
  673    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  674    gutter_dimensions: GutterDimensions,
  675    style: Option<EditorStyle>,
  676    text_style_refinement: Option<TextStyleRefinement>,
  677    next_editor_action_id: EditorActionId,
  678    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  679    use_autoclose: bool,
  680    use_auto_surround: bool,
  681    auto_replace_emoji_shortcode: bool,
  682    show_git_blame_gutter: bool,
  683    show_git_blame_inline: bool,
  684    show_git_blame_inline_delay_task: Option<Task<()>>,
  685    git_blame_inline_enabled: bool,
  686    serialize_dirty_buffers: bool,
  687    show_selection_menu: Option<bool>,
  688    blame: Option<Model<GitBlame>>,
  689    blame_subscription: Option<Subscription>,
  690    custom_context_menu: Option<
  691        Box<
  692            dyn 'static
  693                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  694        >,
  695    >,
  696    last_bounds: Option<Bounds<Pixels>>,
  697    expect_bounds_change: Option<Bounds<Pixels>>,
  698    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  699    tasks_update_task: Option<Task<()>>,
  700    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  701    breadcrumb_header: Option<String>,
  702    focused_block: Option<FocusedBlock>,
  703    next_scroll_position: NextScrollCursorCenterTopBottom,
  704    addons: HashMap<TypeId, Box<dyn Addon>>,
  705    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  706    toggle_fold_multiple_buffers: Task<()>,
  707    _scroll_cursor_center_top_bottom_task: Task<()>,
  708}
  709
  710#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  711enum NextScrollCursorCenterTopBottom {
  712    #[default]
  713    Center,
  714    Top,
  715    Bottom,
  716}
  717
  718impl NextScrollCursorCenterTopBottom {
  719    fn next(&self) -> Self {
  720        match self {
  721            Self::Center => Self::Top,
  722            Self::Top => Self::Bottom,
  723            Self::Bottom => Self::Center,
  724        }
  725    }
  726}
  727
  728#[derive(Clone)]
  729pub struct EditorSnapshot {
  730    pub mode: EditorMode,
  731    show_gutter: bool,
  732    show_line_numbers: Option<bool>,
  733    show_git_diff_gutter: Option<bool>,
  734    show_code_actions: Option<bool>,
  735    show_runnables: Option<bool>,
  736    git_blame_gutter_max_author_length: Option<usize>,
  737    pub display_snapshot: DisplaySnapshot,
  738    pub placeholder_text: Option<Arc<str>>,
  739    diff_map: DiffMapSnapshot,
  740    is_focused: bool,
  741    scroll_anchor: ScrollAnchor,
  742    ongoing_scroll: OngoingScroll,
  743    current_line_highlight: CurrentLineHighlight,
  744    gutter_hovered: bool,
  745}
  746
  747const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  748
  749#[derive(Default, Debug, Clone, Copy)]
  750pub struct GutterDimensions {
  751    pub left_padding: Pixels,
  752    pub right_padding: Pixels,
  753    pub width: Pixels,
  754    pub margin: Pixels,
  755    pub git_blame_entries_width: Option<Pixels>,
  756}
  757
  758impl GutterDimensions {
  759    /// The full width of the space taken up by the gutter.
  760    pub fn full_width(&self) -> Pixels {
  761        self.margin + self.width
  762    }
  763
  764    /// The width of the space reserved for the fold indicators,
  765    /// use alongside 'justify_end' and `gutter_width` to
  766    /// right align content with the line numbers
  767    pub fn fold_area_width(&self) -> Pixels {
  768        self.margin + self.right_padding
  769    }
  770}
  771
  772#[derive(Debug)]
  773pub struct RemoteSelection {
  774    pub replica_id: ReplicaId,
  775    pub selection: Selection<Anchor>,
  776    pub cursor_shape: CursorShape,
  777    pub peer_id: PeerId,
  778    pub line_mode: bool,
  779    pub participant_index: Option<ParticipantIndex>,
  780    pub user_name: Option<SharedString>,
  781}
  782
  783#[derive(Clone, Debug)]
  784struct SelectionHistoryEntry {
  785    selections: Arc<[Selection<Anchor>]>,
  786    select_next_state: Option<SelectNextState>,
  787    select_prev_state: Option<SelectNextState>,
  788    add_selections_state: Option<AddSelectionsState>,
  789}
  790
  791enum SelectionHistoryMode {
  792    Normal,
  793    Undoing,
  794    Redoing,
  795}
  796
  797#[derive(Clone, PartialEq, Eq, Hash)]
  798struct HoveredCursor {
  799    replica_id: u16,
  800    selection_id: usize,
  801}
  802
  803impl Default for SelectionHistoryMode {
  804    fn default() -> Self {
  805        Self::Normal
  806    }
  807}
  808
  809#[derive(Default)]
  810struct SelectionHistory {
  811    #[allow(clippy::type_complexity)]
  812    selections_by_transaction:
  813        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  814    mode: SelectionHistoryMode,
  815    undo_stack: VecDeque<SelectionHistoryEntry>,
  816    redo_stack: VecDeque<SelectionHistoryEntry>,
  817}
  818
  819impl SelectionHistory {
  820    fn insert_transaction(
  821        &mut self,
  822        transaction_id: TransactionId,
  823        selections: Arc<[Selection<Anchor>]>,
  824    ) {
  825        self.selections_by_transaction
  826            .insert(transaction_id, (selections, None));
  827    }
  828
  829    #[allow(clippy::type_complexity)]
  830    fn transaction(
  831        &self,
  832        transaction_id: TransactionId,
  833    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  834        self.selections_by_transaction.get(&transaction_id)
  835    }
  836
  837    #[allow(clippy::type_complexity)]
  838    fn transaction_mut(
  839        &mut self,
  840        transaction_id: TransactionId,
  841    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  842        self.selections_by_transaction.get_mut(&transaction_id)
  843    }
  844
  845    fn push(&mut self, entry: SelectionHistoryEntry) {
  846        if !entry.selections.is_empty() {
  847            match self.mode {
  848                SelectionHistoryMode::Normal => {
  849                    self.push_undo(entry);
  850                    self.redo_stack.clear();
  851                }
  852                SelectionHistoryMode::Undoing => self.push_redo(entry),
  853                SelectionHistoryMode::Redoing => self.push_undo(entry),
  854            }
  855        }
  856    }
  857
  858    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  859        if self
  860            .undo_stack
  861            .back()
  862            .map_or(true, |e| e.selections != entry.selections)
  863        {
  864            self.undo_stack.push_back(entry);
  865            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  866                self.undo_stack.pop_front();
  867            }
  868        }
  869    }
  870
  871    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  872        if self
  873            .redo_stack
  874            .back()
  875            .map_or(true, |e| e.selections != entry.selections)
  876        {
  877            self.redo_stack.push_back(entry);
  878            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  879                self.redo_stack.pop_front();
  880            }
  881        }
  882    }
  883}
  884
  885struct RowHighlight {
  886    index: usize,
  887    range: Range<Anchor>,
  888    color: Hsla,
  889    should_autoscroll: bool,
  890}
  891
  892#[derive(Clone, Debug)]
  893struct AddSelectionsState {
  894    above: bool,
  895    stack: Vec<usize>,
  896}
  897
  898#[derive(Clone)]
  899struct SelectNextState {
  900    query: AhoCorasick,
  901    wordwise: bool,
  902    done: bool,
  903}
  904
  905impl std::fmt::Debug for SelectNextState {
  906    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  907        f.debug_struct(std::any::type_name::<Self>())
  908            .field("wordwise", &self.wordwise)
  909            .field("done", &self.done)
  910            .finish()
  911    }
  912}
  913
  914#[derive(Debug)]
  915struct AutocloseRegion {
  916    selection_id: usize,
  917    range: Range<Anchor>,
  918    pair: BracketPair,
  919}
  920
  921#[derive(Debug)]
  922struct SnippetState {
  923    ranges: Vec<Vec<Range<Anchor>>>,
  924    active_index: usize,
  925    choices: Vec<Option<Vec<String>>>,
  926}
  927
  928#[doc(hidden)]
  929pub struct RenameState {
  930    pub range: Range<Anchor>,
  931    pub old_name: Arc<str>,
  932    pub editor: View<Editor>,
  933    block_id: CustomBlockId,
  934}
  935
  936struct InvalidationStack<T>(Vec<T>);
  937
  938struct RegisteredInlineCompletionProvider {
  939    provider: Arc<dyn InlineCompletionProviderHandle>,
  940    _subscription: Subscription,
  941}
  942
  943#[derive(Debug)]
  944struct ActiveDiagnosticGroup {
  945    primary_range: Range<Anchor>,
  946    primary_message: String,
  947    group_id: usize,
  948    blocks: HashMap<CustomBlockId, Diagnostic>,
  949    is_valid: bool,
  950}
  951
  952#[derive(Serialize, Deserialize, Clone, Debug)]
  953pub struct ClipboardSelection {
  954    pub len: usize,
  955    pub is_entire_line: bool,
  956    pub first_line_indent: u32,
  957}
  958
  959#[derive(Debug)]
  960pub(crate) struct NavigationData {
  961    cursor_anchor: Anchor,
  962    cursor_position: Point,
  963    scroll_anchor: ScrollAnchor,
  964    scroll_top_row: u32,
  965}
  966
  967#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  968pub enum GotoDefinitionKind {
  969    Symbol,
  970    Declaration,
  971    Type,
  972    Implementation,
  973}
  974
  975#[derive(Debug, Clone)]
  976enum InlayHintRefreshReason {
  977    Toggle(bool),
  978    SettingsChange(InlayHintSettings),
  979    NewLinesShown,
  980    BufferEdited(HashSet<Arc<Language>>),
  981    RefreshRequested,
  982    ExcerptsRemoved(Vec<ExcerptId>),
  983}
  984
  985impl InlayHintRefreshReason {
  986    fn description(&self) -> &'static str {
  987        match self {
  988            Self::Toggle(_) => "toggle",
  989            Self::SettingsChange(_) => "settings change",
  990            Self::NewLinesShown => "new lines shown",
  991            Self::BufferEdited(_) => "buffer edited",
  992            Self::RefreshRequested => "refresh requested",
  993            Self::ExcerptsRemoved(_) => "excerpts removed",
  994        }
  995    }
  996}
  997
  998pub enum FormatTarget {
  999    Buffers,
 1000    Ranges(Vec<Range<MultiBufferPoint>>),
 1001}
 1002
 1003pub(crate) struct FocusedBlock {
 1004    id: BlockId,
 1005    focus_handle: WeakFocusHandle,
 1006}
 1007
 1008#[derive(Clone)]
 1009enum JumpData {
 1010    MultiBufferRow {
 1011        row: MultiBufferRow,
 1012        line_offset_from_top: u32,
 1013    },
 1014    MultiBufferPoint {
 1015        excerpt_id: ExcerptId,
 1016        position: Point,
 1017        anchor: text::Anchor,
 1018        line_offset_from_top: u32,
 1019    },
 1020}
 1021
 1022impl Editor {
 1023    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1024        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1025        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1026        Self::new(
 1027            EditorMode::SingleLine { auto_width: false },
 1028            buffer,
 1029            None,
 1030            false,
 1031            cx,
 1032        )
 1033    }
 1034
 1035    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1036        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1037        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1038        Self::new(EditorMode::Full, buffer, None, false, cx)
 1039    }
 1040
 1041    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1042        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1043        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1044        Self::new(
 1045            EditorMode::SingleLine { auto_width: true },
 1046            buffer,
 1047            None,
 1048            false,
 1049            cx,
 1050        )
 1051    }
 1052
 1053    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1054        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1055        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1056        Self::new(
 1057            EditorMode::AutoHeight { max_lines },
 1058            buffer,
 1059            None,
 1060            false,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn for_buffer(
 1066        buffer: Model<Buffer>,
 1067        project: Option<Model<Project>>,
 1068        cx: &mut ViewContext<Self>,
 1069    ) -> Self {
 1070        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1071        Self::new(EditorMode::Full, buffer, project, false, cx)
 1072    }
 1073
 1074    pub fn for_multibuffer(
 1075        buffer: Model<MultiBuffer>,
 1076        project: Option<Model<Project>>,
 1077        show_excerpt_controls: bool,
 1078        cx: &mut ViewContext<Self>,
 1079    ) -> Self {
 1080        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1081    }
 1082
 1083    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1084        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1085        let mut clone = Self::new(
 1086            self.mode,
 1087            self.buffer.clone(),
 1088            self.project.clone(),
 1089            show_excerpt_controls,
 1090            cx,
 1091        );
 1092        self.display_map.update(cx, |display_map, cx| {
 1093            let snapshot = display_map.snapshot(cx);
 1094            clone.display_map.update(cx, |display_map, cx| {
 1095                display_map.set_state(&snapshot, cx);
 1096            });
 1097        });
 1098        clone.selections.clone_state(&self.selections);
 1099        clone.scroll_manager.clone_state(&self.scroll_manager);
 1100        clone.searchable = self.searchable;
 1101        clone
 1102    }
 1103
 1104    pub fn new(
 1105        mode: EditorMode,
 1106        buffer: Model<MultiBuffer>,
 1107        project: Option<Model<Project>>,
 1108        show_excerpt_controls: bool,
 1109        cx: &mut ViewContext<Self>,
 1110    ) -> Self {
 1111        let style = cx.text_style();
 1112        let font_size = style.font_size.to_pixels(cx.rem_size());
 1113        let editor = cx.view().downgrade();
 1114        let fold_placeholder = FoldPlaceholder {
 1115            constrain_width: true,
 1116            render: Arc::new(move |fold_id, fold_range, cx| {
 1117                let editor = editor.clone();
 1118                div()
 1119                    .id(fold_id)
 1120                    .bg(cx.theme().colors().ghost_element_background)
 1121                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1122                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1123                    .rounded_sm()
 1124                    .size_full()
 1125                    .cursor_pointer()
 1126                    .child("")
 1127                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1128                    .on_click(move |_, cx| {
 1129                        editor
 1130                            .update(cx, |editor, cx| {
 1131                                editor.unfold_ranges(
 1132                                    &[fold_range.start..fold_range.end],
 1133                                    true,
 1134                                    false,
 1135                                    cx,
 1136                                );
 1137                                cx.stop_propagation();
 1138                            })
 1139                            .ok();
 1140                    })
 1141                    .into_any()
 1142            }),
 1143            merge_adjacent: true,
 1144            ..Default::default()
 1145        };
 1146        let display_map = cx.new_model(|cx| {
 1147            DisplayMap::new(
 1148                buffer.clone(),
 1149                style.font(),
 1150                font_size,
 1151                None,
 1152                show_excerpt_controls,
 1153                FILE_HEADER_HEIGHT,
 1154                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1155                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1156                fold_placeholder,
 1157                cx,
 1158            )
 1159        });
 1160
 1161        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1162
 1163        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1164
 1165        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1166            .then(|| language_settings::SoftWrap::None);
 1167
 1168        let mut project_subscriptions = Vec::new();
 1169        if mode == EditorMode::Full {
 1170            if let Some(project) = project.as_ref() {
 1171                if buffer.read(cx).is_singleton() {
 1172                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1173                        cx.emit(EditorEvent::TitleChanged);
 1174                    }));
 1175                }
 1176                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1177                    if let project::Event::RefreshInlayHints = event {
 1178                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1179                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1180                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1181                            let focus_handle = editor.focus_handle(cx);
 1182                            if focus_handle.is_focused(cx) {
 1183                                let snapshot = buffer.read(cx).snapshot();
 1184                                for (range, snippet) in snippet_edits {
 1185                                    let editor_range =
 1186                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1187                                    editor
 1188                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1189                                        .ok();
 1190                                }
 1191                            }
 1192                        }
 1193                    }
 1194                }));
 1195                if let Some(task_inventory) = project
 1196                    .read(cx)
 1197                    .task_store()
 1198                    .read(cx)
 1199                    .task_inventory()
 1200                    .cloned()
 1201                {
 1202                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1203                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1204                    }));
 1205                }
 1206            }
 1207        }
 1208
 1209        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1210
 1211        let inlay_hint_settings =
 1212            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1213        let focus_handle = cx.focus_handle();
 1214        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1215        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1216            .detach();
 1217        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1218            .detach();
 1219        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1220
 1221        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1222            Some(false)
 1223        } else {
 1224            None
 1225        };
 1226
 1227        let mut code_action_providers = Vec::new();
 1228        if let Some(project) = project.clone() {
 1229            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1230            code_action_providers.push(Rc::new(project) as Rc<_>);
 1231        }
 1232
 1233        let mut this = Self {
 1234            focus_handle,
 1235            show_cursor_when_unfocused: false,
 1236            last_focused_descendant: None,
 1237            buffer: buffer.clone(),
 1238            display_map: display_map.clone(),
 1239            selections,
 1240            scroll_manager: ScrollManager::new(cx),
 1241            columnar_selection_tail: None,
 1242            add_selections_state: None,
 1243            select_next_state: None,
 1244            select_prev_state: None,
 1245            selection_history: Default::default(),
 1246            autoclose_regions: Default::default(),
 1247            snippet_stack: Default::default(),
 1248            select_larger_syntax_node_stack: Vec::new(),
 1249            ime_transaction: Default::default(),
 1250            active_diagnostics: None,
 1251            soft_wrap_mode_override,
 1252            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1253            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1254            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1255            project,
 1256            blink_manager: blink_manager.clone(),
 1257            show_local_selections: true,
 1258            show_scrollbars: true,
 1259            mode,
 1260            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1261            show_gutter: mode == EditorMode::Full,
 1262            show_line_numbers: None,
 1263            use_relative_line_numbers: None,
 1264            show_git_diff_gutter: None,
 1265            show_code_actions: None,
 1266            show_runnables: None,
 1267            show_wrap_guides: None,
 1268            show_indent_guides,
 1269            placeholder_text: None,
 1270            highlight_order: 0,
 1271            highlighted_rows: HashMap::default(),
 1272            background_highlights: Default::default(),
 1273            gutter_highlights: TreeMap::default(),
 1274            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1275            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1276            nav_history: None,
 1277            context_menu: RefCell::new(None),
 1278            mouse_context_menu: None,
 1279            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1280            completion_tasks: Default::default(),
 1281            signature_help_state: SignatureHelpState::default(),
 1282            auto_signature_help: None,
 1283            find_all_references_task_sources: Vec::new(),
 1284            next_completion_id: 0,
 1285            next_inlay_id: 0,
 1286            code_action_providers,
 1287            available_code_actions: Default::default(),
 1288            code_actions_task: Default::default(),
 1289            document_highlights_task: Default::default(),
 1290            linked_editing_range_task: Default::default(),
 1291            pending_rename: Default::default(),
 1292            searchable: true,
 1293            cursor_shape: EditorSettings::get_global(cx)
 1294                .cursor_shape
 1295                .unwrap_or_default(),
 1296            current_line_highlight: None,
 1297            autoindent_mode: Some(AutoindentMode::EachLine),
 1298            collapse_matches: false,
 1299            workspace: None,
 1300            input_enabled: true,
 1301            use_modal_editing: mode == EditorMode::Full,
 1302            read_only: false,
 1303            use_autoclose: true,
 1304            use_auto_surround: true,
 1305            auto_replace_emoji_shortcode: false,
 1306            leader_peer_id: None,
 1307            remote_id: None,
 1308            hover_state: Default::default(),
 1309            hovered_link_state: Default::default(),
 1310            inline_completion_provider: None,
 1311            active_inline_completion: None,
 1312            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1313            diff_map: DiffMap::default(),
 1314            gutter_hovered: false,
 1315            pixel_position_of_newest_cursor: None,
 1316            last_bounds: None,
 1317            expect_bounds_change: None,
 1318            gutter_dimensions: GutterDimensions::default(),
 1319            style: None,
 1320            show_cursor_names: false,
 1321            hovered_cursors: Default::default(),
 1322            next_editor_action_id: EditorActionId::default(),
 1323            editor_actions: Rc::default(),
 1324            show_inline_completions_override: None,
 1325            enable_inline_completions: true,
 1326            custom_context_menu: None,
 1327            show_git_blame_gutter: false,
 1328            show_git_blame_inline: false,
 1329            show_selection_menu: None,
 1330            show_git_blame_inline_delay_task: None,
 1331            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1332            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1333                .session
 1334                .restore_unsaved_buffers,
 1335            blame: None,
 1336            blame_subscription: None,
 1337            tasks: Default::default(),
 1338            _subscriptions: vec![
 1339                cx.observe(&buffer, Self::on_buffer_changed),
 1340                cx.subscribe(&buffer, Self::on_buffer_event),
 1341                cx.observe(&display_map, Self::on_display_map_changed),
 1342                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1343                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1344                cx.observe_window_activation(|editor, cx| {
 1345                    let active = cx.is_window_active();
 1346                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1347                        if active {
 1348                            blink_manager.enable(cx);
 1349                        } else {
 1350                            blink_manager.disable(cx);
 1351                        }
 1352                    });
 1353                }),
 1354            ],
 1355            tasks_update_task: None,
 1356            linked_edit_ranges: Default::default(),
 1357            previous_search_ranges: None,
 1358            breadcrumb_header: None,
 1359            focused_block: None,
 1360            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1361            addons: HashMap::default(),
 1362            registered_buffers: HashMap::default(),
 1363            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1364            toggle_fold_multiple_buffers: Task::ready(()),
 1365            text_style_refinement: None,
 1366        };
 1367        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1368        this._subscriptions.extend(project_subscriptions);
 1369
 1370        this.end_selection(cx);
 1371        this.scroll_manager.show_scrollbar(cx);
 1372
 1373        if mode == EditorMode::Full {
 1374            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1375            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1376
 1377            if this.git_blame_inline_enabled {
 1378                this.git_blame_inline_enabled = true;
 1379                this.start_git_blame_inline(false, cx);
 1380            }
 1381
 1382            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1383                if let Some(project) = this.project.as_ref() {
 1384                    let lsp_store = project.read(cx).lsp_store();
 1385                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1386                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1387                    });
 1388                    this.registered_buffers
 1389                        .insert(buffer.read(cx).remote_id(), handle);
 1390                }
 1391            }
 1392        }
 1393
 1394        this.report_editor_event("Editor Opened", None, cx);
 1395        this
 1396    }
 1397
 1398    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1399        self.mouse_context_menu
 1400            .as_ref()
 1401            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1402    }
 1403
 1404    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1405        let mut key_context = KeyContext::new_with_defaults();
 1406        key_context.add("Editor");
 1407        let mode = match self.mode {
 1408            EditorMode::SingleLine { .. } => "single_line",
 1409            EditorMode::AutoHeight { .. } => "auto_height",
 1410            EditorMode::Full => "full",
 1411        };
 1412
 1413        if EditorSettings::jupyter_enabled(cx) {
 1414            key_context.add("jupyter");
 1415        }
 1416
 1417        key_context.set("mode", mode);
 1418        if self.pending_rename.is_some() {
 1419            key_context.add("renaming");
 1420        }
 1421        match self.context_menu.borrow().as_ref() {
 1422            Some(CodeContextMenu::Completions(_)) => {
 1423                key_context.add("menu");
 1424                key_context.add("showing_completions")
 1425            }
 1426            Some(CodeContextMenu::CodeActions(_)) => {
 1427                key_context.add("menu");
 1428                key_context.add("showing_code_actions")
 1429            }
 1430            None => {}
 1431        }
 1432
 1433        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1434        if !self.focus_handle(cx).contains_focused(cx)
 1435            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1436        {
 1437            for addon in self.addons.values() {
 1438                addon.extend_key_context(&mut key_context, cx)
 1439            }
 1440        }
 1441
 1442        if let Some(extension) = self
 1443            .buffer
 1444            .read(cx)
 1445            .as_singleton()
 1446            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1447        {
 1448            key_context.set("extension", extension.to_string());
 1449        }
 1450
 1451        if self.has_active_inline_completion() {
 1452            key_context.add("copilot_suggestion");
 1453            key_context.add("inline_completion");
 1454        }
 1455
 1456        if !self
 1457            .selections
 1458            .disjoint
 1459            .iter()
 1460            .all(|selection| selection.start == selection.end)
 1461        {
 1462            key_context.add("selection");
 1463        }
 1464
 1465        key_context
 1466    }
 1467
 1468    pub fn new_file(
 1469        workspace: &mut Workspace,
 1470        _: &workspace::NewFile,
 1471        cx: &mut ViewContext<Workspace>,
 1472    ) {
 1473        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1474            "Failed to create buffer",
 1475            cx,
 1476            |e, _| match e.error_code() {
 1477                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1478                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1479                e.error_tag("required").unwrap_or("the latest version")
 1480            )),
 1481                _ => None,
 1482            },
 1483        );
 1484    }
 1485
 1486    pub fn new_in_workspace(
 1487        workspace: &mut Workspace,
 1488        cx: &mut ViewContext<Workspace>,
 1489    ) -> Task<Result<View<Editor>>> {
 1490        let project = workspace.project().clone();
 1491        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1492
 1493        cx.spawn(|workspace, mut cx| async move {
 1494            let buffer = create.await?;
 1495            workspace.update(&mut cx, |workspace, cx| {
 1496                let editor =
 1497                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1498                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1499                editor
 1500            })
 1501        })
 1502    }
 1503
 1504    fn new_file_vertical(
 1505        workspace: &mut Workspace,
 1506        _: &workspace::NewFileSplitVertical,
 1507        cx: &mut ViewContext<Workspace>,
 1508    ) {
 1509        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1510    }
 1511
 1512    fn new_file_horizontal(
 1513        workspace: &mut Workspace,
 1514        _: &workspace::NewFileSplitHorizontal,
 1515        cx: &mut ViewContext<Workspace>,
 1516    ) {
 1517        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1518    }
 1519
 1520    fn new_file_in_direction(
 1521        workspace: &mut Workspace,
 1522        direction: SplitDirection,
 1523        cx: &mut ViewContext<Workspace>,
 1524    ) {
 1525        let project = workspace.project().clone();
 1526        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1527
 1528        cx.spawn(|workspace, mut cx| async move {
 1529            let buffer = create.await?;
 1530            workspace.update(&mut cx, move |workspace, cx| {
 1531                workspace.split_item(
 1532                    direction,
 1533                    Box::new(
 1534                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1535                    ),
 1536                    cx,
 1537                )
 1538            })?;
 1539            anyhow::Ok(())
 1540        })
 1541        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1542            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1543                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1544                e.error_tag("required").unwrap_or("the latest version")
 1545            )),
 1546            _ => None,
 1547        });
 1548    }
 1549
 1550    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1551        self.leader_peer_id
 1552    }
 1553
 1554    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1555        &self.buffer
 1556    }
 1557
 1558    pub fn workspace(&self) -> Option<View<Workspace>> {
 1559        self.workspace.as_ref()?.0.upgrade()
 1560    }
 1561
 1562    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1563        self.buffer().read(cx).title(cx)
 1564    }
 1565
 1566    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1567        let git_blame_gutter_max_author_length = self
 1568            .render_git_blame_gutter(cx)
 1569            .then(|| {
 1570                if let Some(blame) = self.blame.as_ref() {
 1571                    let max_author_length =
 1572                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1573                    Some(max_author_length)
 1574                } else {
 1575                    None
 1576                }
 1577            })
 1578            .flatten();
 1579
 1580        EditorSnapshot {
 1581            mode: self.mode,
 1582            show_gutter: self.show_gutter,
 1583            show_line_numbers: self.show_line_numbers,
 1584            show_git_diff_gutter: self.show_git_diff_gutter,
 1585            show_code_actions: self.show_code_actions,
 1586            show_runnables: self.show_runnables,
 1587            git_blame_gutter_max_author_length,
 1588            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1589            scroll_anchor: self.scroll_manager.anchor(),
 1590            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1591            placeholder_text: self.placeholder_text.clone(),
 1592            diff_map: self.diff_map.snapshot(),
 1593            is_focused: self.focus_handle.is_focused(cx),
 1594            current_line_highlight: self
 1595                .current_line_highlight
 1596                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1597            gutter_hovered: self.gutter_hovered,
 1598        }
 1599    }
 1600
 1601    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1602        self.buffer.read(cx).language_at(point, cx)
 1603    }
 1604
 1605    pub fn file_at<T: ToOffset>(
 1606        &self,
 1607        point: T,
 1608        cx: &AppContext,
 1609    ) -> Option<Arc<dyn language::File>> {
 1610        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1611    }
 1612
 1613    pub fn active_excerpt(
 1614        &self,
 1615        cx: &AppContext,
 1616    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1617        self.buffer
 1618            .read(cx)
 1619            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1620    }
 1621
 1622    pub fn mode(&self) -> EditorMode {
 1623        self.mode
 1624    }
 1625
 1626    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1627        self.collaboration_hub.as_deref()
 1628    }
 1629
 1630    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1631        self.collaboration_hub = Some(hub);
 1632    }
 1633
 1634    pub fn set_custom_context_menu(
 1635        &mut self,
 1636        f: impl 'static
 1637            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1638    ) {
 1639        self.custom_context_menu = Some(Box::new(f))
 1640    }
 1641
 1642    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1643        self.completion_provider = provider;
 1644    }
 1645
 1646    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1647        self.semantics_provider.clone()
 1648    }
 1649
 1650    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1651        self.semantics_provider = provider;
 1652    }
 1653
 1654    pub fn set_inline_completion_provider<T>(
 1655        &mut self,
 1656        provider: Option<Model<T>>,
 1657        cx: &mut ViewContext<Self>,
 1658    ) where
 1659        T: InlineCompletionProvider,
 1660    {
 1661        self.inline_completion_provider =
 1662            provider.map(|provider| RegisteredInlineCompletionProvider {
 1663                _subscription: cx.observe(&provider, |this, _, cx| {
 1664                    if this.focus_handle.is_focused(cx) {
 1665                        this.update_visible_inline_completion(cx);
 1666                    }
 1667                }),
 1668                provider: Arc::new(provider),
 1669            });
 1670        self.refresh_inline_completion(false, false, cx);
 1671    }
 1672
 1673    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1674        self.placeholder_text.as_deref()
 1675    }
 1676
 1677    pub fn set_placeholder_text(
 1678        &mut self,
 1679        placeholder_text: impl Into<Arc<str>>,
 1680        cx: &mut ViewContext<Self>,
 1681    ) {
 1682        let placeholder_text = Some(placeholder_text.into());
 1683        if self.placeholder_text != placeholder_text {
 1684            self.placeholder_text = placeholder_text;
 1685            cx.notify();
 1686        }
 1687    }
 1688
 1689    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1690        self.cursor_shape = cursor_shape;
 1691
 1692        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1693        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1694
 1695        cx.notify();
 1696    }
 1697
 1698    pub fn set_current_line_highlight(
 1699        &mut self,
 1700        current_line_highlight: Option<CurrentLineHighlight>,
 1701    ) {
 1702        self.current_line_highlight = current_line_highlight;
 1703    }
 1704
 1705    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1706        self.collapse_matches = collapse_matches;
 1707    }
 1708
 1709    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1710        let buffers = self.buffer.read(cx).all_buffers();
 1711        let Some(lsp_store) = self.lsp_store(cx) else {
 1712            return;
 1713        };
 1714        lsp_store.update(cx, |lsp_store, cx| {
 1715            for buffer in buffers {
 1716                self.registered_buffers
 1717                    .entry(buffer.read(cx).remote_id())
 1718                    .or_insert_with(|| {
 1719                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1720                    });
 1721            }
 1722        })
 1723    }
 1724
 1725    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1726        if self.collapse_matches {
 1727            return range.start..range.start;
 1728        }
 1729        range.clone()
 1730    }
 1731
 1732    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1733        if self.display_map.read(cx).clip_at_line_ends != clip {
 1734            self.display_map
 1735                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1736        }
 1737    }
 1738
 1739    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1740        self.input_enabled = input_enabled;
 1741    }
 1742
 1743    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 1744        self.enable_inline_completions = enabled;
 1745        if !self.enable_inline_completions {
 1746            self.take_active_inline_completion(cx);
 1747            cx.notify();
 1748        }
 1749    }
 1750
 1751    pub fn set_autoindent(&mut self, autoindent: bool) {
 1752        if autoindent {
 1753            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1754        } else {
 1755            self.autoindent_mode = None;
 1756        }
 1757    }
 1758
 1759    pub fn read_only(&self, cx: &AppContext) -> bool {
 1760        self.read_only || self.buffer.read(cx).read_only()
 1761    }
 1762
 1763    pub fn set_read_only(&mut self, read_only: bool) {
 1764        self.read_only = read_only;
 1765    }
 1766
 1767    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1768        self.use_autoclose = autoclose;
 1769    }
 1770
 1771    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1772        self.use_auto_surround = auto_surround;
 1773    }
 1774
 1775    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1776        self.auto_replace_emoji_shortcode = auto_replace;
 1777    }
 1778
 1779    pub fn toggle_inline_completions(
 1780        &mut self,
 1781        _: &ToggleInlineCompletions,
 1782        cx: &mut ViewContext<Self>,
 1783    ) {
 1784        if self.show_inline_completions_override.is_some() {
 1785            self.set_show_inline_completions(None, cx);
 1786        } else {
 1787            let cursor = self.selections.newest_anchor().head();
 1788            if let Some((buffer, cursor_buffer_position)) =
 1789                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1790            {
 1791                let show_inline_completions =
 1792                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1793                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1794            }
 1795        }
 1796    }
 1797
 1798    pub fn set_show_inline_completions(
 1799        &mut self,
 1800        show_inline_completions: Option<bool>,
 1801        cx: &mut ViewContext<Self>,
 1802    ) {
 1803        self.show_inline_completions_override = show_inline_completions;
 1804        self.refresh_inline_completion(false, true, cx);
 1805    }
 1806
 1807    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1808        let cursor = self.selections.newest_anchor().head();
 1809        if let Some((buffer, buffer_position)) =
 1810            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1811        {
 1812            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1813        } else {
 1814            false
 1815        }
 1816    }
 1817
 1818    fn should_show_inline_completions(
 1819        &self,
 1820        buffer: &Model<Buffer>,
 1821        buffer_position: language::Anchor,
 1822        cx: &AppContext,
 1823    ) -> bool {
 1824        if !self.snippet_stack.is_empty() {
 1825            return false;
 1826        }
 1827
 1828        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1829            return false;
 1830        }
 1831
 1832        if let Some(provider) = self.inline_completion_provider() {
 1833            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1834                show_inline_completions
 1835            } else {
 1836                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1837            }
 1838        } else {
 1839            false
 1840        }
 1841    }
 1842
 1843    fn inline_completions_disabled_in_scope(
 1844        &self,
 1845        buffer: &Model<Buffer>,
 1846        buffer_position: language::Anchor,
 1847        cx: &AppContext,
 1848    ) -> bool {
 1849        let snapshot = buffer.read(cx).snapshot();
 1850        let settings = snapshot.settings_at(buffer_position, cx);
 1851
 1852        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1853            return false;
 1854        };
 1855
 1856        scope.override_name().map_or(false, |scope_name| {
 1857            settings
 1858                .inline_completions_disabled_in
 1859                .iter()
 1860                .any(|s| s == scope_name)
 1861        })
 1862    }
 1863
 1864    pub fn set_use_modal_editing(&mut self, to: bool) {
 1865        self.use_modal_editing = to;
 1866    }
 1867
 1868    pub fn use_modal_editing(&self) -> bool {
 1869        self.use_modal_editing
 1870    }
 1871
 1872    fn selections_did_change(
 1873        &mut self,
 1874        local: bool,
 1875        old_cursor_position: &Anchor,
 1876        show_completions: bool,
 1877        cx: &mut ViewContext<Self>,
 1878    ) {
 1879        cx.invalidate_character_coordinates();
 1880
 1881        // Copy selections to primary selection buffer
 1882        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1883        if local {
 1884            let selections = self.selections.all::<usize>(cx);
 1885            let buffer_handle = self.buffer.read(cx).read(cx);
 1886
 1887            let mut text = String::new();
 1888            for (index, selection) in selections.iter().enumerate() {
 1889                let text_for_selection = buffer_handle
 1890                    .text_for_range(selection.start..selection.end)
 1891                    .collect::<String>();
 1892
 1893                text.push_str(&text_for_selection);
 1894                if index != selections.len() - 1 {
 1895                    text.push('\n');
 1896                }
 1897            }
 1898
 1899            if !text.is_empty() {
 1900                cx.write_to_primary(ClipboardItem::new_string(text));
 1901            }
 1902        }
 1903
 1904        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1905            self.buffer.update(cx, |buffer, cx| {
 1906                buffer.set_active_selections(
 1907                    &self.selections.disjoint_anchors(),
 1908                    self.selections.line_mode,
 1909                    self.cursor_shape,
 1910                    cx,
 1911                )
 1912            });
 1913        }
 1914        let display_map = self
 1915            .display_map
 1916            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1917        let buffer = &display_map.buffer_snapshot;
 1918        self.add_selections_state = None;
 1919        self.select_next_state = None;
 1920        self.select_prev_state = None;
 1921        self.select_larger_syntax_node_stack.clear();
 1922        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1923        self.snippet_stack
 1924            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1925        self.take_rename(false, cx);
 1926
 1927        let new_cursor_position = self.selections.newest_anchor().head();
 1928
 1929        self.push_to_nav_history(
 1930            *old_cursor_position,
 1931            Some(new_cursor_position.to_point(buffer)),
 1932            cx,
 1933        );
 1934
 1935        if local {
 1936            let new_cursor_position = self.selections.newest_anchor().head();
 1937            let mut context_menu = self.context_menu.borrow_mut();
 1938            let completion_menu = match context_menu.as_ref() {
 1939                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1940                _ => {
 1941                    *context_menu = None;
 1942                    None
 1943                }
 1944            };
 1945
 1946            if let Some(completion_menu) = completion_menu {
 1947                let cursor_position = new_cursor_position.to_offset(buffer);
 1948                let (word_range, kind) =
 1949                    buffer.surrounding_word(completion_menu.initial_position, true);
 1950                if kind == Some(CharKind::Word)
 1951                    && word_range.to_inclusive().contains(&cursor_position)
 1952                {
 1953                    let mut completion_menu = completion_menu.clone();
 1954                    drop(context_menu);
 1955
 1956                    let query = Self::completion_query(buffer, cursor_position);
 1957                    cx.spawn(move |this, mut cx| async move {
 1958                        completion_menu
 1959                            .filter(query.as_deref(), cx.background_executor().clone())
 1960                            .await;
 1961
 1962                        this.update(&mut cx, |this, cx| {
 1963                            let mut context_menu = this.context_menu.borrow_mut();
 1964                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1965                            else {
 1966                                return;
 1967                            };
 1968
 1969                            if menu.id > completion_menu.id {
 1970                                return;
 1971                            }
 1972
 1973                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1974                            drop(context_menu);
 1975                            cx.notify();
 1976                        })
 1977                    })
 1978                    .detach();
 1979
 1980                    if show_completions {
 1981                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1982                    }
 1983                } else {
 1984                    drop(context_menu);
 1985                    self.hide_context_menu(cx);
 1986                }
 1987            } else {
 1988                drop(context_menu);
 1989            }
 1990
 1991            hide_hover(self, cx);
 1992
 1993            if old_cursor_position.to_display_point(&display_map).row()
 1994                != new_cursor_position.to_display_point(&display_map).row()
 1995            {
 1996                self.available_code_actions.take();
 1997            }
 1998            self.refresh_code_actions(cx);
 1999            self.refresh_document_highlights(cx);
 2000            refresh_matching_bracket_highlights(self, cx);
 2001            self.update_visible_inline_completion(cx);
 2002            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2003            if self.git_blame_inline_enabled {
 2004                self.start_inline_blame_timer(cx);
 2005            }
 2006        }
 2007
 2008        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2009        cx.emit(EditorEvent::SelectionsChanged { local });
 2010
 2011        if self.selections.disjoint_anchors().len() == 1 {
 2012            cx.emit(SearchEvent::ActiveMatchChanged)
 2013        }
 2014        cx.notify();
 2015    }
 2016
 2017    pub fn change_selections<R>(
 2018        &mut self,
 2019        autoscroll: Option<Autoscroll>,
 2020        cx: &mut ViewContext<Self>,
 2021        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2022    ) -> R {
 2023        self.change_selections_inner(autoscroll, true, cx, change)
 2024    }
 2025
 2026    pub fn change_selections_inner<R>(
 2027        &mut self,
 2028        autoscroll: Option<Autoscroll>,
 2029        request_completions: bool,
 2030        cx: &mut ViewContext<Self>,
 2031        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2032    ) -> R {
 2033        let old_cursor_position = self.selections.newest_anchor().head();
 2034        self.push_to_selection_history();
 2035
 2036        let (changed, result) = self.selections.change_with(cx, change);
 2037
 2038        if changed {
 2039            if let Some(autoscroll) = autoscroll {
 2040                self.request_autoscroll(autoscroll, cx);
 2041            }
 2042            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2043
 2044            if self.should_open_signature_help_automatically(
 2045                &old_cursor_position,
 2046                self.signature_help_state.backspace_pressed(),
 2047                cx,
 2048            ) {
 2049                self.show_signature_help(&ShowSignatureHelp, cx);
 2050            }
 2051            self.signature_help_state.set_backspace_pressed(false);
 2052        }
 2053
 2054        result
 2055    }
 2056
 2057    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2058    where
 2059        I: IntoIterator<Item = (Range<S>, T)>,
 2060        S: ToOffset,
 2061        T: Into<Arc<str>>,
 2062    {
 2063        if self.read_only(cx) {
 2064            return;
 2065        }
 2066
 2067        self.buffer
 2068            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2069    }
 2070
 2071    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2072    where
 2073        I: IntoIterator<Item = (Range<S>, T)>,
 2074        S: ToOffset,
 2075        T: Into<Arc<str>>,
 2076    {
 2077        if self.read_only(cx) {
 2078            return;
 2079        }
 2080
 2081        self.buffer.update(cx, |buffer, cx| {
 2082            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2083        });
 2084    }
 2085
 2086    pub fn edit_with_block_indent<I, S, T>(
 2087        &mut self,
 2088        edits: I,
 2089        original_indent_columns: Vec<u32>,
 2090        cx: &mut ViewContext<Self>,
 2091    ) where
 2092        I: IntoIterator<Item = (Range<S>, T)>,
 2093        S: ToOffset,
 2094        T: Into<Arc<str>>,
 2095    {
 2096        if self.read_only(cx) {
 2097            return;
 2098        }
 2099
 2100        self.buffer.update(cx, |buffer, cx| {
 2101            buffer.edit(
 2102                edits,
 2103                Some(AutoindentMode::Block {
 2104                    original_indent_columns,
 2105                }),
 2106                cx,
 2107            )
 2108        });
 2109    }
 2110
 2111    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2112        self.hide_context_menu(cx);
 2113
 2114        match phase {
 2115            SelectPhase::Begin {
 2116                position,
 2117                add,
 2118                click_count,
 2119            } => self.begin_selection(position, add, click_count, cx),
 2120            SelectPhase::BeginColumnar {
 2121                position,
 2122                goal_column,
 2123                reset,
 2124            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2125            SelectPhase::Extend {
 2126                position,
 2127                click_count,
 2128            } => self.extend_selection(position, click_count, cx),
 2129            SelectPhase::Update {
 2130                position,
 2131                goal_column,
 2132                scroll_delta,
 2133            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2134            SelectPhase::End => self.end_selection(cx),
 2135        }
 2136    }
 2137
 2138    fn extend_selection(
 2139        &mut self,
 2140        position: DisplayPoint,
 2141        click_count: usize,
 2142        cx: &mut ViewContext<Self>,
 2143    ) {
 2144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2145        let tail = self.selections.newest::<usize>(cx).tail();
 2146        self.begin_selection(position, false, click_count, cx);
 2147
 2148        let position = position.to_offset(&display_map, Bias::Left);
 2149        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2150
 2151        let mut pending_selection = self
 2152            .selections
 2153            .pending_anchor()
 2154            .expect("extend_selection not called with pending selection");
 2155        if position >= tail {
 2156            pending_selection.start = tail_anchor;
 2157        } else {
 2158            pending_selection.end = tail_anchor;
 2159            pending_selection.reversed = true;
 2160        }
 2161
 2162        let mut pending_mode = self.selections.pending_mode().unwrap();
 2163        match &mut pending_mode {
 2164            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2165            _ => {}
 2166        }
 2167
 2168        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2169            s.set_pending(pending_selection, pending_mode)
 2170        });
 2171    }
 2172
 2173    fn begin_selection(
 2174        &mut self,
 2175        position: DisplayPoint,
 2176        add: bool,
 2177        click_count: usize,
 2178        cx: &mut ViewContext<Self>,
 2179    ) {
 2180        if !self.focus_handle.is_focused(cx) {
 2181            self.last_focused_descendant = None;
 2182            cx.focus(&self.focus_handle);
 2183        }
 2184
 2185        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2186        let buffer = &display_map.buffer_snapshot;
 2187        let newest_selection = self.selections.newest_anchor().clone();
 2188        let position = display_map.clip_point(position, Bias::Left);
 2189
 2190        let start;
 2191        let end;
 2192        let mode;
 2193        let mut auto_scroll;
 2194        match click_count {
 2195            1 => {
 2196                start = buffer.anchor_before(position.to_point(&display_map));
 2197                end = start;
 2198                mode = SelectMode::Character;
 2199                auto_scroll = true;
 2200            }
 2201            2 => {
 2202                let range = movement::surrounding_word(&display_map, position);
 2203                start = buffer.anchor_before(range.start.to_point(&display_map));
 2204                end = buffer.anchor_before(range.end.to_point(&display_map));
 2205                mode = SelectMode::Word(start..end);
 2206                auto_scroll = true;
 2207            }
 2208            3 => {
 2209                let position = display_map
 2210                    .clip_point(position, Bias::Left)
 2211                    .to_point(&display_map);
 2212                let line_start = display_map.prev_line_boundary(position).0;
 2213                let next_line_start = buffer.clip_point(
 2214                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2215                    Bias::Left,
 2216                );
 2217                start = buffer.anchor_before(line_start);
 2218                end = buffer.anchor_before(next_line_start);
 2219                mode = SelectMode::Line(start..end);
 2220                auto_scroll = true;
 2221            }
 2222            _ => {
 2223                start = buffer.anchor_before(0);
 2224                end = buffer.anchor_before(buffer.len());
 2225                mode = SelectMode::All;
 2226                auto_scroll = false;
 2227            }
 2228        }
 2229        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2230
 2231        let point_to_delete: Option<usize> = {
 2232            let selected_points: Vec<Selection<Point>> =
 2233                self.selections.disjoint_in_range(start..end, cx);
 2234
 2235            if !add || click_count > 1 {
 2236                None
 2237            } else if !selected_points.is_empty() {
 2238                Some(selected_points[0].id)
 2239            } else {
 2240                let clicked_point_already_selected =
 2241                    self.selections.disjoint.iter().find(|selection| {
 2242                        selection.start.to_point(buffer) == start.to_point(buffer)
 2243                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2244                    });
 2245
 2246                clicked_point_already_selected.map(|selection| selection.id)
 2247            }
 2248        };
 2249
 2250        let selections_count = self.selections.count();
 2251
 2252        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2253            if let Some(point_to_delete) = point_to_delete {
 2254                s.delete(point_to_delete);
 2255
 2256                if selections_count == 1 {
 2257                    s.set_pending_anchor_range(start..end, mode);
 2258                }
 2259            } else {
 2260                if !add {
 2261                    s.clear_disjoint();
 2262                } else if click_count > 1 {
 2263                    s.delete(newest_selection.id)
 2264                }
 2265
 2266                s.set_pending_anchor_range(start..end, mode);
 2267            }
 2268        });
 2269    }
 2270
 2271    fn begin_columnar_selection(
 2272        &mut self,
 2273        position: DisplayPoint,
 2274        goal_column: u32,
 2275        reset: bool,
 2276        cx: &mut ViewContext<Self>,
 2277    ) {
 2278        if !self.focus_handle.is_focused(cx) {
 2279            self.last_focused_descendant = None;
 2280            cx.focus(&self.focus_handle);
 2281        }
 2282
 2283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2284
 2285        if reset {
 2286            let pointer_position = display_map
 2287                .buffer_snapshot
 2288                .anchor_before(position.to_point(&display_map));
 2289
 2290            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2291                s.clear_disjoint();
 2292                s.set_pending_anchor_range(
 2293                    pointer_position..pointer_position,
 2294                    SelectMode::Character,
 2295                );
 2296            });
 2297        }
 2298
 2299        let tail = self.selections.newest::<Point>(cx).tail();
 2300        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2301
 2302        if !reset {
 2303            self.select_columns(
 2304                tail.to_display_point(&display_map),
 2305                position,
 2306                goal_column,
 2307                &display_map,
 2308                cx,
 2309            );
 2310        }
 2311    }
 2312
 2313    fn update_selection(
 2314        &mut self,
 2315        position: DisplayPoint,
 2316        goal_column: u32,
 2317        scroll_delta: gpui::Point<f32>,
 2318        cx: &mut ViewContext<Self>,
 2319    ) {
 2320        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2321
 2322        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2323            let tail = tail.to_display_point(&display_map);
 2324            self.select_columns(tail, position, goal_column, &display_map, cx);
 2325        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2326            let buffer = self.buffer.read(cx).snapshot(cx);
 2327            let head;
 2328            let tail;
 2329            let mode = self.selections.pending_mode().unwrap();
 2330            match &mode {
 2331                SelectMode::Character => {
 2332                    head = position.to_point(&display_map);
 2333                    tail = pending.tail().to_point(&buffer);
 2334                }
 2335                SelectMode::Word(original_range) => {
 2336                    let original_display_range = original_range.start.to_display_point(&display_map)
 2337                        ..original_range.end.to_display_point(&display_map);
 2338                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2339                        ..original_display_range.end.to_point(&display_map);
 2340                    if movement::is_inside_word(&display_map, position)
 2341                        || original_display_range.contains(&position)
 2342                    {
 2343                        let word_range = movement::surrounding_word(&display_map, position);
 2344                        if word_range.start < original_display_range.start {
 2345                            head = word_range.start.to_point(&display_map);
 2346                        } else {
 2347                            head = word_range.end.to_point(&display_map);
 2348                        }
 2349                    } else {
 2350                        head = position.to_point(&display_map);
 2351                    }
 2352
 2353                    if head <= original_buffer_range.start {
 2354                        tail = original_buffer_range.end;
 2355                    } else {
 2356                        tail = original_buffer_range.start;
 2357                    }
 2358                }
 2359                SelectMode::Line(original_range) => {
 2360                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2361
 2362                    let position = display_map
 2363                        .clip_point(position, Bias::Left)
 2364                        .to_point(&display_map);
 2365                    let line_start = display_map.prev_line_boundary(position).0;
 2366                    let next_line_start = buffer.clip_point(
 2367                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2368                        Bias::Left,
 2369                    );
 2370
 2371                    if line_start < original_range.start {
 2372                        head = line_start
 2373                    } else {
 2374                        head = next_line_start
 2375                    }
 2376
 2377                    if head <= original_range.start {
 2378                        tail = original_range.end;
 2379                    } else {
 2380                        tail = original_range.start;
 2381                    }
 2382                }
 2383                SelectMode::All => {
 2384                    return;
 2385                }
 2386            };
 2387
 2388            if head < tail {
 2389                pending.start = buffer.anchor_before(head);
 2390                pending.end = buffer.anchor_before(tail);
 2391                pending.reversed = true;
 2392            } else {
 2393                pending.start = buffer.anchor_before(tail);
 2394                pending.end = buffer.anchor_before(head);
 2395                pending.reversed = false;
 2396            }
 2397
 2398            self.change_selections(None, cx, |s| {
 2399                s.set_pending(pending, mode);
 2400            });
 2401        } else {
 2402            log::error!("update_selection dispatched with no pending selection");
 2403            return;
 2404        }
 2405
 2406        self.apply_scroll_delta(scroll_delta, cx);
 2407        cx.notify();
 2408    }
 2409
 2410    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2411        self.columnar_selection_tail.take();
 2412        if self.selections.pending_anchor().is_some() {
 2413            let selections = self.selections.all::<usize>(cx);
 2414            self.change_selections(None, cx, |s| {
 2415                s.select(selections);
 2416                s.clear_pending();
 2417            });
 2418        }
 2419    }
 2420
 2421    fn select_columns(
 2422        &mut self,
 2423        tail: DisplayPoint,
 2424        head: DisplayPoint,
 2425        goal_column: u32,
 2426        display_map: &DisplaySnapshot,
 2427        cx: &mut ViewContext<Self>,
 2428    ) {
 2429        let start_row = cmp::min(tail.row(), head.row());
 2430        let end_row = cmp::max(tail.row(), head.row());
 2431        let start_column = cmp::min(tail.column(), goal_column);
 2432        let end_column = cmp::max(tail.column(), goal_column);
 2433        let reversed = start_column < tail.column();
 2434
 2435        let selection_ranges = (start_row.0..=end_row.0)
 2436            .map(DisplayRow)
 2437            .filter_map(|row| {
 2438                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2439                    let start = display_map
 2440                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2441                        .to_point(display_map);
 2442                    let end = display_map
 2443                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2444                        .to_point(display_map);
 2445                    if reversed {
 2446                        Some(end..start)
 2447                    } else {
 2448                        Some(start..end)
 2449                    }
 2450                } else {
 2451                    None
 2452                }
 2453            })
 2454            .collect::<Vec<_>>();
 2455
 2456        self.change_selections(None, cx, |s| {
 2457            s.select_ranges(selection_ranges);
 2458        });
 2459        cx.notify();
 2460    }
 2461
 2462    pub fn has_pending_nonempty_selection(&self) -> bool {
 2463        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2464            Some(Selection { start, end, .. }) => start != end,
 2465            None => false,
 2466        };
 2467
 2468        pending_nonempty_selection
 2469            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2470    }
 2471
 2472    pub fn has_pending_selection(&self) -> bool {
 2473        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2474    }
 2475
 2476    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2477        if self.clear_expanded_diff_hunks(cx) {
 2478            cx.notify();
 2479            return;
 2480        }
 2481        if self.dismiss_menus_and_popups(true, cx) {
 2482            return;
 2483        }
 2484
 2485        if self.mode == EditorMode::Full
 2486            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2487        {
 2488            return;
 2489        }
 2490
 2491        cx.propagate();
 2492    }
 2493
 2494    pub fn dismiss_menus_and_popups(
 2495        &mut self,
 2496        should_report_inline_completion_event: bool,
 2497        cx: &mut ViewContext<Self>,
 2498    ) -> bool {
 2499        if self.take_rename(false, cx).is_some() {
 2500            return true;
 2501        }
 2502
 2503        if hide_hover(self, cx) {
 2504            return true;
 2505        }
 2506
 2507        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2508            return true;
 2509        }
 2510
 2511        if self.hide_context_menu(cx).is_some() {
 2512            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2513                self.update_visible_inline_completion(cx);
 2514            }
 2515            return true;
 2516        }
 2517
 2518        if self.mouse_context_menu.take().is_some() {
 2519            return true;
 2520        }
 2521
 2522        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2523            return true;
 2524        }
 2525
 2526        if self.snippet_stack.pop().is_some() {
 2527            return true;
 2528        }
 2529
 2530        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2531            self.dismiss_diagnostics(cx);
 2532            return true;
 2533        }
 2534
 2535        false
 2536    }
 2537
 2538    fn linked_editing_ranges_for(
 2539        &self,
 2540        selection: Range<text::Anchor>,
 2541        cx: &AppContext,
 2542    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2543        if self.linked_edit_ranges.is_empty() {
 2544            return None;
 2545        }
 2546        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2547            selection.end.buffer_id.and_then(|end_buffer_id| {
 2548                if selection.start.buffer_id != Some(end_buffer_id) {
 2549                    return None;
 2550                }
 2551                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2552                let snapshot = buffer.read(cx).snapshot();
 2553                self.linked_edit_ranges
 2554                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2555                    .map(|ranges| (ranges, snapshot, buffer))
 2556            })?;
 2557        use text::ToOffset as TO;
 2558        // find offset from the start of current range to current cursor position
 2559        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2560
 2561        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2562        let start_difference = start_offset - start_byte_offset;
 2563        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2564        let end_difference = end_offset - start_byte_offset;
 2565        // Current range has associated linked ranges.
 2566        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2567        for range in linked_ranges.iter() {
 2568            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2569            let end_offset = start_offset + end_difference;
 2570            let start_offset = start_offset + start_difference;
 2571            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2572                continue;
 2573            }
 2574            if self.selections.disjoint_anchor_ranges().any(|s| {
 2575                if s.start.buffer_id != selection.start.buffer_id
 2576                    || s.end.buffer_id != selection.end.buffer_id
 2577                {
 2578                    return false;
 2579                }
 2580                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2581                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2582            }) {
 2583                continue;
 2584            }
 2585            let start = buffer_snapshot.anchor_after(start_offset);
 2586            let end = buffer_snapshot.anchor_after(end_offset);
 2587            linked_edits
 2588                .entry(buffer.clone())
 2589                .or_default()
 2590                .push(start..end);
 2591        }
 2592        Some(linked_edits)
 2593    }
 2594
 2595    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2596        let text: Arc<str> = text.into();
 2597
 2598        if self.read_only(cx) {
 2599            return;
 2600        }
 2601
 2602        let selections = self.selections.all_adjusted(cx);
 2603        let mut bracket_inserted = false;
 2604        let mut edits = Vec::new();
 2605        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2606        let mut new_selections = Vec::with_capacity(selections.len());
 2607        let mut new_autoclose_regions = Vec::new();
 2608        let snapshot = self.buffer.read(cx).read(cx);
 2609
 2610        for (selection, autoclose_region) in
 2611            self.selections_with_autoclose_regions(selections, &snapshot)
 2612        {
 2613            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2614                // Determine if the inserted text matches the opening or closing
 2615                // bracket of any of this language's bracket pairs.
 2616                let mut bracket_pair = None;
 2617                let mut is_bracket_pair_start = false;
 2618                let mut is_bracket_pair_end = false;
 2619                if !text.is_empty() {
 2620                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2621                    //  and they are removing the character that triggered IME popup.
 2622                    for (pair, enabled) in scope.brackets() {
 2623                        if !pair.close && !pair.surround {
 2624                            continue;
 2625                        }
 2626
 2627                        if enabled && pair.start.ends_with(text.as_ref()) {
 2628                            let prefix_len = pair.start.len() - text.len();
 2629                            let preceding_text_matches_prefix = prefix_len == 0
 2630                                || (selection.start.column >= (prefix_len as u32)
 2631                                    && snapshot.contains_str_at(
 2632                                        Point::new(
 2633                                            selection.start.row,
 2634                                            selection.start.column - (prefix_len as u32),
 2635                                        ),
 2636                                        &pair.start[..prefix_len],
 2637                                    ));
 2638                            if preceding_text_matches_prefix {
 2639                                bracket_pair = Some(pair.clone());
 2640                                is_bracket_pair_start = true;
 2641                                break;
 2642                            }
 2643                        }
 2644                        if pair.end.as_str() == text.as_ref() {
 2645                            bracket_pair = Some(pair.clone());
 2646                            is_bracket_pair_end = true;
 2647                            break;
 2648                        }
 2649                    }
 2650                }
 2651
 2652                if let Some(bracket_pair) = bracket_pair {
 2653                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2654                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2655                    let auto_surround =
 2656                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2657                    if selection.is_empty() {
 2658                        if is_bracket_pair_start {
 2659                            // If the inserted text is a suffix of an opening bracket and the
 2660                            // selection is preceded by the rest of the opening bracket, then
 2661                            // insert the closing bracket.
 2662                            let following_text_allows_autoclose = snapshot
 2663                                .chars_at(selection.start)
 2664                                .next()
 2665                                .map_or(true, |c| scope.should_autoclose_before(c));
 2666
 2667                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2668                                && bracket_pair.start.len() == 1
 2669                            {
 2670                                let target = bracket_pair.start.chars().next().unwrap();
 2671                                let current_line_count = snapshot
 2672                                    .reversed_chars_at(selection.start)
 2673                                    .take_while(|&c| c != '\n')
 2674                                    .filter(|&c| c == target)
 2675                                    .count();
 2676                                current_line_count % 2 == 1
 2677                            } else {
 2678                                false
 2679                            };
 2680
 2681                            if autoclose
 2682                                && bracket_pair.close
 2683                                && following_text_allows_autoclose
 2684                                && !is_closing_quote
 2685                            {
 2686                                let anchor = snapshot.anchor_before(selection.end);
 2687                                new_selections.push((selection.map(|_| anchor), text.len()));
 2688                                new_autoclose_regions.push((
 2689                                    anchor,
 2690                                    text.len(),
 2691                                    selection.id,
 2692                                    bracket_pair.clone(),
 2693                                ));
 2694                                edits.push((
 2695                                    selection.range(),
 2696                                    format!("{}{}", text, bracket_pair.end).into(),
 2697                                ));
 2698                                bracket_inserted = true;
 2699                                continue;
 2700                            }
 2701                        }
 2702
 2703                        if let Some(region) = autoclose_region {
 2704                            // If the selection is followed by an auto-inserted closing bracket,
 2705                            // then don't insert that closing bracket again; just move the selection
 2706                            // past the closing bracket.
 2707                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2708                                && text.as_ref() == region.pair.end.as_str();
 2709                            if should_skip {
 2710                                let anchor = snapshot.anchor_after(selection.end);
 2711                                new_selections
 2712                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2713                                continue;
 2714                            }
 2715                        }
 2716
 2717                        let always_treat_brackets_as_autoclosed = snapshot
 2718                            .settings_at(selection.start, cx)
 2719                            .always_treat_brackets_as_autoclosed;
 2720                        if always_treat_brackets_as_autoclosed
 2721                            && is_bracket_pair_end
 2722                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2723                        {
 2724                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2725                            // and the inserted text is a closing bracket and the selection is followed
 2726                            // by the closing bracket then move the selection past the closing bracket.
 2727                            let anchor = snapshot.anchor_after(selection.end);
 2728                            new_selections.push((selection.map(|_| anchor), text.len()));
 2729                            continue;
 2730                        }
 2731                    }
 2732                    // If an opening bracket is 1 character long and is typed while
 2733                    // text is selected, then surround that text with the bracket pair.
 2734                    else if auto_surround
 2735                        && bracket_pair.surround
 2736                        && is_bracket_pair_start
 2737                        && bracket_pair.start.chars().count() == 1
 2738                    {
 2739                        edits.push((selection.start..selection.start, text.clone()));
 2740                        edits.push((
 2741                            selection.end..selection.end,
 2742                            bracket_pair.end.as_str().into(),
 2743                        ));
 2744                        bracket_inserted = true;
 2745                        new_selections.push((
 2746                            Selection {
 2747                                id: selection.id,
 2748                                start: snapshot.anchor_after(selection.start),
 2749                                end: snapshot.anchor_before(selection.end),
 2750                                reversed: selection.reversed,
 2751                                goal: selection.goal,
 2752                            },
 2753                            0,
 2754                        ));
 2755                        continue;
 2756                    }
 2757                }
 2758            }
 2759
 2760            if self.auto_replace_emoji_shortcode
 2761                && selection.is_empty()
 2762                && text.as_ref().ends_with(':')
 2763            {
 2764                if let Some(possible_emoji_short_code) =
 2765                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2766                {
 2767                    if !possible_emoji_short_code.is_empty() {
 2768                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2769                            let emoji_shortcode_start = Point::new(
 2770                                selection.start.row,
 2771                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2772                            );
 2773
 2774                            // Remove shortcode from buffer
 2775                            edits.push((
 2776                                emoji_shortcode_start..selection.start,
 2777                                "".to_string().into(),
 2778                            ));
 2779                            new_selections.push((
 2780                                Selection {
 2781                                    id: selection.id,
 2782                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2783                                    end: snapshot.anchor_before(selection.start),
 2784                                    reversed: selection.reversed,
 2785                                    goal: selection.goal,
 2786                                },
 2787                                0,
 2788                            ));
 2789
 2790                            // Insert emoji
 2791                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2792                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2793                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2794
 2795                            continue;
 2796                        }
 2797                    }
 2798                }
 2799            }
 2800
 2801            // If not handling any auto-close operation, then just replace the selected
 2802            // text with the given input and move the selection to the end of the
 2803            // newly inserted text.
 2804            let anchor = snapshot.anchor_after(selection.end);
 2805            if !self.linked_edit_ranges.is_empty() {
 2806                let start_anchor = snapshot.anchor_before(selection.start);
 2807
 2808                let is_word_char = text.chars().next().map_or(true, |char| {
 2809                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2810                    classifier.is_word(char)
 2811                });
 2812
 2813                if is_word_char {
 2814                    if let Some(ranges) = self
 2815                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2816                    {
 2817                        for (buffer, edits) in ranges {
 2818                            linked_edits
 2819                                .entry(buffer.clone())
 2820                                .or_default()
 2821                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2822                        }
 2823                    }
 2824                }
 2825            }
 2826
 2827            new_selections.push((selection.map(|_| anchor), 0));
 2828            edits.push((selection.start..selection.end, text.clone()));
 2829        }
 2830
 2831        drop(snapshot);
 2832
 2833        self.transact(cx, |this, cx| {
 2834            this.buffer.update(cx, |buffer, cx| {
 2835                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2836            });
 2837            for (buffer, edits) in linked_edits {
 2838                buffer.update(cx, |buffer, cx| {
 2839                    let snapshot = buffer.snapshot();
 2840                    let edits = edits
 2841                        .into_iter()
 2842                        .map(|(range, text)| {
 2843                            use text::ToPoint as TP;
 2844                            let end_point = TP::to_point(&range.end, &snapshot);
 2845                            let start_point = TP::to_point(&range.start, &snapshot);
 2846                            (start_point..end_point, text)
 2847                        })
 2848                        .sorted_by_key(|(range, _)| range.start)
 2849                        .collect::<Vec<_>>();
 2850                    buffer.edit(edits, None, cx);
 2851                })
 2852            }
 2853            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2854            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2855            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2856            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2857                .zip(new_selection_deltas)
 2858                .map(|(selection, delta)| Selection {
 2859                    id: selection.id,
 2860                    start: selection.start + delta,
 2861                    end: selection.end + delta,
 2862                    reversed: selection.reversed,
 2863                    goal: SelectionGoal::None,
 2864                })
 2865                .collect::<Vec<_>>();
 2866
 2867            let mut i = 0;
 2868            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2869                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2870                let start = map.buffer_snapshot.anchor_before(position);
 2871                let end = map.buffer_snapshot.anchor_after(position);
 2872                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2873                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2874                        Ordering::Less => i += 1,
 2875                        Ordering::Greater => break,
 2876                        Ordering::Equal => {
 2877                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2878                                Ordering::Less => i += 1,
 2879                                Ordering::Equal => break,
 2880                                Ordering::Greater => break,
 2881                            }
 2882                        }
 2883                    }
 2884                }
 2885                this.autoclose_regions.insert(
 2886                    i,
 2887                    AutocloseRegion {
 2888                        selection_id,
 2889                        range: start..end,
 2890                        pair,
 2891                    },
 2892                );
 2893            }
 2894
 2895            let had_active_inline_completion = this.has_active_inline_completion();
 2896            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2897                s.select(new_selections)
 2898            });
 2899
 2900            if !bracket_inserted {
 2901                if let Some(on_type_format_task) =
 2902                    this.trigger_on_type_formatting(text.to_string(), cx)
 2903                {
 2904                    on_type_format_task.detach_and_log_err(cx);
 2905                }
 2906            }
 2907
 2908            let editor_settings = EditorSettings::get_global(cx);
 2909            if bracket_inserted
 2910                && (editor_settings.auto_signature_help
 2911                    || editor_settings.show_signature_help_after_edits)
 2912            {
 2913                this.show_signature_help(&ShowSignatureHelp, cx);
 2914            }
 2915
 2916            let trigger_in_words =
 2917                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2918            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2919            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2920            this.refresh_inline_completion(true, false, cx);
 2921        });
 2922    }
 2923
 2924    fn find_possible_emoji_shortcode_at_position(
 2925        snapshot: &MultiBufferSnapshot,
 2926        position: Point,
 2927    ) -> Option<String> {
 2928        let mut chars = Vec::new();
 2929        let mut found_colon = false;
 2930        for char in snapshot.reversed_chars_at(position).take(100) {
 2931            // Found a possible emoji shortcode in the middle of the buffer
 2932            if found_colon {
 2933                if char.is_whitespace() {
 2934                    chars.reverse();
 2935                    return Some(chars.iter().collect());
 2936                }
 2937                // If the previous character is not a whitespace, we are in the middle of a word
 2938                // and we only want to complete the shortcode if the word is made up of other emojis
 2939                let mut containing_word = String::new();
 2940                for ch in snapshot
 2941                    .reversed_chars_at(position)
 2942                    .skip(chars.len() + 1)
 2943                    .take(100)
 2944                {
 2945                    if ch.is_whitespace() {
 2946                        break;
 2947                    }
 2948                    containing_word.push(ch);
 2949                }
 2950                let containing_word = containing_word.chars().rev().collect::<String>();
 2951                if util::word_consists_of_emojis(containing_word.as_str()) {
 2952                    chars.reverse();
 2953                    return Some(chars.iter().collect());
 2954                }
 2955            }
 2956
 2957            if char.is_whitespace() || !char.is_ascii() {
 2958                return None;
 2959            }
 2960            if char == ':' {
 2961                found_colon = true;
 2962            } else {
 2963                chars.push(char);
 2964            }
 2965        }
 2966        // Found a possible emoji shortcode at the beginning of the buffer
 2967        chars.reverse();
 2968        Some(chars.iter().collect())
 2969    }
 2970
 2971    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2972        self.transact(cx, |this, cx| {
 2973            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2974                let selections = this.selections.all::<usize>(cx);
 2975                let multi_buffer = this.buffer.read(cx);
 2976                let buffer = multi_buffer.snapshot(cx);
 2977                selections
 2978                    .iter()
 2979                    .map(|selection| {
 2980                        let start_point = selection.start.to_point(&buffer);
 2981                        let mut indent =
 2982                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2983                        indent.len = cmp::min(indent.len, start_point.column);
 2984                        let start = selection.start;
 2985                        let end = selection.end;
 2986                        let selection_is_empty = start == end;
 2987                        let language_scope = buffer.language_scope_at(start);
 2988                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2989                            &language_scope
 2990                        {
 2991                            let leading_whitespace_len = buffer
 2992                                .reversed_chars_at(start)
 2993                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2994                                .map(|c| c.len_utf8())
 2995                                .sum::<usize>();
 2996
 2997                            let trailing_whitespace_len = buffer
 2998                                .chars_at(end)
 2999                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3000                                .map(|c| c.len_utf8())
 3001                                .sum::<usize>();
 3002
 3003                            let insert_extra_newline =
 3004                                language.brackets().any(|(pair, enabled)| {
 3005                                    let pair_start = pair.start.trim_end();
 3006                                    let pair_end = pair.end.trim_start();
 3007
 3008                                    enabled
 3009                                        && pair.newline
 3010                                        && buffer.contains_str_at(
 3011                                            end + trailing_whitespace_len,
 3012                                            pair_end,
 3013                                        )
 3014                                        && buffer.contains_str_at(
 3015                                            (start - leading_whitespace_len)
 3016                                                .saturating_sub(pair_start.len()),
 3017                                            pair_start,
 3018                                        )
 3019                                });
 3020
 3021                            // Comment extension on newline is allowed only for cursor selections
 3022                            let comment_delimiter = maybe!({
 3023                                if !selection_is_empty {
 3024                                    return None;
 3025                                }
 3026
 3027                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3028                                    return None;
 3029                                }
 3030
 3031                                let delimiters = language.line_comment_prefixes();
 3032                                let max_len_of_delimiter =
 3033                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3034                                let (snapshot, range) =
 3035                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3036
 3037                                let mut index_of_first_non_whitespace = 0;
 3038                                let comment_candidate = snapshot
 3039                                    .chars_for_range(range)
 3040                                    .skip_while(|c| {
 3041                                        let should_skip = c.is_whitespace();
 3042                                        if should_skip {
 3043                                            index_of_first_non_whitespace += 1;
 3044                                        }
 3045                                        should_skip
 3046                                    })
 3047                                    .take(max_len_of_delimiter)
 3048                                    .collect::<String>();
 3049                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3050                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3051                                })?;
 3052                                let cursor_is_placed_after_comment_marker =
 3053                                    index_of_first_non_whitespace + comment_prefix.len()
 3054                                        <= start_point.column as usize;
 3055                                if cursor_is_placed_after_comment_marker {
 3056                                    Some(comment_prefix.clone())
 3057                                } else {
 3058                                    None
 3059                                }
 3060                            });
 3061                            (comment_delimiter, insert_extra_newline)
 3062                        } else {
 3063                            (None, false)
 3064                        };
 3065
 3066                        let capacity_for_delimiter = comment_delimiter
 3067                            .as_deref()
 3068                            .map(str::len)
 3069                            .unwrap_or_default();
 3070                        let mut new_text =
 3071                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3072                        new_text.push('\n');
 3073                        new_text.extend(indent.chars());
 3074                        if let Some(delimiter) = &comment_delimiter {
 3075                            new_text.push_str(delimiter);
 3076                        }
 3077                        if insert_extra_newline {
 3078                            new_text = new_text.repeat(2);
 3079                        }
 3080
 3081                        let anchor = buffer.anchor_after(end);
 3082                        let new_selection = selection.map(|_| anchor);
 3083                        (
 3084                            (start..end, new_text),
 3085                            (insert_extra_newline, new_selection),
 3086                        )
 3087                    })
 3088                    .unzip()
 3089            };
 3090
 3091            this.edit_with_autoindent(edits, cx);
 3092            let buffer = this.buffer.read(cx).snapshot(cx);
 3093            let new_selections = selection_fixup_info
 3094                .into_iter()
 3095                .map(|(extra_newline_inserted, new_selection)| {
 3096                    let mut cursor = new_selection.end.to_point(&buffer);
 3097                    if extra_newline_inserted {
 3098                        cursor.row -= 1;
 3099                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3100                    }
 3101                    new_selection.map(|_| cursor)
 3102                })
 3103                .collect();
 3104
 3105            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3106            this.refresh_inline_completion(true, false, cx);
 3107        });
 3108    }
 3109
 3110    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3111        let buffer = self.buffer.read(cx);
 3112        let snapshot = buffer.snapshot(cx);
 3113
 3114        let mut edits = Vec::new();
 3115        let mut rows = Vec::new();
 3116
 3117        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3118            let cursor = selection.head();
 3119            let row = cursor.row;
 3120
 3121            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3122
 3123            let newline = "\n".to_string();
 3124            edits.push((start_of_line..start_of_line, newline));
 3125
 3126            rows.push(row + rows_inserted as u32);
 3127        }
 3128
 3129        self.transact(cx, |editor, cx| {
 3130            editor.edit(edits, cx);
 3131
 3132            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3133                let mut index = 0;
 3134                s.move_cursors_with(|map, _, _| {
 3135                    let row = rows[index];
 3136                    index += 1;
 3137
 3138                    let point = Point::new(row, 0);
 3139                    let boundary = map.next_line_boundary(point).1;
 3140                    let clipped = map.clip_point(boundary, Bias::Left);
 3141
 3142                    (clipped, SelectionGoal::None)
 3143                });
 3144            });
 3145
 3146            let mut indent_edits = Vec::new();
 3147            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3148            for row in rows {
 3149                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3150                for (row, indent) in indents {
 3151                    if indent.len == 0 {
 3152                        continue;
 3153                    }
 3154
 3155                    let text = match indent.kind {
 3156                        IndentKind::Space => " ".repeat(indent.len as usize),
 3157                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3158                    };
 3159                    let point = Point::new(row.0, 0);
 3160                    indent_edits.push((point..point, text));
 3161                }
 3162            }
 3163            editor.edit(indent_edits, cx);
 3164        });
 3165    }
 3166
 3167    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3168        let buffer = self.buffer.read(cx);
 3169        let snapshot = buffer.snapshot(cx);
 3170
 3171        let mut edits = Vec::new();
 3172        let mut rows = Vec::new();
 3173        let mut rows_inserted = 0;
 3174
 3175        for selection in self.selections.all_adjusted(cx) {
 3176            let cursor = selection.head();
 3177            let row = cursor.row;
 3178
 3179            let point = Point::new(row + 1, 0);
 3180            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3181
 3182            let newline = "\n".to_string();
 3183            edits.push((start_of_line..start_of_line, newline));
 3184
 3185            rows_inserted += 1;
 3186            rows.push(row + rows_inserted);
 3187        }
 3188
 3189        self.transact(cx, |editor, cx| {
 3190            editor.edit(edits, cx);
 3191
 3192            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3193                let mut index = 0;
 3194                s.move_cursors_with(|map, _, _| {
 3195                    let row = rows[index];
 3196                    index += 1;
 3197
 3198                    let point = Point::new(row, 0);
 3199                    let boundary = map.next_line_boundary(point).1;
 3200                    let clipped = map.clip_point(boundary, Bias::Left);
 3201
 3202                    (clipped, SelectionGoal::None)
 3203                });
 3204            });
 3205
 3206            let mut indent_edits = Vec::new();
 3207            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3208            for row in rows {
 3209                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3210                for (row, indent) in indents {
 3211                    if indent.len == 0 {
 3212                        continue;
 3213                    }
 3214
 3215                    let text = match indent.kind {
 3216                        IndentKind::Space => " ".repeat(indent.len as usize),
 3217                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3218                    };
 3219                    let point = Point::new(row.0, 0);
 3220                    indent_edits.push((point..point, text));
 3221                }
 3222            }
 3223            editor.edit(indent_edits, cx);
 3224        });
 3225    }
 3226
 3227    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3228        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3229            original_indent_columns: Vec::new(),
 3230        });
 3231        self.insert_with_autoindent_mode(text, autoindent, cx);
 3232    }
 3233
 3234    fn insert_with_autoindent_mode(
 3235        &mut self,
 3236        text: &str,
 3237        autoindent_mode: Option<AutoindentMode>,
 3238        cx: &mut ViewContext<Self>,
 3239    ) {
 3240        if self.read_only(cx) {
 3241            return;
 3242        }
 3243
 3244        let text: Arc<str> = text.into();
 3245        self.transact(cx, |this, cx| {
 3246            let old_selections = this.selections.all_adjusted(cx);
 3247            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3248                let anchors = {
 3249                    let snapshot = buffer.read(cx);
 3250                    old_selections
 3251                        .iter()
 3252                        .map(|s| {
 3253                            let anchor = snapshot.anchor_after(s.head());
 3254                            s.map(|_| anchor)
 3255                        })
 3256                        .collect::<Vec<_>>()
 3257                };
 3258                buffer.edit(
 3259                    old_selections
 3260                        .iter()
 3261                        .map(|s| (s.start..s.end, text.clone())),
 3262                    autoindent_mode,
 3263                    cx,
 3264                );
 3265                anchors
 3266            });
 3267
 3268            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3269                s.select_anchors(selection_anchors);
 3270            })
 3271        });
 3272    }
 3273
 3274    fn trigger_completion_on_input(
 3275        &mut self,
 3276        text: &str,
 3277        trigger_in_words: bool,
 3278        cx: &mut ViewContext<Self>,
 3279    ) {
 3280        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3281            self.show_completions(
 3282                &ShowCompletions {
 3283                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3284                },
 3285                cx,
 3286            );
 3287        } else {
 3288            self.hide_context_menu(cx);
 3289        }
 3290    }
 3291
 3292    fn is_completion_trigger(
 3293        &self,
 3294        text: &str,
 3295        trigger_in_words: bool,
 3296        cx: &mut ViewContext<Self>,
 3297    ) -> bool {
 3298        let position = self.selections.newest_anchor().head();
 3299        let multibuffer = self.buffer.read(cx);
 3300        let Some(buffer) = position
 3301            .buffer_id
 3302            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3303        else {
 3304            return false;
 3305        };
 3306
 3307        if let Some(completion_provider) = &self.completion_provider {
 3308            completion_provider.is_completion_trigger(
 3309                &buffer,
 3310                position.text_anchor,
 3311                text,
 3312                trigger_in_words,
 3313                cx,
 3314            )
 3315        } else {
 3316            false
 3317        }
 3318    }
 3319
 3320    /// If any empty selections is touching the start of its innermost containing autoclose
 3321    /// region, expand it to select the brackets.
 3322    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3323        let selections = self.selections.all::<usize>(cx);
 3324        let buffer = self.buffer.read(cx).read(cx);
 3325        let new_selections = self
 3326            .selections_with_autoclose_regions(selections, &buffer)
 3327            .map(|(mut selection, region)| {
 3328                if !selection.is_empty() {
 3329                    return selection;
 3330                }
 3331
 3332                if let Some(region) = region {
 3333                    let mut range = region.range.to_offset(&buffer);
 3334                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3335                        range.start -= region.pair.start.len();
 3336                        if buffer.contains_str_at(range.start, &region.pair.start)
 3337                            && buffer.contains_str_at(range.end, &region.pair.end)
 3338                        {
 3339                            range.end += region.pair.end.len();
 3340                            selection.start = range.start;
 3341                            selection.end = range.end;
 3342
 3343                            return selection;
 3344                        }
 3345                    }
 3346                }
 3347
 3348                let always_treat_brackets_as_autoclosed = buffer
 3349                    .settings_at(selection.start, cx)
 3350                    .always_treat_brackets_as_autoclosed;
 3351
 3352                if !always_treat_brackets_as_autoclosed {
 3353                    return selection;
 3354                }
 3355
 3356                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3357                    for (pair, enabled) in scope.brackets() {
 3358                        if !enabled || !pair.close {
 3359                            continue;
 3360                        }
 3361
 3362                        if buffer.contains_str_at(selection.start, &pair.end) {
 3363                            let pair_start_len = pair.start.len();
 3364                            if buffer.contains_str_at(
 3365                                selection.start.saturating_sub(pair_start_len),
 3366                                &pair.start,
 3367                            ) {
 3368                                selection.start -= pair_start_len;
 3369                                selection.end += pair.end.len();
 3370
 3371                                return selection;
 3372                            }
 3373                        }
 3374                    }
 3375                }
 3376
 3377                selection
 3378            })
 3379            .collect();
 3380
 3381        drop(buffer);
 3382        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3383    }
 3384
 3385    /// Iterate the given selections, and for each one, find the smallest surrounding
 3386    /// autoclose region. This uses the ordering of the selections and the autoclose
 3387    /// regions to avoid repeated comparisons.
 3388    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3389        &'a self,
 3390        selections: impl IntoIterator<Item = Selection<D>>,
 3391        buffer: &'a MultiBufferSnapshot,
 3392    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3393        let mut i = 0;
 3394        let mut regions = self.autoclose_regions.as_slice();
 3395        selections.into_iter().map(move |selection| {
 3396            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3397
 3398            let mut enclosing = None;
 3399            while let Some(pair_state) = regions.get(i) {
 3400                if pair_state.range.end.to_offset(buffer) < range.start {
 3401                    regions = &regions[i + 1..];
 3402                    i = 0;
 3403                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3404                    break;
 3405                } else {
 3406                    if pair_state.selection_id == selection.id {
 3407                        enclosing = Some(pair_state);
 3408                    }
 3409                    i += 1;
 3410                }
 3411            }
 3412
 3413            (selection, enclosing)
 3414        })
 3415    }
 3416
 3417    /// Remove any autoclose regions that no longer contain their selection.
 3418    fn invalidate_autoclose_regions(
 3419        &mut self,
 3420        mut selections: &[Selection<Anchor>],
 3421        buffer: &MultiBufferSnapshot,
 3422    ) {
 3423        self.autoclose_regions.retain(|state| {
 3424            let mut i = 0;
 3425            while let Some(selection) = selections.get(i) {
 3426                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3427                    selections = &selections[1..];
 3428                    continue;
 3429                }
 3430                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3431                    break;
 3432                }
 3433                if selection.id == state.selection_id {
 3434                    return true;
 3435                } else {
 3436                    i += 1;
 3437                }
 3438            }
 3439            false
 3440        });
 3441    }
 3442
 3443    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3444        let offset = position.to_offset(buffer);
 3445        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3446        if offset > word_range.start && kind == Some(CharKind::Word) {
 3447            Some(
 3448                buffer
 3449                    .text_for_range(word_range.start..offset)
 3450                    .collect::<String>(),
 3451            )
 3452        } else {
 3453            None
 3454        }
 3455    }
 3456
 3457    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3458        self.refresh_inlay_hints(
 3459            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3460            cx,
 3461        );
 3462    }
 3463
 3464    pub fn inlay_hints_enabled(&self) -> bool {
 3465        self.inlay_hint_cache.enabled
 3466    }
 3467
 3468    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3469        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3470            return;
 3471        }
 3472
 3473        let reason_description = reason.description();
 3474        let ignore_debounce = matches!(
 3475            reason,
 3476            InlayHintRefreshReason::SettingsChange(_)
 3477                | InlayHintRefreshReason::Toggle(_)
 3478                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3479        );
 3480        let (invalidate_cache, required_languages) = match reason {
 3481            InlayHintRefreshReason::Toggle(enabled) => {
 3482                self.inlay_hint_cache.enabled = enabled;
 3483                if enabled {
 3484                    (InvalidationStrategy::RefreshRequested, None)
 3485                } else {
 3486                    self.inlay_hint_cache.clear();
 3487                    self.splice_inlays(
 3488                        self.visible_inlay_hints(cx)
 3489                            .iter()
 3490                            .map(|inlay| inlay.id)
 3491                            .collect(),
 3492                        Vec::new(),
 3493                        cx,
 3494                    );
 3495                    return;
 3496                }
 3497            }
 3498            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3499                match self.inlay_hint_cache.update_settings(
 3500                    &self.buffer,
 3501                    new_settings,
 3502                    self.visible_inlay_hints(cx),
 3503                    cx,
 3504                ) {
 3505                    ControlFlow::Break(Some(InlaySplice {
 3506                        to_remove,
 3507                        to_insert,
 3508                    })) => {
 3509                        self.splice_inlays(to_remove, to_insert, cx);
 3510                        return;
 3511                    }
 3512                    ControlFlow::Break(None) => return,
 3513                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3514                }
 3515            }
 3516            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3517                if let Some(InlaySplice {
 3518                    to_remove,
 3519                    to_insert,
 3520                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3521                {
 3522                    self.splice_inlays(to_remove, to_insert, cx);
 3523                }
 3524                return;
 3525            }
 3526            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3527            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3528                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3529            }
 3530            InlayHintRefreshReason::RefreshRequested => {
 3531                (InvalidationStrategy::RefreshRequested, None)
 3532            }
 3533        };
 3534
 3535        if let Some(InlaySplice {
 3536            to_remove,
 3537            to_insert,
 3538        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3539            reason_description,
 3540            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3541            invalidate_cache,
 3542            ignore_debounce,
 3543            cx,
 3544        ) {
 3545            self.splice_inlays(to_remove, to_insert, cx);
 3546        }
 3547    }
 3548
 3549    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3550        self.display_map
 3551            .read(cx)
 3552            .current_inlays()
 3553            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3554            .cloned()
 3555            .collect()
 3556    }
 3557
 3558    pub fn excerpts_for_inlay_hints_query(
 3559        &self,
 3560        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3561        cx: &mut ViewContext<Editor>,
 3562    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3563        let Some(project) = self.project.as_ref() else {
 3564            return HashMap::default();
 3565        };
 3566        let project = project.read(cx);
 3567        let multi_buffer = self.buffer().read(cx);
 3568        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3569        let multi_buffer_visible_start = self
 3570            .scroll_manager
 3571            .anchor()
 3572            .anchor
 3573            .to_point(&multi_buffer_snapshot);
 3574        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3575            multi_buffer_visible_start
 3576                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3577            Bias::Left,
 3578        );
 3579        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3580        multi_buffer_snapshot
 3581            .range_to_buffer_ranges(multi_buffer_visible_range)
 3582            .into_iter()
 3583            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3584            .filter_map(|(excerpt, excerpt_visible_range)| {
 3585                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3586                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3587                let worktree_entry = buffer_worktree
 3588                    .read(cx)
 3589                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3590                if worktree_entry.is_ignored {
 3591                    return None;
 3592                }
 3593
 3594                let language = excerpt.buffer().language()?;
 3595                if let Some(restrict_to_languages) = restrict_to_languages {
 3596                    if !restrict_to_languages.contains(language) {
 3597                        return None;
 3598                    }
 3599                }
 3600                Some((
 3601                    excerpt.id(),
 3602                    (
 3603                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3604                        excerpt.buffer().version().clone(),
 3605                        excerpt_visible_range,
 3606                    ),
 3607                ))
 3608            })
 3609            .collect()
 3610    }
 3611
 3612    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3613        TextLayoutDetails {
 3614            text_system: cx.text_system().clone(),
 3615            editor_style: self.style.clone().unwrap(),
 3616            rem_size: cx.rem_size(),
 3617            scroll_anchor: self.scroll_manager.anchor(),
 3618            visible_rows: self.visible_line_count(),
 3619            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3620        }
 3621    }
 3622
 3623    pub fn splice_inlays(
 3624        &self,
 3625        to_remove: Vec<InlayId>,
 3626        to_insert: Vec<Inlay>,
 3627        cx: &mut ViewContext<Self>,
 3628    ) {
 3629        self.display_map.update(cx, |display_map, cx| {
 3630            display_map.splice_inlays(to_remove, to_insert, cx)
 3631        });
 3632        cx.notify();
 3633    }
 3634
 3635    fn trigger_on_type_formatting(
 3636        &self,
 3637        input: String,
 3638        cx: &mut ViewContext<Self>,
 3639    ) -> Option<Task<Result<()>>> {
 3640        if input.len() != 1 {
 3641            return None;
 3642        }
 3643
 3644        let project = self.project.as_ref()?;
 3645        let position = self.selections.newest_anchor().head();
 3646        let (buffer, buffer_position) = self
 3647            .buffer
 3648            .read(cx)
 3649            .text_anchor_for_position(position, cx)?;
 3650
 3651        let settings = language_settings::language_settings(
 3652            buffer
 3653                .read(cx)
 3654                .language_at(buffer_position)
 3655                .map(|l| l.name()),
 3656            buffer.read(cx).file(),
 3657            cx,
 3658        );
 3659        if !settings.use_on_type_format {
 3660            return None;
 3661        }
 3662
 3663        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3664        // hence we do LSP request & edit on host side only — add formats to host's history.
 3665        let push_to_lsp_host_history = true;
 3666        // If this is not the host, append its history with new edits.
 3667        let push_to_client_history = project.read(cx).is_via_collab();
 3668
 3669        let on_type_formatting = project.update(cx, |project, cx| {
 3670            project.on_type_format(
 3671                buffer.clone(),
 3672                buffer_position,
 3673                input,
 3674                push_to_lsp_host_history,
 3675                cx,
 3676            )
 3677        });
 3678        Some(cx.spawn(|editor, mut cx| async move {
 3679            if let Some(transaction) = on_type_formatting.await? {
 3680                if push_to_client_history {
 3681                    buffer
 3682                        .update(&mut cx, |buffer, _| {
 3683                            buffer.push_transaction(transaction, Instant::now());
 3684                        })
 3685                        .ok();
 3686                }
 3687                editor.update(&mut cx, |editor, cx| {
 3688                    editor.refresh_document_highlights(cx);
 3689                })?;
 3690            }
 3691            Ok(())
 3692        }))
 3693    }
 3694
 3695    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3696        if self.pending_rename.is_some() {
 3697            return;
 3698        }
 3699
 3700        let Some(provider) = self.completion_provider.as_ref() else {
 3701            return;
 3702        };
 3703
 3704        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3705            return;
 3706        }
 3707
 3708        let position = self.selections.newest_anchor().head();
 3709        let (buffer, buffer_position) =
 3710            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3711                output
 3712            } else {
 3713                return;
 3714            };
 3715        let show_completion_documentation = buffer
 3716            .read(cx)
 3717            .snapshot()
 3718            .settings_at(buffer_position, cx)
 3719            .show_completion_documentation;
 3720
 3721        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3722
 3723        let trigger_kind = match &options.trigger {
 3724            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3725                CompletionTriggerKind::TRIGGER_CHARACTER
 3726            }
 3727            _ => CompletionTriggerKind::INVOKED,
 3728        };
 3729        let completion_context = CompletionContext {
 3730            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3731                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3732                    Some(String::from(trigger))
 3733                } else {
 3734                    None
 3735                }
 3736            }),
 3737            trigger_kind,
 3738        };
 3739        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3740        let sort_completions = provider.sort_completions();
 3741
 3742        let id = post_inc(&mut self.next_completion_id);
 3743        let task = cx.spawn(|editor, mut cx| {
 3744            async move {
 3745                editor.update(&mut cx, |this, _| {
 3746                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3747                })?;
 3748                let completions = completions.await.log_err();
 3749                let menu = if let Some(completions) = completions {
 3750                    let mut menu = CompletionsMenu::new(
 3751                        id,
 3752                        sort_completions,
 3753                        show_completion_documentation,
 3754                        position,
 3755                        buffer.clone(),
 3756                        completions.into(),
 3757                    );
 3758
 3759                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3760                        .await;
 3761
 3762                    menu.visible().then_some(menu)
 3763                } else {
 3764                    None
 3765                };
 3766
 3767                editor.update(&mut cx, |editor, cx| {
 3768                    match editor.context_menu.borrow().as_ref() {
 3769                        None => {}
 3770                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3771                            if prev_menu.id > id {
 3772                                return;
 3773                            }
 3774                        }
 3775                        _ => return,
 3776                    }
 3777
 3778                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3779                        let mut menu = menu.unwrap();
 3780                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3781
 3782                        if editor.show_inline_completions_in_menu(cx) {
 3783                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3784                                menu.show_inline_completion_hint(hint);
 3785                            }
 3786                        } else {
 3787                            editor.discard_inline_completion(false, cx);
 3788                        }
 3789
 3790                        *editor.context_menu.borrow_mut() =
 3791                            Some(CodeContextMenu::Completions(menu));
 3792
 3793                        cx.notify();
 3794                    } else if editor.completion_tasks.len() <= 1 {
 3795                        // If there are no more completion tasks and the last menu was
 3796                        // empty, we should hide it.
 3797                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3798                        // If it was already hidden and we don't show inline
 3799                        // completions in the menu, we should also show the
 3800                        // inline-completion when available.
 3801                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3802                            editor.update_visible_inline_completion(cx);
 3803                        }
 3804                    }
 3805                })?;
 3806
 3807                Ok::<_, anyhow::Error>(())
 3808            }
 3809            .log_err()
 3810        });
 3811
 3812        self.completion_tasks.push((id, task));
 3813    }
 3814
 3815    pub fn confirm_completion(
 3816        &mut self,
 3817        action: &ConfirmCompletion,
 3818        cx: &mut ViewContext<Self>,
 3819    ) -> Option<Task<Result<()>>> {
 3820        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3821    }
 3822
 3823    pub fn compose_completion(
 3824        &mut self,
 3825        action: &ComposeCompletion,
 3826        cx: &mut ViewContext<Self>,
 3827    ) -> Option<Task<Result<()>>> {
 3828        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3829    }
 3830
 3831    fn do_completion(
 3832        &mut self,
 3833        item_ix: Option<usize>,
 3834        intent: CompletionIntent,
 3835        cx: &mut ViewContext<Editor>,
 3836    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3837        use language::ToOffset as _;
 3838
 3839        {
 3840            let context_menu = self.context_menu.borrow();
 3841            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3842                let entries = menu.entries.borrow();
 3843                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3844                match entry {
 3845                    Some(CompletionEntry::InlineCompletionHint(
 3846                        InlineCompletionMenuHint::Loading,
 3847                    )) => return Some(Task::ready(Ok(()))),
 3848                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3849                        drop(entries);
 3850                        drop(context_menu);
 3851                        self.context_menu_next(&Default::default(), cx);
 3852                        return Some(Task::ready(Ok(())));
 3853                    }
 3854                    _ => {}
 3855                }
 3856            }
 3857        }
 3858
 3859        let completions_menu =
 3860            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3861                menu
 3862            } else {
 3863                return None;
 3864            };
 3865
 3866        let entries = completions_menu.entries.borrow();
 3867        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3868        let mat = match mat {
 3869            CompletionEntry::InlineCompletionHint(_) => {
 3870                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3871                cx.stop_propagation();
 3872                return Some(Task::ready(Ok(())));
 3873            }
 3874            CompletionEntry::Match(mat) => {
 3875                if self.show_inline_completions_in_menu(cx) {
 3876                    self.discard_inline_completion(true, cx);
 3877                }
 3878                mat
 3879            }
 3880        };
 3881        let candidate_id = mat.candidate_id;
 3882        drop(entries);
 3883
 3884        let buffer_handle = completions_menu.buffer;
 3885        let completion = completions_menu
 3886            .completions
 3887            .borrow()
 3888            .get(candidate_id)?
 3889            .clone();
 3890        cx.stop_propagation();
 3891
 3892        let snippet;
 3893        let text;
 3894
 3895        if completion.is_snippet() {
 3896            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3897            text = snippet.as_ref().unwrap().text.clone();
 3898        } else {
 3899            snippet = None;
 3900            text = completion.new_text.clone();
 3901        };
 3902        let selections = self.selections.all::<usize>(cx);
 3903        let buffer = buffer_handle.read(cx);
 3904        let old_range = completion.old_range.to_offset(buffer);
 3905        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3906
 3907        let newest_selection = self.selections.newest_anchor();
 3908        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3909            return None;
 3910        }
 3911
 3912        let lookbehind = newest_selection
 3913            .start
 3914            .text_anchor
 3915            .to_offset(buffer)
 3916            .saturating_sub(old_range.start);
 3917        let lookahead = old_range
 3918            .end
 3919            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3920        let mut common_prefix_len = old_text
 3921            .bytes()
 3922            .zip(text.bytes())
 3923            .take_while(|(a, b)| a == b)
 3924            .count();
 3925
 3926        let snapshot = self.buffer.read(cx).snapshot(cx);
 3927        let mut range_to_replace: Option<Range<isize>> = None;
 3928        let mut ranges = Vec::new();
 3929        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3930        for selection in &selections {
 3931            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3932                let start = selection.start.saturating_sub(lookbehind);
 3933                let end = selection.end + lookahead;
 3934                if selection.id == newest_selection.id {
 3935                    range_to_replace = Some(
 3936                        ((start + common_prefix_len) as isize - selection.start as isize)
 3937                            ..(end as isize - selection.start as isize),
 3938                    );
 3939                }
 3940                ranges.push(start + common_prefix_len..end);
 3941            } else {
 3942                common_prefix_len = 0;
 3943                ranges.clear();
 3944                ranges.extend(selections.iter().map(|s| {
 3945                    if s.id == newest_selection.id {
 3946                        range_to_replace = Some(
 3947                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3948                                - selection.start as isize
 3949                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3950                                    - selection.start as isize,
 3951                        );
 3952                        old_range.clone()
 3953                    } else {
 3954                        s.start..s.end
 3955                    }
 3956                }));
 3957                break;
 3958            }
 3959            if !self.linked_edit_ranges.is_empty() {
 3960                let start_anchor = snapshot.anchor_before(selection.head());
 3961                let end_anchor = snapshot.anchor_after(selection.tail());
 3962                if let Some(ranges) = self
 3963                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3964                {
 3965                    for (buffer, edits) in ranges {
 3966                        linked_edits.entry(buffer.clone()).or_default().extend(
 3967                            edits
 3968                                .into_iter()
 3969                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3970                        );
 3971                    }
 3972                }
 3973            }
 3974        }
 3975        let text = &text[common_prefix_len..];
 3976
 3977        cx.emit(EditorEvent::InputHandled {
 3978            utf16_range_to_replace: range_to_replace,
 3979            text: text.into(),
 3980        });
 3981
 3982        self.transact(cx, |this, cx| {
 3983            if let Some(mut snippet) = snippet {
 3984                snippet.text = text.to_string();
 3985                for tabstop in snippet
 3986                    .tabstops
 3987                    .iter_mut()
 3988                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3989                {
 3990                    tabstop.start -= common_prefix_len as isize;
 3991                    tabstop.end -= common_prefix_len as isize;
 3992                }
 3993
 3994                this.insert_snippet(&ranges, snippet, cx).log_err();
 3995            } else {
 3996                this.buffer.update(cx, |buffer, cx| {
 3997                    buffer.edit(
 3998                        ranges.iter().map(|range| (range.clone(), text)),
 3999                        this.autoindent_mode.clone(),
 4000                        cx,
 4001                    );
 4002                });
 4003            }
 4004            for (buffer, edits) in linked_edits {
 4005                buffer.update(cx, |buffer, cx| {
 4006                    let snapshot = buffer.snapshot();
 4007                    let edits = edits
 4008                        .into_iter()
 4009                        .map(|(range, text)| {
 4010                            use text::ToPoint as TP;
 4011                            let end_point = TP::to_point(&range.end, &snapshot);
 4012                            let start_point = TP::to_point(&range.start, &snapshot);
 4013                            (start_point..end_point, text)
 4014                        })
 4015                        .sorted_by_key(|(range, _)| range.start)
 4016                        .collect::<Vec<_>>();
 4017                    buffer.edit(edits, None, cx);
 4018                })
 4019            }
 4020
 4021            this.refresh_inline_completion(true, false, cx);
 4022        });
 4023
 4024        let show_new_completions_on_confirm = completion
 4025            .confirm
 4026            .as_ref()
 4027            .map_or(false, |confirm| confirm(intent, cx));
 4028        if show_new_completions_on_confirm {
 4029            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4030        }
 4031
 4032        let provider = self.completion_provider.as_ref()?;
 4033        drop(completion);
 4034        let apply_edits = provider.apply_additional_edits_for_completion(
 4035            buffer_handle,
 4036            completions_menu.completions.clone(),
 4037            candidate_id,
 4038            true,
 4039            cx,
 4040        );
 4041
 4042        let editor_settings = EditorSettings::get_global(cx);
 4043        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4044            // After the code completion is finished, users often want to know what signatures are needed.
 4045            // so we should automatically call signature_help
 4046            self.show_signature_help(&ShowSignatureHelp, cx);
 4047        }
 4048
 4049        Some(cx.foreground_executor().spawn(async move {
 4050            apply_edits.await?;
 4051            Ok(())
 4052        }))
 4053    }
 4054
 4055    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4056        let mut context_menu = self.context_menu.borrow_mut();
 4057        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4058            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4059                // Toggle if we're selecting the same one
 4060                *context_menu = None;
 4061                cx.notify();
 4062                return;
 4063            } else {
 4064                // Otherwise, clear it and start a new one
 4065                *context_menu = None;
 4066                cx.notify();
 4067            }
 4068        }
 4069        drop(context_menu);
 4070        let snapshot = self.snapshot(cx);
 4071        let deployed_from_indicator = action.deployed_from_indicator;
 4072        let mut task = self.code_actions_task.take();
 4073        let action = action.clone();
 4074        cx.spawn(|editor, mut cx| async move {
 4075            while let Some(prev_task) = task {
 4076                prev_task.await.log_err();
 4077                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4078            }
 4079
 4080            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4081                if editor.focus_handle.is_focused(cx) {
 4082                    let multibuffer_point = action
 4083                        .deployed_from_indicator
 4084                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4085                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4086                    let (buffer, buffer_row) = snapshot
 4087                        .buffer_snapshot
 4088                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4089                        .and_then(|(buffer_snapshot, range)| {
 4090                            editor
 4091                                .buffer
 4092                                .read(cx)
 4093                                .buffer(buffer_snapshot.remote_id())
 4094                                .map(|buffer| (buffer, range.start.row))
 4095                        })?;
 4096                    let (_, code_actions) = editor
 4097                        .available_code_actions
 4098                        .clone()
 4099                        .and_then(|(location, code_actions)| {
 4100                            let snapshot = location.buffer.read(cx).snapshot();
 4101                            let point_range = location.range.to_point(&snapshot);
 4102                            let point_range = point_range.start.row..=point_range.end.row;
 4103                            if point_range.contains(&buffer_row) {
 4104                                Some((location, code_actions))
 4105                            } else {
 4106                                None
 4107                            }
 4108                        })
 4109                        .unzip();
 4110                    let buffer_id = buffer.read(cx).remote_id();
 4111                    let tasks = editor
 4112                        .tasks
 4113                        .get(&(buffer_id, buffer_row))
 4114                        .map(|t| Arc::new(t.to_owned()));
 4115                    if tasks.is_none() && code_actions.is_none() {
 4116                        return None;
 4117                    }
 4118
 4119                    editor.completion_tasks.clear();
 4120                    editor.discard_inline_completion(false, cx);
 4121                    let task_context =
 4122                        tasks
 4123                            .as_ref()
 4124                            .zip(editor.project.clone())
 4125                            .map(|(tasks, project)| {
 4126                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4127                            });
 4128
 4129                    Some(cx.spawn(|editor, mut cx| async move {
 4130                        let task_context = match task_context {
 4131                            Some(task_context) => task_context.await,
 4132                            None => None,
 4133                        };
 4134                        let resolved_tasks =
 4135                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4136                                Rc::new(ResolvedTasks {
 4137                                    templates: tasks.resolve(&task_context).collect(),
 4138                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4139                                        multibuffer_point.row,
 4140                                        tasks.column,
 4141                                    )),
 4142                                })
 4143                            });
 4144                        let spawn_straight_away = resolved_tasks
 4145                            .as_ref()
 4146                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4147                            && code_actions
 4148                                .as_ref()
 4149                                .map_or(true, |actions| actions.is_empty());
 4150                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4151                            *editor.context_menu.borrow_mut() =
 4152                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4153                                    buffer,
 4154                                    actions: CodeActionContents {
 4155                                        tasks: resolved_tasks,
 4156                                        actions: code_actions,
 4157                                    },
 4158                                    selected_item: Default::default(),
 4159                                    scroll_handle: UniformListScrollHandle::default(),
 4160                                    deployed_from_indicator,
 4161                                }));
 4162                            if spawn_straight_away {
 4163                                if let Some(task) = editor.confirm_code_action(
 4164                                    &ConfirmCodeAction { item_ix: Some(0) },
 4165                                    cx,
 4166                                ) {
 4167                                    cx.notify();
 4168                                    return task;
 4169                                }
 4170                            }
 4171                            cx.notify();
 4172                            Task::ready(Ok(()))
 4173                        }) {
 4174                            task.await
 4175                        } else {
 4176                            Ok(())
 4177                        }
 4178                    }))
 4179                } else {
 4180                    Some(Task::ready(Ok(())))
 4181                }
 4182            })?;
 4183            if let Some(task) = spawned_test_task {
 4184                task.await?;
 4185            }
 4186
 4187            Ok::<_, anyhow::Error>(())
 4188        })
 4189        .detach_and_log_err(cx);
 4190    }
 4191
 4192    pub fn confirm_code_action(
 4193        &mut self,
 4194        action: &ConfirmCodeAction,
 4195        cx: &mut ViewContext<Self>,
 4196    ) -> Option<Task<Result<()>>> {
 4197        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4198            menu
 4199        } else {
 4200            return None;
 4201        };
 4202        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4203        let action = actions_menu.actions.get(action_ix)?;
 4204        let title = action.label();
 4205        let buffer = actions_menu.buffer;
 4206        let workspace = self.workspace()?;
 4207
 4208        match action {
 4209            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4210                workspace.update(cx, |workspace, cx| {
 4211                    workspace::tasks::schedule_resolved_task(
 4212                        workspace,
 4213                        task_source_kind,
 4214                        resolved_task,
 4215                        false,
 4216                        cx,
 4217                    );
 4218
 4219                    Some(Task::ready(Ok(())))
 4220                })
 4221            }
 4222            CodeActionsItem::CodeAction {
 4223                excerpt_id,
 4224                action,
 4225                provider,
 4226            } => {
 4227                let apply_code_action =
 4228                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4229                let workspace = workspace.downgrade();
 4230                Some(cx.spawn(|editor, cx| async move {
 4231                    let project_transaction = apply_code_action.await?;
 4232                    Self::open_project_transaction(
 4233                        &editor,
 4234                        workspace,
 4235                        project_transaction,
 4236                        title,
 4237                        cx,
 4238                    )
 4239                    .await
 4240                }))
 4241            }
 4242        }
 4243    }
 4244
 4245    pub async fn open_project_transaction(
 4246        this: &WeakView<Editor>,
 4247        workspace: WeakView<Workspace>,
 4248        transaction: ProjectTransaction,
 4249        title: String,
 4250        mut cx: AsyncWindowContext,
 4251    ) -> Result<()> {
 4252        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4253        cx.update(|cx| {
 4254            entries.sort_unstable_by_key(|(buffer, _)| {
 4255                buffer.read(cx).file().map(|f| f.path().clone())
 4256            });
 4257        })?;
 4258
 4259        // If the project transaction's edits are all contained within this editor, then
 4260        // avoid opening a new editor to display them.
 4261
 4262        if let Some((buffer, transaction)) = entries.first() {
 4263            if entries.len() == 1 {
 4264                let excerpt = this.update(&mut cx, |editor, cx| {
 4265                    editor
 4266                        .buffer()
 4267                        .read(cx)
 4268                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4269                })?;
 4270                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4271                    if excerpted_buffer == *buffer {
 4272                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4273                            let excerpt_range = excerpt_range.to_offset(buffer);
 4274                            buffer
 4275                                .edited_ranges_for_transaction::<usize>(transaction)
 4276                                .all(|range| {
 4277                                    excerpt_range.start <= range.start
 4278                                        && excerpt_range.end >= range.end
 4279                                })
 4280                        })?;
 4281
 4282                        if all_edits_within_excerpt {
 4283                            return Ok(());
 4284                        }
 4285                    }
 4286                }
 4287            }
 4288        } else {
 4289            return Ok(());
 4290        }
 4291
 4292        let mut ranges_to_highlight = Vec::new();
 4293        let excerpt_buffer = cx.new_model(|cx| {
 4294            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4295            for (buffer_handle, transaction) in &entries {
 4296                let buffer = buffer_handle.read(cx);
 4297                ranges_to_highlight.extend(
 4298                    multibuffer.push_excerpts_with_context_lines(
 4299                        buffer_handle.clone(),
 4300                        buffer
 4301                            .edited_ranges_for_transaction::<usize>(transaction)
 4302                            .collect(),
 4303                        DEFAULT_MULTIBUFFER_CONTEXT,
 4304                        cx,
 4305                    ),
 4306                );
 4307            }
 4308            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4309            multibuffer
 4310        })?;
 4311
 4312        workspace.update(&mut cx, |workspace, cx| {
 4313            let project = workspace.project().clone();
 4314            let editor =
 4315                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4316            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4317            editor.update(cx, |editor, cx| {
 4318                editor.highlight_background::<Self>(
 4319                    &ranges_to_highlight,
 4320                    |theme| theme.editor_highlighted_line_background,
 4321                    cx,
 4322                );
 4323            });
 4324        })?;
 4325
 4326        Ok(())
 4327    }
 4328
 4329    pub fn clear_code_action_providers(&mut self) {
 4330        self.code_action_providers.clear();
 4331        self.available_code_actions.take();
 4332    }
 4333
 4334    pub fn add_code_action_provider(
 4335        &mut self,
 4336        provider: Rc<dyn CodeActionProvider>,
 4337        cx: &mut ViewContext<Self>,
 4338    ) {
 4339        if self
 4340            .code_action_providers
 4341            .iter()
 4342            .any(|existing_provider| existing_provider.id() == provider.id())
 4343        {
 4344            return;
 4345        }
 4346
 4347        self.code_action_providers.push(provider);
 4348        self.refresh_code_actions(cx);
 4349    }
 4350
 4351    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4352        self.code_action_providers
 4353            .retain(|provider| provider.id() != id);
 4354        self.refresh_code_actions(cx);
 4355    }
 4356
 4357    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4358        let buffer = self.buffer.read(cx);
 4359        let newest_selection = self.selections.newest_anchor().clone();
 4360        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4361        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4362        if start_buffer != end_buffer {
 4363            return None;
 4364        }
 4365
 4366        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4367            cx.background_executor()
 4368                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4369                .await;
 4370
 4371            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4372                let providers = this.code_action_providers.clone();
 4373                let tasks = this
 4374                    .code_action_providers
 4375                    .iter()
 4376                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4377                    .collect::<Vec<_>>();
 4378                (providers, tasks)
 4379            })?;
 4380
 4381            let mut actions = Vec::new();
 4382            for (provider, provider_actions) in
 4383                providers.into_iter().zip(future::join_all(tasks).await)
 4384            {
 4385                if let Some(provider_actions) = provider_actions.log_err() {
 4386                    actions.extend(provider_actions.into_iter().map(|action| {
 4387                        AvailableCodeAction {
 4388                            excerpt_id: newest_selection.start.excerpt_id,
 4389                            action,
 4390                            provider: provider.clone(),
 4391                        }
 4392                    }));
 4393                }
 4394            }
 4395
 4396            this.update(&mut cx, |this, cx| {
 4397                this.available_code_actions = if actions.is_empty() {
 4398                    None
 4399                } else {
 4400                    Some((
 4401                        Location {
 4402                            buffer: start_buffer,
 4403                            range: start..end,
 4404                        },
 4405                        actions.into(),
 4406                    ))
 4407                };
 4408                cx.notify();
 4409            })
 4410        }));
 4411        None
 4412    }
 4413
 4414    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4415        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4416            self.show_git_blame_inline = false;
 4417
 4418            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4419                cx.background_executor().timer(delay).await;
 4420
 4421                this.update(&mut cx, |this, cx| {
 4422                    this.show_git_blame_inline = true;
 4423                    cx.notify();
 4424                })
 4425                .log_err();
 4426            }));
 4427        }
 4428    }
 4429
 4430    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4431        if self.pending_rename.is_some() {
 4432            return None;
 4433        }
 4434
 4435        let provider = self.semantics_provider.clone()?;
 4436        let buffer = self.buffer.read(cx);
 4437        let newest_selection = self.selections.newest_anchor().clone();
 4438        let cursor_position = newest_selection.head();
 4439        let (cursor_buffer, cursor_buffer_position) =
 4440            buffer.text_anchor_for_position(cursor_position, cx)?;
 4441        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4442        if cursor_buffer != tail_buffer {
 4443            return None;
 4444        }
 4445        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4446        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4447            cx.background_executor()
 4448                .timer(Duration::from_millis(debounce))
 4449                .await;
 4450
 4451            let highlights = if let Some(highlights) = cx
 4452                .update(|cx| {
 4453                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4454                })
 4455                .ok()
 4456                .flatten()
 4457            {
 4458                highlights.await.log_err()
 4459            } else {
 4460                None
 4461            };
 4462
 4463            if let Some(highlights) = highlights {
 4464                this.update(&mut cx, |this, cx| {
 4465                    if this.pending_rename.is_some() {
 4466                        return;
 4467                    }
 4468
 4469                    let buffer_id = cursor_position.buffer_id;
 4470                    let buffer = this.buffer.read(cx);
 4471                    if !buffer
 4472                        .text_anchor_for_position(cursor_position, cx)
 4473                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4474                    {
 4475                        return;
 4476                    }
 4477
 4478                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4479                    let mut write_ranges = Vec::new();
 4480                    let mut read_ranges = Vec::new();
 4481                    for highlight in highlights {
 4482                        for (excerpt_id, excerpt_range) in
 4483                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4484                        {
 4485                            let start = highlight
 4486                                .range
 4487                                .start
 4488                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4489                            let end = highlight
 4490                                .range
 4491                                .end
 4492                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4493                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4494                                continue;
 4495                            }
 4496
 4497                            let range = Anchor {
 4498                                buffer_id,
 4499                                excerpt_id,
 4500                                text_anchor: start,
 4501                            }..Anchor {
 4502                                buffer_id,
 4503                                excerpt_id,
 4504                                text_anchor: end,
 4505                            };
 4506                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4507                                write_ranges.push(range);
 4508                            } else {
 4509                                read_ranges.push(range);
 4510                            }
 4511                        }
 4512                    }
 4513
 4514                    this.highlight_background::<DocumentHighlightRead>(
 4515                        &read_ranges,
 4516                        |theme| theme.editor_document_highlight_read_background,
 4517                        cx,
 4518                    );
 4519                    this.highlight_background::<DocumentHighlightWrite>(
 4520                        &write_ranges,
 4521                        |theme| theme.editor_document_highlight_write_background,
 4522                        cx,
 4523                    );
 4524                    cx.notify();
 4525                })
 4526                .log_err();
 4527            }
 4528        }));
 4529        None
 4530    }
 4531
 4532    pub fn refresh_inline_completion(
 4533        &mut self,
 4534        debounce: bool,
 4535        user_requested: bool,
 4536        cx: &mut ViewContext<Self>,
 4537    ) -> Option<()> {
 4538        let provider = self.inline_completion_provider()?;
 4539        let cursor = self.selections.newest_anchor().head();
 4540        let (buffer, cursor_buffer_position) =
 4541            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4542
 4543        if !user_requested
 4544            && (!self.enable_inline_completions
 4545                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4546                || !self.is_focused(cx)
 4547                || buffer.read(cx).is_empty())
 4548        {
 4549            self.discard_inline_completion(false, cx);
 4550            return None;
 4551        }
 4552
 4553        self.update_visible_inline_completion(cx);
 4554        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4555        Some(())
 4556    }
 4557
 4558    fn cycle_inline_completion(
 4559        &mut self,
 4560        direction: Direction,
 4561        cx: &mut ViewContext<Self>,
 4562    ) -> Option<()> {
 4563        let provider = self.inline_completion_provider()?;
 4564        let cursor = self.selections.newest_anchor().head();
 4565        let (buffer, cursor_buffer_position) =
 4566            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4567        if !self.enable_inline_completions
 4568            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4569        {
 4570            return None;
 4571        }
 4572
 4573        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4574        self.update_visible_inline_completion(cx);
 4575
 4576        Some(())
 4577    }
 4578
 4579    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4580        if !self.has_active_inline_completion() {
 4581            self.refresh_inline_completion(false, true, cx);
 4582            return;
 4583        }
 4584
 4585        self.update_visible_inline_completion(cx);
 4586    }
 4587
 4588    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4589        self.show_cursor_names(cx);
 4590    }
 4591
 4592    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4593        self.show_cursor_names = true;
 4594        cx.notify();
 4595        cx.spawn(|this, mut cx| async move {
 4596            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4597            this.update(&mut cx, |this, cx| {
 4598                this.show_cursor_names = false;
 4599                cx.notify()
 4600            })
 4601            .ok()
 4602        })
 4603        .detach();
 4604    }
 4605
 4606    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4607        if self.has_active_inline_completion() {
 4608            self.cycle_inline_completion(Direction::Next, cx);
 4609        } else {
 4610            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4611            if is_copilot_disabled {
 4612                cx.propagate();
 4613            }
 4614        }
 4615    }
 4616
 4617    pub fn previous_inline_completion(
 4618        &mut self,
 4619        _: &PreviousInlineCompletion,
 4620        cx: &mut ViewContext<Self>,
 4621    ) {
 4622        if self.has_active_inline_completion() {
 4623            self.cycle_inline_completion(Direction::Prev, cx);
 4624        } else {
 4625            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4626            if is_copilot_disabled {
 4627                cx.propagate();
 4628            }
 4629        }
 4630    }
 4631
 4632    pub fn accept_inline_completion(
 4633        &mut self,
 4634        _: &AcceptInlineCompletion,
 4635        cx: &mut ViewContext<Self>,
 4636    ) {
 4637        let buffer = self.buffer.read(cx);
 4638        let snapshot = buffer.snapshot(cx);
 4639        let selection = self.selections.newest_adjusted(cx);
 4640        let cursor = selection.head();
 4641        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4642        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4643        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4644        {
 4645            if cursor.column < suggested_indent.len
 4646                && cursor.column <= current_indent.len
 4647                && current_indent.len <= suggested_indent.len
 4648            {
 4649                self.tab(&Default::default(), cx);
 4650                return;
 4651            }
 4652        }
 4653
 4654        if self.show_inline_completions_in_menu(cx) {
 4655            self.hide_context_menu(cx);
 4656        }
 4657
 4658        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4659            return;
 4660        };
 4661
 4662        self.report_inline_completion_event(true, cx);
 4663
 4664        match &active_inline_completion.completion {
 4665            InlineCompletion::Move(position) => {
 4666                let position = *position;
 4667                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4668                    selections.select_anchor_ranges([position..position]);
 4669                });
 4670            }
 4671            InlineCompletion::Edit(edits) => {
 4672                if let Some(provider) = self.inline_completion_provider() {
 4673                    provider.accept(cx);
 4674                }
 4675
 4676                let snapshot = self.buffer.read(cx).snapshot(cx);
 4677                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4678
 4679                self.buffer.update(cx, |buffer, cx| {
 4680                    buffer.edit(edits.iter().cloned(), None, cx)
 4681                });
 4682
 4683                self.change_selections(None, cx, |s| {
 4684                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4685                });
 4686
 4687                self.update_visible_inline_completion(cx);
 4688                if self.active_inline_completion.is_none() {
 4689                    self.refresh_inline_completion(true, true, cx);
 4690                }
 4691
 4692                cx.notify();
 4693            }
 4694        }
 4695    }
 4696
 4697    pub fn accept_partial_inline_completion(
 4698        &mut self,
 4699        _: &AcceptPartialInlineCompletion,
 4700        cx: &mut ViewContext<Self>,
 4701    ) {
 4702        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4703            return;
 4704        };
 4705        if self.selections.count() != 1 {
 4706            return;
 4707        }
 4708
 4709        self.report_inline_completion_event(true, cx);
 4710
 4711        match &active_inline_completion.completion {
 4712            InlineCompletion::Move(position) => {
 4713                let position = *position;
 4714                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4715                    selections.select_anchor_ranges([position..position]);
 4716                });
 4717            }
 4718            InlineCompletion::Edit(edits) => {
 4719                // Find an insertion that starts at the cursor position.
 4720                let snapshot = self.buffer.read(cx).snapshot(cx);
 4721                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4722                let insertion = edits.iter().find_map(|(range, text)| {
 4723                    let range = range.to_offset(&snapshot);
 4724                    if range.is_empty() && range.start == cursor_offset {
 4725                        Some(text)
 4726                    } else {
 4727                        None
 4728                    }
 4729                });
 4730
 4731                if let Some(text) = insertion {
 4732                    let mut partial_completion = text
 4733                        .chars()
 4734                        .by_ref()
 4735                        .take_while(|c| c.is_alphabetic())
 4736                        .collect::<String>();
 4737                    if partial_completion.is_empty() {
 4738                        partial_completion = text
 4739                            .chars()
 4740                            .by_ref()
 4741                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4742                            .collect::<String>();
 4743                    }
 4744
 4745                    cx.emit(EditorEvent::InputHandled {
 4746                        utf16_range_to_replace: None,
 4747                        text: partial_completion.clone().into(),
 4748                    });
 4749
 4750                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4751
 4752                    self.refresh_inline_completion(true, true, cx);
 4753                    cx.notify();
 4754                } else {
 4755                    self.accept_inline_completion(&Default::default(), cx);
 4756                }
 4757            }
 4758        }
 4759    }
 4760
 4761    fn discard_inline_completion(
 4762        &mut self,
 4763        should_report_inline_completion_event: bool,
 4764        cx: &mut ViewContext<Self>,
 4765    ) -> bool {
 4766        if should_report_inline_completion_event {
 4767            self.report_inline_completion_event(false, cx);
 4768        }
 4769
 4770        if let Some(provider) = self.inline_completion_provider() {
 4771            provider.discard(cx);
 4772        }
 4773
 4774        self.take_active_inline_completion(cx).is_some()
 4775    }
 4776
 4777    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4778        let Some(provider) = self.inline_completion_provider() else {
 4779            return;
 4780        };
 4781
 4782        let Some((_, buffer, _)) = self
 4783            .buffer
 4784            .read(cx)
 4785            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4786        else {
 4787            return;
 4788        };
 4789
 4790        let extension = buffer
 4791            .read(cx)
 4792            .file()
 4793            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4794
 4795        let event_type = match accepted {
 4796            true => "Inline Completion Accepted",
 4797            false => "Inline Completion Discarded",
 4798        };
 4799        telemetry::event!(
 4800            event_type,
 4801            provider = provider.name(),
 4802            suggestion_accepted = accepted,
 4803            file_extension = extension,
 4804        );
 4805    }
 4806
 4807    pub fn has_active_inline_completion(&self) -> bool {
 4808        self.active_inline_completion.is_some()
 4809    }
 4810
 4811    fn take_active_inline_completion(
 4812        &mut self,
 4813        cx: &mut ViewContext<Self>,
 4814    ) -> Option<InlineCompletion> {
 4815        let active_inline_completion = self.active_inline_completion.take()?;
 4816        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4817        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4818        Some(active_inline_completion.completion)
 4819    }
 4820
 4821    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4822        let selection = self.selections.newest_anchor();
 4823        let cursor = selection.head();
 4824        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4825        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4826        let excerpt_id = cursor.excerpt_id;
 4827
 4828        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4829            && (self.context_menu.borrow().is_some()
 4830                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4831        if completions_menu_has_precedence
 4832            || !offset_selection.is_empty()
 4833            || !self.enable_inline_completions
 4834            || self
 4835                .active_inline_completion
 4836                .as_ref()
 4837                .map_or(false, |completion| {
 4838                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4839                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4840                    !invalidation_range.contains(&offset_selection.head())
 4841                })
 4842        {
 4843            self.discard_inline_completion(false, cx);
 4844            return None;
 4845        }
 4846
 4847        self.take_active_inline_completion(cx);
 4848        let provider = self.inline_completion_provider()?;
 4849
 4850        let (buffer, cursor_buffer_position) =
 4851            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4852
 4853        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4854        let edits = completion
 4855            .edits
 4856            .into_iter()
 4857            .flat_map(|(range, new_text)| {
 4858                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4859                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4860                Some((start..end, new_text))
 4861            })
 4862            .collect::<Vec<_>>();
 4863        if edits.is_empty() {
 4864            return None;
 4865        }
 4866
 4867        let first_edit_start = edits.first().unwrap().0.start;
 4868        let edit_start_row = first_edit_start
 4869            .to_point(&multibuffer)
 4870            .row
 4871            .saturating_sub(2);
 4872
 4873        let last_edit_end = edits.last().unwrap().0.end;
 4874        let edit_end_row = cmp::min(
 4875            multibuffer.max_point().row,
 4876            last_edit_end.to_point(&multibuffer).row + 2,
 4877        );
 4878
 4879        let cursor_row = cursor.to_point(&multibuffer).row;
 4880
 4881        let mut inlay_ids = Vec::new();
 4882        let invalidation_row_range;
 4883        let completion;
 4884        if cursor_row < edit_start_row {
 4885            invalidation_row_range = cursor_row..edit_end_row;
 4886            completion = InlineCompletion::Move(first_edit_start);
 4887        } else if cursor_row > edit_end_row {
 4888            invalidation_row_range = edit_start_row..cursor_row;
 4889            completion = InlineCompletion::Move(first_edit_start);
 4890        } else {
 4891            if edits
 4892                .iter()
 4893                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4894            {
 4895                let mut inlays = Vec::new();
 4896                for (range, new_text) in &edits {
 4897                    let inlay = Inlay::inline_completion(
 4898                        post_inc(&mut self.next_inlay_id),
 4899                        range.start,
 4900                        new_text.as_str(),
 4901                    );
 4902                    inlay_ids.push(inlay.id);
 4903                    inlays.push(inlay);
 4904                }
 4905
 4906                self.splice_inlays(vec![], inlays, cx);
 4907            } else {
 4908                let background_color = cx.theme().status().deleted_background;
 4909                self.highlight_text::<InlineCompletionHighlight>(
 4910                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4911                    HighlightStyle {
 4912                        background_color: Some(background_color),
 4913                        ..Default::default()
 4914                    },
 4915                    cx,
 4916                );
 4917            }
 4918
 4919            invalidation_row_range = edit_start_row..edit_end_row;
 4920            completion = InlineCompletion::Edit(edits);
 4921        };
 4922
 4923        let invalidation_range = multibuffer
 4924            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4925            ..multibuffer.anchor_after(Point::new(
 4926                invalidation_row_range.end,
 4927                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4928            ));
 4929
 4930        self.active_inline_completion = Some(InlineCompletionState {
 4931            inlay_ids,
 4932            completion,
 4933            invalidation_range,
 4934        });
 4935
 4936        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4937            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4938                match self.context_menu.borrow_mut().as_mut() {
 4939                    Some(CodeContextMenu::Completions(menu)) => {
 4940                        menu.show_inline_completion_hint(hint);
 4941                    }
 4942                    _ => {}
 4943                }
 4944            }
 4945        }
 4946
 4947        cx.notify();
 4948
 4949        Some(())
 4950    }
 4951
 4952    fn inline_completion_menu_hint(
 4953        &mut self,
 4954        cx: &mut ViewContext<Self>,
 4955    ) -> Option<InlineCompletionMenuHint> {
 4956        let provider = self.inline_completion_provider()?;
 4957        if self.has_active_inline_completion() {
 4958            let editor_snapshot = self.snapshot(cx);
 4959
 4960            let text = match &self.active_inline_completion.as_ref()?.completion {
 4961                InlineCompletion::Edit(edits) => {
 4962                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4963                }
 4964                InlineCompletion::Move(target) => {
 4965                    let target_point =
 4966                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4967                    let target_line = target_point.row + 1;
 4968                    InlineCompletionText::Move(
 4969                        format!("Jump to edit in line {}", target_line).into(),
 4970                    )
 4971                }
 4972            };
 4973
 4974            Some(InlineCompletionMenuHint::Loaded { text })
 4975        } else if provider.is_refreshing(cx) {
 4976            Some(InlineCompletionMenuHint::Loading)
 4977        } else {
 4978            Some(InlineCompletionMenuHint::None)
 4979        }
 4980    }
 4981
 4982    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4983        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4984    }
 4985
 4986    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4987        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4988            && self
 4989                .inline_completion_provider()
 4990                .map_or(false, |provider| provider.show_completions_in_menu())
 4991    }
 4992
 4993    fn render_code_actions_indicator(
 4994        &self,
 4995        _style: &EditorStyle,
 4996        row: DisplayRow,
 4997        is_active: bool,
 4998        cx: &mut ViewContext<Self>,
 4999    ) -> Option<IconButton> {
 5000        if self.available_code_actions.is_some() {
 5001            Some(
 5002                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5003                    .shape(ui::IconButtonShape::Square)
 5004                    .icon_size(IconSize::XSmall)
 5005                    .icon_color(Color::Muted)
 5006                    .toggle_state(is_active)
 5007                    .tooltip({
 5008                        let focus_handle = self.focus_handle.clone();
 5009                        move |cx| {
 5010                            Tooltip::for_action_in(
 5011                                "Toggle Code Actions",
 5012                                &ToggleCodeActions {
 5013                                    deployed_from_indicator: None,
 5014                                },
 5015                                &focus_handle,
 5016                                cx,
 5017                            )
 5018                        }
 5019                    })
 5020                    .on_click(cx.listener(move |editor, _e, cx| {
 5021                        editor.focus(cx);
 5022                        editor.toggle_code_actions(
 5023                            &ToggleCodeActions {
 5024                                deployed_from_indicator: Some(row),
 5025                            },
 5026                            cx,
 5027                        );
 5028                    })),
 5029            )
 5030        } else {
 5031            None
 5032        }
 5033    }
 5034
 5035    fn clear_tasks(&mut self) {
 5036        self.tasks.clear()
 5037    }
 5038
 5039    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5040        if self.tasks.insert(key, value).is_some() {
 5041            // This case should hopefully be rare, but just in case...
 5042            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5043        }
 5044    }
 5045
 5046    fn build_tasks_context(
 5047        project: &Model<Project>,
 5048        buffer: &Model<Buffer>,
 5049        buffer_row: u32,
 5050        tasks: &Arc<RunnableTasks>,
 5051        cx: &mut ViewContext<Self>,
 5052    ) -> Task<Option<task::TaskContext>> {
 5053        let position = Point::new(buffer_row, tasks.column);
 5054        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5055        let location = Location {
 5056            buffer: buffer.clone(),
 5057            range: range_start..range_start,
 5058        };
 5059        // Fill in the environmental variables from the tree-sitter captures
 5060        let mut captured_task_variables = TaskVariables::default();
 5061        for (capture_name, value) in tasks.extra_variables.clone() {
 5062            captured_task_variables.insert(
 5063                task::VariableName::Custom(capture_name.into()),
 5064                value.clone(),
 5065            );
 5066        }
 5067        project.update(cx, |project, cx| {
 5068            project.task_store().update(cx, |task_store, cx| {
 5069                task_store.task_context_for_location(captured_task_variables, location, cx)
 5070            })
 5071        })
 5072    }
 5073
 5074    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5075        let Some((workspace, _)) = self.workspace.clone() else {
 5076            return;
 5077        };
 5078        let Some(project) = self.project.clone() else {
 5079            return;
 5080        };
 5081
 5082        // Try to find a closest, enclosing node using tree-sitter that has a
 5083        // task
 5084        let Some((buffer, buffer_row, tasks)) = self
 5085            .find_enclosing_node_task(cx)
 5086            // Or find the task that's closest in row-distance.
 5087            .or_else(|| self.find_closest_task(cx))
 5088        else {
 5089            return;
 5090        };
 5091
 5092        let reveal_strategy = action.reveal;
 5093        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5094        cx.spawn(|_, mut cx| async move {
 5095            let context = task_context.await?;
 5096            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5097
 5098            let resolved = resolved_task.resolved.as_mut()?;
 5099            resolved.reveal = reveal_strategy;
 5100
 5101            workspace
 5102                .update(&mut cx, |workspace, cx| {
 5103                    workspace::tasks::schedule_resolved_task(
 5104                        workspace,
 5105                        task_source_kind,
 5106                        resolved_task,
 5107                        false,
 5108                        cx,
 5109                    );
 5110                })
 5111                .ok()
 5112        })
 5113        .detach();
 5114    }
 5115
 5116    fn find_closest_task(
 5117        &mut self,
 5118        cx: &mut ViewContext<Self>,
 5119    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5120        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5121
 5122        let ((buffer_id, row), tasks) = self
 5123            .tasks
 5124            .iter()
 5125            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5126
 5127        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5128        let tasks = Arc::new(tasks.to_owned());
 5129        Some((buffer, *row, tasks))
 5130    }
 5131
 5132    fn find_enclosing_node_task(
 5133        &mut self,
 5134        cx: &mut ViewContext<Self>,
 5135    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5136        let snapshot = self.buffer.read(cx).snapshot(cx);
 5137        let offset = self.selections.newest::<usize>(cx).head();
 5138        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5139        let buffer_id = excerpt.buffer().remote_id();
 5140
 5141        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5142        let mut cursor = layer.node().walk();
 5143
 5144        while cursor.goto_first_child_for_byte(offset).is_some() {
 5145            if cursor.node().end_byte() == offset {
 5146                cursor.goto_next_sibling();
 5147            }
 5148        }
 5149
 5150        // Ascend to the smallest ancestor that contains the range and has a task.
 5151        loop {
 5152            let node = cursor.node();
 5153            let node_range = node.byte_range();
 5154            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5155
 5156            // Check if this node contains our offset
 5157            if node_range.start <= offset && node_range.end >= offset {
 5158                // If it contains offset, check for task
 5159                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5160                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5161                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5162                }
 5163            }
 5164
 5165            if !cursor.goto_parent() {
 5166                break;
 5167            }
 5168        }
 5169        None
 5170    }
 5171
 5172    fn render_run_indicator(
 5173        &self,
 5174        _style: &EditorStyle,
 5175        is_active: bool,
 5176        row: DisplayRow,
 5177        cx: &mut ViewContext<Self>,
 5178    ) -> IconButton {
 5179        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5180            .shape(ui::IconButtonShape::Square)
 5181            .icon_size(IconSize::XSmall)
 5182            .icon_color(Color::Muted)
 5183            .toggle_state(is_active)
 5184            .on_click(cx.listener(move |editor, _e, cx| {
 5185                editor.focus(cx);
 5186                editor.toggle_code_actions(
 5187                    &ToggleCodeActions {
 5188                        deployed_from_indicator: Some(row),
 5189                    },
 5190                    cx,
 5191                );
 5192            }))
 5193    }
 5194
 5195    #[cfg(any(feature = "test-support", test))]
 5196    pub fn context_menu_visible(&self) -> bool {
 5197        self.context_menu
 5198            .borrow()
 5199            .as_ref()
 5200            .map_or(false, |menu| menu.visible())
 5201    }
 5202
 5203    #[cfg(feature = "test-support")]
 5204    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5205        self.context_menu
 5206            .borrow()
 5207            .as_ref()
 5208            .map_or(false, |menu| match menu {
 5209                CodeContextMenu::Completions(menu) => {
 5210                    menu.entries.borrow().first().map_or(false, |entry| {
 5211                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5212                    })
 5213                }
 5214                CodeContextMenu::CodeActions(_) => false,
 5215            })
 5216    }
 5217
 5218    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5219        self.context_menu
 5220            .borrow()
 5221            .as_ref()
 5222            .map(|menu| menu.origin(cursor_position))
 5223    }
 5224
 5225    fn render_context_menu(
 5226        &self,
 5227        style: &EditorStyle,
 5228        max_height_in_lines: u32,
 5229        cx: &mut ViewContext<Editor>,
 5230    ) -> Option<AnyElement> {
 5231        self.context_menu.borrow().as_ref().and_then(|menu| {
 5232            if menu.visible() {
 5233                Some(menu.render(style, max_height_in_lines, cx))
 5234            } else {
 5235                None
 5236            }
 5237        })
 5238    }
 5239
 5240    fn render_context_menu_aside(
 5241        &self,
 5242        style: &EditorStyle,
 5243        max_size: Size<Pixels>,
 5244        cx: &mut ViewContext<Editor>,
 5245    ) -> Option<AnyElement> {
 5246        self.context_menu.borrow().as_ref().and_then(|menu| {
 5247            if menu.visible() {
 5248                menu.render_aside(
 5249                    style,
 5250                    max_size,
 5251                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5252                    cx,
 5253                )
 5254            } else {
 5255                None
 5256            }
 5257        })
 5258    }
 5259
 5260    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5261        cx.notify();
 5262        self.completion_tasks.clear();
 5263        let context_menu = self.context_menu.borrow_mut().take();
 5264        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5265            self.update_visible_inline_completion(cx);
 5266        }
 5267        context_menu
 5268    }
 5269
 5270    fn show_snippet_choices(
 5271        &mut self,
 5272        choices: &Vec<String>,
 5273        selection: Range<Anchor>,
 5274        cx: &mut ViewContext<Self>,
 5275    ) {
 5276        if selection.start.buffer_id.is_none() {
 5277            return;
 5278        }
 5279        let buffer_id = selection.start.buffer_id.unwrap();
 5280        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5281        let id = post_inc(&mut self.next_completion_id);
 5282
 5283        if let Some(buffer) = buffer {
 5284            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5285                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5286            ));
 5287        }
 5288    }
 5289
 5290    pub fn insert_snippet(
 5291        &mut self,
 5292        insertion_ranges: &[Range<usize>],
 5293        snippet: Snippet,
 5294        cx: &mut ViewContext<Self>,
 5295    ) -> Result<()> {
 5296        struct Tabstop<T> {
 5297            is_end_tabstop: bool,
 5298            ranges: Vec<Range<T>>,
 5299            choices: Option<Vec<String>>,
 5300        }
 5301
 5302        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5303            let snippet_text: Arc<str> = snippet.text.clone().into();
 5304            buffer.edit(
 5305                insertion_ranges
 5306                    .iter()
 5307                    .cloned()
 5308                    .map(|range| (range, snippet_text.clone())),
 5309                Some(AutoindentMode::EachLine),
 5310                cx,
 5311            );
 5312
 5313            let snapshot = &*buffer.read(cx);
 5314            let snippet = &snippet;
 5315            snippet
 5316                .tabstops
 5317                .iter()
 5318                .map(|tabstop| {
 5319                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5320                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5321                    });
 5322                    let mut tabstop_ranges = tabstop
 5323                        .ranges
 5324                        .iter()
 5325                        .flat_map(|tabstop_range| {
 5326                            let mut delta = 0_isize;
 5327                            insertion_ranges.iter().map(move |insertion_range| {
 5328                                let insertion_start = insertion_range.start as isize + delta;
 5329                                delta +=
 5330                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5331
 5332                                let start = ((insertion_start + tabstop_range.start) as usize)
 5333                                    .min(snapshot.len());
 5334                                let end = ((insertion_start + tabstop_range.end) as usize)
 5335                                    .min(snapshot.len());
 5336                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5337                            })
 5338                        })
 5339                        .collect::<Vec<_>>();
 5340                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5341
 5342                    Tabstop {
 5343                        is_end_tabstop,
 5344                        ranges: tabstop_ranges,
 5345                        choices: tabstop.choices.clone(),
 5346                    }
 5347                })
 5348                .collect::<Vec<_>>()
 5349        });
 5350        if let Some(tabstop) = tabstops.first() {
 5351            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5352                s.select_ranges(tabstop.ranges.iter().cloned());
 5353            });
 5354
 5355            if let Some(choices) = &tabstop.choices {
 5356                if let Some(selection) = tabstop.ranges.first() {
 5357                    self.show_snippet_choices(choices, selection.clone(), cx)
 5358                }
 5359            }
 5360
 5361            // If we're already at the last tabstop and it's at the end of the snippet,
 5362            // we're done, we don't need to keep the state around.
 5363            if !tabstop.is_end_tabstop {
 5364                let choices = tabstops
 5365                    .iter()
 5366                    .map(|tabstop| tabstop.choices.clone())
 5367                    .collect();
 5368
 5369                let ranges = tabstops
 5370                    .into_iter()
 5371                    .map(|tabstop| tabstop.ranges)
 5372                    .collect::<Vec<_>>();
 5373
 5374                self.snippet_stack.push(SnippetState {
 5375                    active_index: 0,
 5376                    ranges,
 5377                    choices,
 5378                });
 5379            }
 5380
 5381            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5382            if self.autoclose_regions.is_empty() {
 5383                let snapshot = self.buffer.read(cx).snapshot(cx);
 5384                for selection in &mut self.selections.all::<Point>(cx) {
 5385                    let selection_head = selection.head();
 5386                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5387                        continue;
 5388                    };
 5389
 5390                    let mut bracket_pair = None;
 5391                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5392                    let prev_chars = snapshot
 5393                        .reversed_chars_at(selection_head)
 5394                        .collect::<String>();
 5395                    for (pair, enabled) in scope.brackets() {
 5396                        if enabled
 5397                            && pair.close
 5398                            && prev_chars.starts_with(pair.start.as_str())
 5399                            && next_chars.starts_with(pair.end.as_str())
 5400                        {
 5401                            bracket_pair = Some(pair.clone());
 5402                            break;
 5403                        }
 5404                    }
 5405                    if let Some(pair) = bracket_pair {
 5406                        let start = snapshot.anchor_after(selection_head);
 5407                        let end = snapshot.anchor_after(selection_head);
 5408                        self.autoclose_regions.push(AutocloseRegion {
 5409                            selection_id: selection.id,
 5410                            range: start..end,
 5411                            pair,
 5412                        });
 5413                    }
 5414                }
 5415            }
 5416        }
 5417        Ok(())
 5418    }
 5419
 5420    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5421        self.move_to_snippet_tabstop(Bias::Right, cx)
 5422    }
 5423
 5424    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5425        self.move_to_snippet_tabstop(Bias::Left, cx)
 5426    }
 5427
 5428    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5429        if let Some(mut snippet) = self.snippet_stack.pop() {
 5430            match bias {
 5431                Bias::Left => {
 5432                    if snippet.active_index > 0 {
 5433                        snippet.active_index -= 1;
 5434                    } else {
 5435                        self.snippet_stack.push(snippet);
 5436                        return false;
 5437                    }
 5438                }
 5439                Bias::Right => {
 5440                    if snippet.active_index + 1 < snippet.ranges.len() {
 5441                        snippet.active_index += 1;
 5442                    } else {
 5443                        self.snippet_stack.push(snippet);
 5444                        return false;
 5445                    }
 5446                }
 5447            }
 5448            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5449                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5450                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5451                });
 5452
 5453                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5454                    if let Some(selection) = current_ranges.first() {
 5455                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5456                    }
 5457                }
 5458
 5459                // If snippet state is not at the last tabstop, push it back on the stack
 5460                if snippet.active_index + 1 < snippet.ranges.len() {
 5461                    self.snippet_stack.push(snippet);
 5462                }
 5463                return true;
 5464            }
 5465        }
 5466
 5467        false
 5468    }
 5469
 5470    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5471        self.transact(cx, |this, cx| {
 5472            this.select_all(&SelectAll, cx);
 5473            this.insert("", cx);
 5474        });
 5475    }
 5476
 5477    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5478        self.transact(cx, |this, cx| {
 5479            this.select_autoclose_pair(cx);
 5480            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5481            if !this.linked_edit_ranges.is_empty() {
 5482                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5483                let snapshot = this.buffer.read(cx).snapshot(cx);
 5484
 5485                for selection in selections.iter() {
 5486                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5487                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5488                    if selection_start.buffer_id != selection_end.buffer_id {
 5489                        continue;
 5490                    }
 5491                    if let Some(ranges) =
 5492                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5493                    {
 5494                        for (buffer, entries) in ranges {
 5495                            linked_ranges.entry(buffer).or_default().extend(entries);
 5496                        }
 5497                    }
 5498                }
 5499            }
 5500
 5501            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5502            if !this.selections.line_mode {
 5503                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5504                for selection in &mut selections {
 5505                    if selection.is_empty() {
 5506                        let old_head = selection.head();
 5507                        let mut new_head =
 5508                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5509                                .to_point(&display_map);
 5510                        if let Some((buffer, line_buffer_range)) = display_map
 5511                            .buffer_snapshot
 5512                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5513                        {
 5514                            let indent_size =
 5515                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5516                            let indent_len = match indent_size.kind {
 5517                                IndentKind::Space => {
 5518                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5519                                }
 5520                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5521                            };
 5522                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5523                                let indent_len = indent_len.get();
 5524                                new_head = cmp::min(
 5525                                    new_head,
 5526                                    MultiBufferPoint::new(
 5527                                        old_head.row,
 5528                                        ((old_head.column - 1) / indent_len) * indent_len,
 5529                                    ),
 5530                                );
 5531                            }
 5532                        }
 5533
 5534                        selection.set_head(new_head, SelectionGoal::None);
 5535                    }
 5536                }
 5537            }
 5538
 5539            this.signature_help_state.set_backspace_pressed(true);
 5540            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5541            this.insert("", cx);
 5542            let empty_str: Arc<str> = Arc::from("");
 5543            for (buffer, edits) in linked_ranges {
 5544                let snapshot = buffer.read(cx).snapshot();
 5545                use text::ToPoint as TP;
 5546
 5547                let edits = edits
 5548                    .into_iter()
 5549                    .map(|range| {
 5550                        let end_point = TP::to_point(&range.end, &snapshot);
 5551                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5552
 5553                        if end_point == start_point {
 5554                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5555                                .saturating_sub(1);
 5556                            start_point =
 5557                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5558                        };
 5559
 5560                        (start_point..end_point, empty_str.clone())
 5561                    })
 5562                    .sorted_by_key(|(range, _)| range.start)
 5563                    .collect::<Vec<_>>();
 5564                buffer.update(cx, |this, cx| {
 5565                    this.edit(edits, None, cx);
 5566                })
 5567            }
 5568            this.refresh_inline_completion(true, false, cx);
 5569            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5570        });
 5571    }
 5572
 5573    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5574        self.transact(cx, |this, cx| {
 5575            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5576                let line_mode = s.line_mode;
 5577                s.move_with(|map, selection| {
 5578                    if selection.is_empty() && !line_mode {
 5579                        let cursor = movement::right(map, selection.head());
 5580                        selection.end = cursor;
 5581                        selection.reversed = true;
 5582                        selection.goal = SelectionGoal::None;
 5583                    }
 5584                })
 5585            });
 5586            this.insert("", cx);
 5587            this.refresh_inline_completion(true, false, cx);
 5588        });
 5589    }
 5590
 5591    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5592        if self.move_to_prev_snippet_tabstop(cx) {
 5593            return;
 5594        }
 5595
 5596        self.outdent(&Outdent, cx);
 5597    }
 5598
 5599    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5600        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5601            return;
 5602        }
 5603
 5604        let mut selections = self.selections.all_adjusted(cx);
 5605        let buffer = self.buffer.read(cx);
 5606        let snapshot = buffer.snapshot(cx);
 5607        let rows_iter = selections.iter().map(|s| s.head().row);
 5608        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5609
 5610        let mut edits = Vec::new();
 5611        let mut prev_edited_row = 0;
 5612        let mut row_delta = 0;
 5613        for selection in &mut selections {
 5614            if selection.start.row != prev_edited_row {
 5615                row_delta = 0;
 5616            }
 5617            prev_edited_row = selection.end.row;
 5618
 5619            // If the selection is non-empty, then increase the indentation of the selected lines.
 5620            if !selection.is_empty() {
 5621                row_delta =
 5622                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5623                continue;
 5624            }
 5625
 5626            // If the selection is empty and the cursor is in the leading whitespace before the
 5627            // suggested indentation, then auto-indent the line.
 5628            let cursor = selection.head();
 5629            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5630            if let Some(suggested_indent) =
 5631                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5632            {
 5633                if cursor.column < suggested_indent.len
 5634                    && cursor.column <= current_indent.len
 5635                    && current_indent.len <= suggested_indent.len
 5636                {
 5637                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5638                    selection.end = selection.start;
 5639                    if row_delta == 0 {
 5640                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5641                            cursor.row,
 5642                            current_indent,
 5643                            suggested_indent,
 5644                        ));
 5645                        row_delta = suggested_indent.len - current_indent.len;
 5646                    }
 5647                    continue;
 5648                }
 5649            }
 5650
 5651            // Otherwise, insert a hard or soft tab.
 5652            let settings = buffer.settings_at(cursor, cx);
 5653            let tab_size = if settings.hard_tabs {
 5654                IndentSize::tab()
 5655            } else {
 5656                let tab_size = settings.tab_size.get();
 5657                let char_column = snapshot
 5658                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5659                    .flat_map(str::chars)
 5660                    .count()
 5661                    + row_delta as usize;
 5662                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5663                IndentSize::spaces(chars_to_next_tab_stop)
 5664            };
 5665            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5666            selection.end = selection.start;
 5667            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5668            row_delta += tab_size.len;
 5669        }
 5670
 5671        self.transact(cx, |this, cx| {
 5672            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5673            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5674            this.refresh_inline_completion(true, false, cx);
 5675        });
 5676    }
 5677
 5678    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5679        if self.read_only(cx) {
 5680            return;
 5681        }
 5682        let mut selections = self.selections.all::<Point>(cx);
 5683        let mut prev_edited_row = 0;
 5684        let mut row_delta = 0;
 5685        let mut edits = Vec::new();
 5686        let buffer = self.buffer.read(cx);
 5687        let snapshot = buffer.snapshot(cx);
 5688        for selection in &mut selections {
 5689            if selection.start.row != prev_edited_row {
 5690                row_delta = 0;
 5691            }
 5692            prev_edited_row = selection.end.row;
 5693
 5694            row_delta =
 5695                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5696        }
 5697
 5698        self.transact(cx, |this, cx| {
 5699            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5700            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5701        });
 5702    }
 5703
 5704    fn indent_selection(
 5705        buffer: &MultiBuffer,
 5706        snapshot: &MultiBufferSnapshot,
 5707        selection: &mut Selection<Point>,
 5708        edits: &mut Vec<(Range<Point>, String)>,
 5709        delta_for_start_row: u32,
 5710        cx: &AppContext,
 5711    ) -> u32 {
 5712        let settings = buffer.settings_at(selection.start, cx);
 5713        let tab_size = settings.tab_size.get();
 5714        let indent_kind = if settings.hard_tabs {
 5715            IndentKind::Tab
 5716        } else {
 5717            IndentKind::Space
 5718        };
 5719        let mut start_row = selection.start.row;
 5720        let mut end_row = selection.end.row + 1;
 5721
 5722        // If a selection ends at the beginning of a line, don't indent
 5723        // that last line.
 5724        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5725            end_row -= 1;
 5726        }
 5727
 5728        // Avoid re-indenting a row that has already been indented by a
 5729        // previous selection, but still update this selection's column
 5730        // to reflect that indentation.
 5731        if delta_for_start_row > 0 {
 5732            start_row += 1;
 5733            selection.start.column += delta_for_start_row;
 5734            if selection.end.row == selection.start.row {
 5735                selection.end.column += delta_for_start_row;
 5736            }
 5737        }
 5738
 5739        let mut delta_for_end_row = 0;
 5740        let has_multiple_rows = start_row + 1 != end_row;
 5741        for row in start_row..end_row {
 5742            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5743            let indent_delta = match (current_indent.kind, indent_kind) {
 5744                (IndentKind::Space, IndentKind::Space) => {
 5745                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5746                    IndentSize::spaces(columns_to_next_tab_stop)
 5747                }
 5748                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5749                (_, IndentKind::Tab) => IndentSize::tab(),
 5750            };
 5751
 5752            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5753                0
 5754            } else {
 5755                selection.start.column
 5756            };
 5757            let row_start = Point::new(row, start);
 5758            edits.push((
 5759                row_start..row_start,
 5760                indent_delta.chars().collect::<String>(),
 5761            ));
 5762
 5763            // Update this selection's endpoints to reflect the indentation.
 5764            if row == selection.start.row {
 5765                selection.start.column += indent_delta.len;
 5766            }
 5767            if row == selection.end.row {
 5768                selection.end.column += indent_delta.len;
 5769                delta_for_end_row = indent_delta.len;
 5770            }
 5771        }
 5772
 5773        if selection.start.row == selection.end.row {
 5774            delta_for_start_row + delta_for_end_row
 5775        } else {
 5776            delta_for_end_row
 5777        }
 5778    }
 5779
 5780    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5781        if self.read_only(cx) {
 5782            return;
 5783        }
 5784        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5785        let selections = self.selections.all::<Point>(cx);
 5786        let mut deletion_ranges = Vec::new();
 5787        let mut last_outdent = None;
 5788        {
 5789            let buffer = self.buffer.read(cx);
 5790            let snapshot = buffer.snapshot(cx);
 5791            for selection in &selections {
 5792                let settings = buffer.settings_at(selection.start, cx);
 5793                let tab_size = settings.tab_size.get();
 5794                let mut rows = selection.spanned_rows(false, &display_map);
 5795
 5796                // Avoid re-outdenting a row that has already been outdented by a
 5797                // previous selection.
 5798                if let Some(last_row) = last_outdent {
 5799                    if last_row == rows.start {
 5800                        rows.start = rows.start.next_row();
 5801                    }
 5802                }
 5803                let has_multiple_rows = rows.len() > 1;
 5804                for row in rows.iter_rows() {
 5805                    let indent_size = snapshot.indent_size_for_line(row);
 5806                    if indent_size.len > 0 {
 5807                        let deletion_len = match indent_size.kind {
 5808                            IndentKind::Space => {
 5809                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5810                                if columns_to_prev_tab_stop == 0 {
 5811                                    tab_size
 5812                                } else {
 5813                                    columns_to_prev_tab_stop
 5814                                }
 5815                            }
 5816                            IndentKind::Tab => 1,
 5817                        };
 5818                        let start = if has_multiple_rows
 5819                            || deletion_len > selection.start.column
 5820                            || indent_size.len < selection.start.column
 5821                        {
 5822                            0
 5823                        } else {
 5824                            selection.start.column - deletion_len
 5825                        };
 5826                        deletion_ranges.push(
 5827                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5828                        );
 5829                        last_outdent = Some(row);
 5830                    }
 5831                }
 5832            }
 5833        }
 5834
 5835        self.transact(cx, |this, cx| {
 5836            this.buffer.update(cx, |buffer, cx| {
 5837                let empty_str: Arc<str> = Arc::default();
 5838                buffer.edit(
 5839                    deletion_ranges
 5840                        .into_iter()
 5841                        .map(|range| (range, empty_str.clone())),
 5842                    None,
 5843                    cx,
 5844                );
 5845            });
 5846            let selections = this.selections.all::<usize>(cx);
 5847            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5848        });
 5849    }
 5850
 5851    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5852        if self.read_only(cx) {
 5853            return;
 5854        }
 5855        let selections = self
 5856            .selections
 5857            .all::<usize>(cx)
 5858            .into_iter()
 5859            .map(|s| s.range());
 5860
 5861        self.transact(cx, |this, cx| {
 5862            this.buffer.update(cx, |buffer, cx| {
 5863                buffer.autoindent_ranges(selections, cx);
 5864            });
 5865            let selections = this.selections.all::<usize>(cx);
 5866            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5867        });
 5868    }
 5869
 5870    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5872        let selections = self.selections.all::<Point>(cx);
 5873
 5874        let mut new_cursors = Vec::new();
 5875        let mut edit_ranges = Vec::new();
 5876        let mut selections = selections.iter().peekable();
 5877        while let Some(selection) = selections.next() {
 5878            let mut rows = selection.spanned_rows(false, &display_map);
 5879            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5880
 5881            // Accumulate contiguous regions of rows that we want to delete.
 5882            while let Some(next_selection) = selections.peek() {
 5883                let next_rows = next_selection.spanned_rows(false, &display_map);
 5884                if next_rows.start <= rows.end {
 5885                    rows.end = next_rows.end;
 5886                    selections.next().unwrap();
 5887                } else {
 5888                    break;
 5889                }
 5890            }
 5891
 5892            let buffer = &display_map.buffer_snapshot;
 5893            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5894            let edit_end;
 5895            let cursor_buffer_row;
 5896            if buffer.max_point().row >= rows.end.0 {
 5897                // If there's a line after the range, delete the \n from the end of the row range
 5898                // and position the cursor on the next line.
 5899                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5900                cursor_buffer_row = rows.end;
 5901            } else {
 5902                // If there isn't a line after the range, delete the \n from the line before the
 5903                // start of the row range and position the cursor there.
 5904                edit_start = edit_start.saturating_sub(1);
 5905                edit_end = buffer.len();
 5906                cursor_buffer_row = rows.start.previous_row();
 5907            }
 5908
 5909            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5910            *cursor.column_mut() =
 5911                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5912
 5913            new_cursors.push((
 5914                selection.id,
 5915                buffer.anchor_after(cursor.to_point(&display_map)),
 5916            ));
 5917            edit_ranges.push(edit_start..edit_end);
 5918        }
 5919
 5920        self.transact(cx, |this, cx| {
 5921            let buffer = this.buffer.update(cx, |buffer, cx| {
 5922                let empty_str: Arc<str> = Arc::default();
 5923                buffer.edit(
 5924                    edit_ranges
 5925                        .into_iter()
 5926                        .map(|range| (range, empty_str.clone())),
 5927                    None,
 5928                    cx,
 5929                );
 5930                buffer.snapshot(cx)
 5931            });
 5932            let new_selections = new_cursors
 5933                .into_iter()
 5934                .map(|(id, cursor)| {
 5935                    let cursor = cursor.to_point(&buffer);
 5936                    Selection {
 5937                        id,
 5938                        start: cursor,
 5939                        end: cursor,
 5940                        reversed: false,
 5941                        goal: SelectionGoal::None,
 5942                    }
 5943                })
 5944                .collect();
 5945
 5946            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5947                s.select(new_selections);
 5948            });
 5949        });
 5950    }
 5951
 5952    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5953        if self.read_only(cx) {
 5954            return;
 5955        }
 5956        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5957        for selection in self.selections.all::<Point>(cx) {
 5958            let start = MultiBufferRow(selection.start.row);
 5959            // Treat single line selections as if they include the next line. Otherwise this action
 5960            // would do nothing for single line selections individual cursors.
 5961            let end = if selection.start.row == selection.end.row {
 5962                MultiBufferRow(selection.start.row + 1)
 5963            } else {
 5964                MultiBufferRow(selection.end.row)
 5965            };
 5966
 5967            if let Some(last_row_range) = row_ranges.last_mut() {
 5968                if start <= last_row_range.end {
 5969                    last_row_range.end = end;
 5970                    continue;
 5971                }
 5972            }
 5973            row_ranges.push(start..end);
 5974        }
 5975
 5976        let snapshot = self.buffer.read(cx).snapshot(cx);
 5977        let mut cursor_positions = Vec::new();
 5978        for row_range in &row_ranges {
 5979            let anchor = snapshot.anchor_before(Point::new(
 5980                row_range.end.previous_row().0,
 5981                snapshot.line_len(row_range.end.previous_row()),
 5982            ));
 5983            cursor_positions.push(anchor..anchor);
 5984        }
 5985
 5986        self.transact(cx, |this, cx| {
 5987            for row_range in row_ranges.into_iter().rev() {
 5988                for row in row_range.iter_rows().rev() {
 5989                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5990                    let next_line_row = row.next_row();
 5991                    let indent = snapshot.indent_size_for_line(next_line_row);
 5992                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5993
 5994                    let replace =
 5995                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5996                            " "
 5997                        } else {
 5998                            ""
 5999                        };
 6000
 6001                    this.buffer.update(cx, |buffer, cx| {
 6002                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6003                    });
 6004                }
 6005            }
 6006
 6007            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6008                s.select_anchor_ranges(cursor_positions)
 6009            });
 6010        });
 6011    }
 6012
 6013    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6014        self.join_lines_impl(true, cx);
 6015    }
 6016
 6017    pub fn sort_lines_case_sensitive(
 6018        &mut self,
 6019        _: &SortLinesCaseSensitive,
 6020        cx: &mut ViewContext<Self>,
 6021    ) {
 6022        self.manipulate_lines(cx, |lines| lines.sort())
 6023    }
 6024
 6025    pub fn sort_lines_case_insensitive(
 6026        &mut self,
 6027        _: &SortLinesCaseInsensitive,
 6028        cx: &mut ViewContext<Self>,
 6029    ) {
 6030        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6031    }
 6032
 6033    pub fn unique_lines_case_insensitive(
 6034        &mut self,
 6035        _: &UniqueLinesCaseInsensitive,
 6036        cx: &mut ViewContext<Self>,
 6037    ) {
 6038        self.manipulate_lines(cx, |lines| {
 6039            let mut seen = HashSet::default();
 6040            lines.retain(|line| seen.insert(line.to_lowercase()));
 6041        })
 6042    }
 6043
 6044    pub fn unique_lines_case_sensitive(
 6045        &mut self,
 6046        _: &UniqueLinesCaseSensitive,
 6047        cx: &mut ViewContext<Self>,
 6048    ) {
 6049        self.manipulate_lines(cx, |lines| {
 6050            let mut seen = HashSet::default();
 6051            lines.retain(|line| seen.insert(*line));
 6052        })
 6053    }
 6054
 6055    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6056        let mut revert_changes = HashMap::default();
 6057        let snapshot = self.snapshot(cx);
 6058        for hunk in hunks_for_ranges(
 6059            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6060            &snapshot,
 6061        ) {
 6062            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6063        }
 6064        if !revert_changes.is_empty() {
 6065            self.transact(cx, |editor, cx| {
 6066                editor.revert(revert_changes, cx);
 6067            });
 6068        }
 6069    }
 6070
 6071    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6072        let Some(project) = self.project.clone() else {
 6073            return;
 6074        };
 6075        self.reload(project, cx).detach_and_notify_err(cx);
 6076    }
 6077
 6078    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6079        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6080        if !revert_changes.is_empty() {
 6081            self.transact(cx, |editor, cx| {
 6082                editor.revert(revert_changes, cx);
 6083            });
 6084        }
 6085    }
 6086
 6087    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6088        let snapshot = self.buffer.read(cx).read(cx);
 6089        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6090            drop(snapshot);
 6091            let mut revert_changes = HashMap::default();
 6092            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6093            if !revert_changes.is_empty() {
 6094                self.revert(revert_changes, cx)
 6095            }
 6096        }
 6097    }
 6098
 6099    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6100        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6101            let project_path = buffer.read(cx).project_path(cx)?;
 6102            let project = self.project.as_ref()?.read(cx);
 6103            let entry = project.entry_for_path(&project_path, cx)?;
 6104            let parent = match &entry.canonical_path {
 6105                Some(canonical_path) => canonical_path.to_path_buf(),
 6106                None => project.absolute_path(&project_path, cx)?,
 6107            }
 6108            .parent()?
 6109            .to_path_buf();
 6110            Some(parent)
 6111        }) {
 6112            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6113        }
 6114    }
 6115
 6116    fn gather_revert_changes(
 6117        &mut self,
 6118        selections: &[Selection<Point>],
 6119        cx: &mut ViewContext<Editor>,
 6120    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6121        let mut revert_changes = HashMap::default();
 6122        let snapshot = self.snapshot(cx);
 6123        for hunk in hunks_for_selections(&snapshot, selections) {
 6124            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6125        }
 6126        revert_changes
 6127    }
 6128
 6129    pub fn prepare_revert_change(
 6130        &mut self,
 6131        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6132        hunk: &MultiBufferDiffHunk,
 6133        cx: &AppContext,
 6134    ) -> Option<()> {
 6135        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6136        let buffer = buffer.read(cx);
 6137        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6138        let original_text = change_set
 6139            .read(cx)
 6140            .base_text
 6141            .as_ref()?
 6142            .read(cx)
 6143            .as_rope()
 6144            .slice(hunk.diff_base_byte_range.clone());
 6145        let buffer_snapshot = buffer.snapshot();
 6146        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6147        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6148            probe
 6149                .0
 6150                .start
 6151                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6152                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6153        }) {
 6154            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6155            Some(())
 6156        } else {
 6157            None
 6158        }
 6159    }
 6160
 6161    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6162        self.manipulate_lines(cx, |lines| lines.reverse())
 6163    }
 6164
 6165    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6166        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6167    }
 6168
 6169    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6170    where
 6171        Fn: FnMut(&mut Vec<&str>),
 6172    {
 6173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6174        let buffer = self.buffer.read(cx).snapshot(cx);
 6175
 6176        let mut edits = Vec::new();
 6177
 6178        let selections = self.selections.all::<Point>(cx);
 6179        let mut selections = selections.iter().peekable();
 6180        let mut contiguous_row_selections = Vec::new();
 6181        let mut new_selections = Vec::new();
 6182        let mut added_lines = 0;
 6183        let mut removed_lines = 0;
 6184
 6185        while let Some(selection) = selections.next() {
 6186            let (start_row, end_row) = consume_contiguous_rows(
 6187                &mut contiguous_row_selections,
 6188                selection,
 6189                &display_map,
 6190                &mut selections,
 6191            );
 6192
 6193            let start_point = Point::new(start_row.0, 0);
 6194            let end_point = Point::new(
 6195                end_row.previous_row().0,
 6196                buffer.line_len(end_row.previous_row()),
 6197            );
 6198            let text = buffer
 6199                .text_for_range(start_point..end_point)
 6200                .collect::<String>();
 6201
 6202            let mut lines = text.split('\n').collect_vec();
 6203
 6204            let lines_before = lines.len();
 6205            callback(&mut lines);
 6206            let lines_after = lines.len();
 6207
 6208            edits.push((start_point..end_point, lines.join("\n")));
 6209
 6210            // Selections must change based on added and removed line count
 6211            let start_row =
 6212                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6213            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6214            new_selections.push(Selection {
 6215                id: selection.id,
 6216                start: start_row,
 6217                end: end_row,
 6218                goal: SelectionGoal::None,
 6219                reversed: selection.reversed,
 6220            });
 6221
 6222            if lines_after > lines_before {
 6223                added_lines += lines_after - lines_before;
 6224            } else if lines_before > lines_after {
 6225                removed_lines += lines_before - lines_after;
 6226            }
 6227        }
 6228
 6229        self.transact(cx, |this, cx| {
 6230            let buffer = this.buffer.update(cx, |buffer, cx| {
 6231                buffer.edit(edits, None, cx);
 6232                buffer.snapshot(cx)
 6233            });
 6234
 6235            // Recalculate offsets on newly edited buffer
 6236            let new_selections = new_selections
 6237                .iter()
 6238                .map(|s| {
 6239                    let start_point = Point::new(s.start.0, 0);
 6240                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6241                    Selection {
 6242                        id: s.id,
 6243                        start: buffer.point_to_offset(start_point),
 6244                        end: buffer.point_to_offset(end_point),
 6245                        goal: s.goal,
 6246                        reversed: s.reversed,
 6247                    }
 6248                })
 6249                .collect();
 6250
 6251            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6252                s.select(new_selections);
 6253            });
 6254
 6255            this.request_autoscroll(Autoscroll::fit(), cx);
 6256        });
 6257    }
 6258
 6259    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6260        self.manipulate_text(cx, |text| text.to_uppercase())
 6261    }
 6262
 6263    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6264        self.manipulate_text(cx, |text| text.to_lowercase())
 6265    }
 6266
 6267    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6268        self.manipulate_text(cx, |text| {
 6269            text.split('\n')
 6270                .map(|line| line.to_case(Case::Title))
 6271                .join("\n")
 6272        })
 6273    }
 6274
 6275    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6276        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6277    }
 6278
 6279    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6280        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6281    }
 6282
 6283    pub fn convert_to_upper_camel_case(
 6284        &mut self,
 6285        _: &ConvertToUpperCamelCase,
 6286        cx: &mut ViewContext<Self>,
 6287    ) {
 6288        self.manipulate_text(cx, |text| {
 6289            text.split('\n')
 6290                .map(|line| line.to_case(Case::UpperCamel))
 6291                .join("\n")
 6292        })
 6293    }
 6294
 6295    pub fn convert_to_lower_camel_case(
 6296        &mut self,
 6297        _: &ConvertToLowerCamelCase,
 6298        cx: &mut ViewContext<Self>,
 6299    ) {
 6300        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6301    }
 6302
 6303    pub fn convert_to_opposite_case(
 6304        &mut self,
 6305        _: &ConvertToOppositeCase,
 6306        cx: &mut ViewContext<Self>,
 6307    ) {
 6308        self.manipulate_text(cx, |text| {
 6309            text.chars()
 6310                .fold(String::with_capacity(text.len()), |mut t, c| {
 6311                    if c.is_uppercase() {
 6312                        t.extend(c.to_lowercase());
 6313                    } else {
 6314                        t.extend(c.to_uppercase());
 6315                    }
 6316                    t
 6317                })
 6318        })
 6319    }
 6320
 6321    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6322    where
 6323        Fn: FnMut(&str) -> String,
 6324    {
 6325        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6326        let buffer = self.buffer.read(cx).snapshot(cx);
 6327
 6328        let mut new_selections = Vec::new();
 6329        let mut edits = Vec::new();
 6330        let mut selection_adjustment = 0i32;
 6331
 6332        for selection in self.selections.all::<usize>(cx) {
 6333            let selection_is_empty = selection.is_empty();
 6334
 6335            let (start, end) = if selection_is_empty {
 6336                let word_range = movement::surrounding_word(
 6337                    &display_map,
 6338                    selection.start.to_display_point(&display_map),
 6339                );
 6340                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6341                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6342                (start, end)
 6343            } else {
 6344                (selection.start, selection.end)
 6345            };
 6346
 6347            let text = buffer.text_for_range(start..end).collect::<String>();
 6348            let old_length = text.len() as i32;
 6349            let text = callback(&text);
 6350
 6351            new_selections.push(Selection {
 6352                start: (start as i32 - selection_adjustment) as usize,
 6353                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6354                goal: SelectionGoal::None,
 6355                ..selection
 6356            });
 6357
 6358            selection_adjustment += old_length - text.len() as i32;
 6359
 6360            edits.push((start..end, text));
 6361        }
 6362
 6363        self.transact(cx, |this, cx| {
 6364            this.buffer.update(cx, |buffer, cx| {
 6365                buffer.edit(edits, None, cx);
 6366            });
 6367
 6368            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6369                s.select(new_selections);
 6370            });
 6371
 6372            this.request_autoscroll(Autoscroll::fit(), cx);
 6373        });
 6374    }
 6375
 6376    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6378        let buffer = &display_map.buffer_snapshot;
 6379        let selections = self.selections.all::<Point>(cx);
 6380
 6381        let mut edits = Vec::new();
 6382        let mut selections_iter = selections.iter().peekable();
 6383        while let Some(selection) = selections_iter.next() {
 6384            let mut rows = selection.spanned_rows(false, &display_map);
 6385            // duplicate line-wise
 6386            if whole_lines || selection.start == selection.end {
 6387                // Avoid duplicating the same lines twice.
 6388                while let Some(next_selection) = selections_iter.peek() {
 6389                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6390                    if next_rows.start < rows.end {
 6391                        rows.end = next_rows.end;
 6392                        selections_iter.next().unwrap();
 6393                    } else {
 6394                        break;
 6395                    }
 6396                }
 6397
 6398                // Copy the text from the selected row region and splice it either at the start
 6399                // or end of the region.
 6400                let start = Point::new(rows.start.0, 0);
 6401                let end = Point::new(
 6402                    rows.end.previous_row().0,
 6403                    buffer.line_len(rows.end.previous_row()),
 6404                );
 6405                let text = buffer
 6406                    .text_for_range(start..end)
 6407                    .chain(Some("\n"))
 6408                    .collect::<String>();
 6409                let insert_location = if upwards {
 6410                    Point::new(rows.end.0, 0)
 6411                } else {
 6412                    start
 6413                };
 6414                edits.push((insert_location..insert_location, text));
 6415            } else {
 6416                // duplicate character-wise
 6417                let start = selection.start;
 6418                let end = selection.end;
 6419                let text = buffer.text_for_range(start..end).collect::<String>();
 6420                edits.push((selection.end..selection.end, text));
 6421            }
 6422        }
 6423
 6424        self.transact(cx, |this, cx| {
 6425            this.buffer.update(cx, |buffer, cx| {
 6426                buffer.edit(edits, None, cx);
 6427            });
 6428
 6429            this.request_autoscroll(Autoscroll::fit(), cx);
 6430        });
 6431    }
 6432
 6433    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6434        self.duplicate(true, true, cx);
 6435    }
 6436
 6437    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6438        self.duplicate(false, true, cx);
 6439    }
 6440
 6441    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6442        self.duplicate(false, false, cx);
 6443    }
 6444
 6445    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6447        let buffer = self.buffer.read(cx).snapshot(cx);
 6448
 6449        let mut edits = Vec::new();
 6450        let mut unfold_ranges = Vec::new();
 6451        let mut refold_creases = Vec::new();
 6452
 6453        let selections = self.selections.all::<Point>(cx);
 6454        let mut selections = selections.iter().peekable();
 6455        let mut contiguous_row_selections = Vec::new();
 6456        let mut new_selections = Vec::new();
 6457
 6458        while let Some(selection) = selections.next() {
 6459            // Find all the selections that span a contiguous row range
 6460            let (start_row, end_row) = consume_contiguous_rows(
 6461                &mut contiguous_row_selections,
 6462                selection,
 6463                &display_map,
 6464                &mut selections,
 6465            );
 6466
 6467            // Move the text spanned by the row range to be before the line preceding the row range
 6468            if start_row.0 > 0 {
 6469                let range_to_move = Point::new(
 6470                    start_row.previous_row().0,
 6471                    buffer.line_len(start_row.previous_row()),
 6472                )
 6473                    ..Point::new(
 6474                        end_row.previous_row().0,
 6475                        buffer.line_len(end_row.previous_row()),
 6476                    );
 6477                let insertion_point = display_map
 6478                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6479                    .0;
 6480
 6481                // Don't move lines across excerpts
 6482                if buffer
 6483                    .excerpt_boundaries_in_range((
 6484                        Bound::Excluded(insertion_point),
 6485                        Bound::Included(range_to_move.end),
 6486                    ))
 6487                    .next()
 6488                    .is_none()
 6489                {
 6490                    let text = buffer
 6491                        .text_for_range(range_to_move.clone())
 6492                        .flat_map(|s| s.chars())
 6493                        .skip(1)
 6494                        .chain(['\n'])
 6495                        .collect::<String>();
 6496
 6497                    edits.push((
 6498                        buffer.anchor_after(range_to_move.start)
 6499                            ..buffer.anchor_before(range_to_move.end),
 6500                        String::new(),
 6501                    ));
 6502                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6503                    edits.push((insertion_anchor..insertion_anchor, text));
 6504
 6505                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6506
 6507                    // Move selections up
 6508                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6509                        |mut selection| {
 6510                            selection.start.row -= row_delta;
 6511                            selection.end.row -= row_delta;
 6512                            selection
 6513                        },
 6514                    ));
 6515
 6516                    // Move folds up
 6517                    unfold_ranges.push(range_to_move.clone());
 6518                    for fold in display_map.folds_in_range(
 6519                        buffer.anchor_before(range_to_move.start)
 6520                            ..buffer.anchor_after(range_to_move.end),
 6521                    ) {
 6522                        let mut start = fold.range.start.to_point(&buffer);
 6523                        let mut end = fold.range.end.to_point(&buffer);
 6524                        start.row -= row_delta;
 6525                        end.row -= row_delta;
 6526                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6527                    }
 6528                }
 6529            }
 6530
 6531            // If we didn't move line(s), preserve the existing selections
 6532            new_selections.append(&mut contiguous_row_selections);
 6533        }
 6534
 6535        self.transact(cx, |this, cx| {
 6536            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6537            this.buffer.update(cx, |buffer, cx| {
 6538                for (range, text) in edits {
 6539                    buffer.edit([(range, text)], None, cx);
 6540                }
 6541            });
 6542            this.fold_creases(refold_creases, true, cx);
 6543            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6544                s.select(new_selections);
 6545            })
 6546        });
 6547    }
 6548
 6549    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6550        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6551        let buffer = self.buffer.read(cx).snapshot(cx);
 6552
 6553        let mut edits = Vec::new();
 6554        let mut unfold_ranges = Vec::new();
 6555        let mut refold_creases = Vec::new();
 6556
 6557        let selections = self.selections.all::<Point>(cx);
 6558        let mut selections = selections.iter().peekable();
 6559        let mut contiguous_row_selections = Vec::new();
 6560        let mut new_selections = Vec::new();
 6561
 6562        while let Some(selection) = selections.next() {
 6563            // Find all the selections that span a contiguous row range
 6564            let (start_row, end_row) = consume_contiguous_rows(
 6565                &mut contiguous_row_selections,
 6566                selection,
 6567                &display_map,
 6568                &mut selections,
 6569            );
 6570
 6571            // Move the text spanned by the row range to be after the last line of the row range
 6572            if end_row.0 <= buffer.max_point().row {
 6573                let range_to_move =
 6574                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6575                let insertion_point = display_map
 6576                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6577                    .0;
 6578
 6579                // Don't move lines across excerpt boundaries
 6580                if buffer
 6581                    .excerpt_boundaries_in_range((
 6582                        Bound::Excluded(range_to_move.start),
 6583                        Bound::Included(insertion_point),
 6584                    ))
 6585                    .next()
 6586                    .is_none()
 6587                {
 6588                    let mut text = String::from("\n");
 6589                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6590                    text.pop(); // Drop trailing newline
 6591                    edits.push((
 6592                        buffer.anchor_after(range_to_move.start)
 6593                            ..buffer.anchor_before(range_to_move.end),
 6594                        String::new(),
 6595                    ));
 6596                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6597                    edits.push((insertion_anchor..insertion_anchor, text));
 6598
 6599                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6600
 6601                    // Move selections down
 6602                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6603                        |mut selection| {
 6604                            selection.start.row += row_delta;
 6605                            selection.end.row += row_delta;
 6606                            selection
 6607                        },
 6608                    ));
 6609
 6610                    // Move folds down
 6611                    unfold_ranges.push(range_to_move.clone());
 6612                    for fold in display_map.folds_in_range(
 6613                        buffer.anchor_before(range_to_move.start)
 6614                            ..buffer.anchor_after(range_to_move.end),
 6615                    ) {
 6616                        let mut start = fold.range.start.to_point(&buffer);
 6617                        let mut end = fold.range.end.to_point(&buffer);
 6618                        start.row += row_delta;
 6619                        end.row += row_delta;
 6620                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6621                    }
 6622                }
 6623            }
 6624
 6625            // If we didn't move line(s), preserve the existing selections
 6626            new_selections.append(&mut contiguous_row_selections);
 6627        }
 6628
 6629        self.transact(cx, |this, cx| {
 6630            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6631            this.buffer.update(cx, |buffer, cx| {
 6632                for (range, text) in edits {
 6633                    buffer.edit([(range, text)], None, cx);
 6634                }
 6635            });
 6636            this.fold_creases(refold_creases, true, cx);
 6637            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6638        });
 6639    }
 6640
 6641    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6642        let text_layout_details = &self.text_layout_details(cx);
 6643        self.transact(cx, |this, cx| {
 6644            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6645                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6646                let line_mode = s.line_mode;
 6647                s.move_with(|display_map, selection| {
 6648                    if !selection.is_empty() || line_mode {
 6649                        return;
 6650                    }
 6651
 6652                    let mut head = selection.head();
 6653                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6654                    if head.column() == display_map.line_len(head.row()) {
 6655                        transpose_offset = display_map
 6656                            .buffer_snapshot
 6657                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6658                    }
 6659
 6660                    if transpose_offset == 0 {
 6661                        return;
 6662                    }
 6663
 6664                    *head.column_mut() += 1;
 6665                    head = display_map.clip_point(head, Bias::Right);
 6666                    let goal = SelectionGoal::HorizontalPosition(
 6667                        display_map
 6668                            .x_for_display_point(head, text_layout_details)
 6669                            .into(),
 6670                    );
 6671                    selection.collapse_to(head, goal);
 6672
 6673                    let transpose_start = display_map
 6674                        .buffer_snapshot
 6675                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6676                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6677                        let transpose_end = display_map
 6678                            .buffer_snapshot
 6679                            .clip_offset(transpose_offset + 1, Bias::Right);
 6680                        if let Some(ch) =
 6681                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6682                        {
 6683                            edits.push((transpose_start..transpose_offset, String::new()));
 6684                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6685                        }
 6686                    }
 6687                });
 6688                edits
 6689            });
 6690            this.buffer
 6691                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6692            let selections = this.selections.all::<usize>(cx);
 6693            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6694                s.select(selections);
 6695            });
 6696        });
 6697    }
 6698
 6699    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6700        self.rewrap_impl(IsVimMode::No, cx)
 6701    }
 6702
 6703    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6704        let buffer = self.buffer.read(cx).snapshot(cx);
 6705        let selections = self.selections.all::<Point>(cx);
 6706        let mut selections = selections.iter().peekable();
 6707
 6708        let mut edits = Vec::new();
 6709        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6710
 6711        while let Some(selection) = selections.next() {
 6712            let mut start_row = selection.start.row;
 6713            let mut end_row = selection.end.row;
 6714
 6715            // Skip selections that overlap with a range that has already been rewrapped.
 6716            let selection_range = start_row..end_row;
 6717            if rewrapped_row_ranges
 6718                .iter()
 6719                .any(|range| range.overlaps(&selection_range))
 6720            {
 6721                continue;
 6722            }
 6723
 6724            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6725
 6726            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6727                match language_scope.language_name().0.as_ref() {
 6728                    "Markdown" | "Plain Text" => {
 6729                        should_rewrap = true;
 6730                    }
 6731                    _ => {}
 6732                }
 6733            }
 6734
 6735            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6736
 6737            // Since not all lines in the selection may be at the same indent
 6738            // level, choose the indent size that is the most common between all
 6739            // of the lines.
 6740            //
 6741            // If there is a tie, we use the deepest indent.
 6742            let (indent_size, indent_end) = {
 6743                let mut indent_size_occurrences = HashMap::default();
 6744                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6745
 6746                for row in start_row..=end_row {
 6747                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6748                    rows_by_indent_size.entry(indent).or_default().push(row);
 6749                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6750                }
 6751
 6752                let indent_size = indent_size_occurrences
 6753                    .into_iter()
 6754                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6755                    .map(|(indent, _)| indent)
 6756                    .unwrap_or_default();
 6757                let row = rows_by_indent_size[&indent_size][0];
 6758                let indent_end = Point::new(row, indent_size.len);
 6759
 6760                (indent_size, indent_end)
 6761            };
 6762
 6763            let mut line_prefix = indent_size.chars().collect::<String>();
 6764
 6765            if let Some(comment_prefix) =
 6766                buffer
 6767                    .language_scope_at(selection.head())
 6768                    .and_then(|language| {
 6769                        language
 6770                            .line_comment_prefixes()
 6771                            .iter()
 6772                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6773                            .cloned()
 6774                    })
 6775            {
 6776                line_prefix.push_str(&comment_prefix);
 6777                should_rewrap = true;
 6778            }
 6779
 6780            if !should_rewrap {
 6781                continue;
 6782            }
 6783
 6784            if selection.is_empty() {
 6785                'expand_upwards: while start_row > 0 {
 6786                    let prev_row = start_row - 1;
 6787                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6788                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6789                    {
 6790                        start_row = prev_row;
 6791                    } else {
 6792                        break 'expand_upwards;
 6793                    }
 6794                }
 6795
 6796                'expand_downwards: while end_row < buffer.max_point().row {
 6797                    let next_row = end_row + 1;
 6798                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6799                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6800                    {
 6801                        end_row = next_row;
 6802                    } else {
 6803                        break 'expand_downwards;
 6804                    }
 6805                }
 6806            }
 6807
 6808            let start = Point::new(start_row, 0);
 6809            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6810            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6811            let Some(lines_without_prefixes) = selection_text
 6812                .lines()
 6813                .map(|line| {
 6814                    line.strip_prefix(&line_prefix)
 6815                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6816                        .ok_or_else(|| {
 6817                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6818                        })
 6819                })
 6820                .collect::<Result<Vec<_>, _>>()
 6821                .log_err()
 6822            else {
 6823                continue;
 6824            };
 6825
 6826            let wrap_column = buffer
 6827                .settings_at(Point::new(start_row, 0), cx)
 6828                .preferred_line_length as usize;
 6829            let wrapped_text = wrap_with_prefix(
 6830                line_prefix,
 6831                lines_without_prefixes.join(" "),
 6832                wrap_column,
 6833                tab_size,
 6834            );
 6835
 6836            // TODO: should always use char-based diff while still supporting cursor behavior that
 6837            // matches vim.
 6838            let diff = match is_vim_mode {
 6839                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6840                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6841            };
 6842            let mut offset = start.to_offset(&buffer);
 6843            let mut moved_since_edit = true;
 6844
 6845            for change in diff.iter_all_changes() {
 6846                let value = change.value();
 6847                match change.tag() {
 6848                    ChangeTag::Equal => {
 6849                        offset += value.len();
 6850                        moved_since_edit = true;
 6851                    }
 6852                    ChangeTag::Delete => {
 6853                        let start = buffer.anchor_after(offset);
 6854                        let end = buffer.anchor_before(offset + value.len());
 6855
 6856                        if moved_since_edit {
 6857                            edits.push((start..end, String::new()));
 6858                        } else {
 6859                            edits.last_mut().unwrap().0.end = end;
 6860                        }
 6861
 6862                        offset += value.len();
 6863                        moved_since_edit = false;
 6864                    }
 6865                    ChangeTag::Insert => {
 6866                        if moved_since_edit {
 6867                            let anchor = buffer.anchor_after(offset);
 6868                            edits.push((anchor..anchor, value.to_string()));
 6869                        } else {
 6870                            edits.last_mut().unwrap().1.push_str(value);
 6871                        }
 6872
 6873                        moved_since_edit = false;
 6874                    }
 6875                }
 6876            }
 6877
 6878            rewrapped_row_ranges.push(start_row..=end_row);
 6879        }
 6880
 6881        self.buffer
 6882            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6883    }
 6884
 6885    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6886        let mut text = String::new();
 6887        let buffer = self.buffer.read(cx).snapshot(cx);
 6888        let mut selections = self.selections.all::<Point>(cx);
 6889        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6890        {
 6891            let max_point = buffer.max_point();
 6892            let mut is_first = true;
 6893            for selection in &mut selections {
 6894                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6895                if is_entire_line {
 6896                    selection.start = Point::new(selection.start.row, 0);
 6897                    if !selection.is_empty() && selection.end.column == 0 {
 6898                        selection.end = cmp::min(max_point, selection.end);
 6899                    } else {
 6900                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6901                    }
 6902                    selection.goal = SelectionGoal::None;
 6903                }
 6904                if is_first {
 6905                    is_first = false;
 6906                } else {
 6907                    text += "\n";
 6908                }
 6909                let mut len = 0;
 6910                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6911                    text.push_str(chunk);
 6912                    len += chunk.len();
 6913                }
 6914                clipboard_selections.push(ClipboardSelection {
 6915                    len,
 6916                    is_entire_line,
 6917                    first_line_indent: buffer
 6918                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6919                        .len,
 6920                });
 6921            }
 6922        }
 6923
 6924        self.transact(cx, |this, cx| {
 6925            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6926                s.select(selections);
 6927            });
 6928            this.insert("", cx);
 6929        });
 6930        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6931    }
 6932
 6933    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6934        let item = self.cut_common(cx);
 6935        cx.write_to_clipboard(item);
 6936    }
 6937
 6938    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6939        self.change_selections(None, cx, |s| {
 6940            s.move_with(|snapshot, sel| {
 6941                if sel.is_empty() {
 6942                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6943                }
 6944            });
 6945        });
 6946        let item = self.cut_common(cx);
 6947        cx.set_global(KillRing(item))
 6948    }
 6949
 6950    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6951        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6952            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6953                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6954            } else {
 6955                return;
 6956            }
 6957        } else {
 6958            return;
 6959        };
 6960        self.do_paste(&text, metadata, false, cx);
 6961    }
 6962
 6963    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6964        let selections = self.selections.all::<Point>(cx);
 6965        let buffer = self.buffer.read(cx).read(cx);
 6966        let mut text = String::new();
 6967
 6968        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6969        {
 6970            let max_point = buffer.max_point();
 6971            let mut is_first = true;
 6972            for selection in selections.iter() {
 6973                let mut start = selection.start;
 6974                let mut end = selection.end;
 6975                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6976                if is_entire_line {
 6977                    start = Point::new(start.row, 0);
 6978                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6979                }
 6980                if is_first {
 6981                    is_first = false;
 6982                } else {
 6983                    text += "\n";
 6984                }
 6985                let mut len = 0;
 6986                for chunk in buffer.text_for_range(start..end) {
 6987                    text.push_str(chunk);
 6988                    len += chunk.len();
 6989                }
 6990                clipboard_selections.push(ClipboardSelection {
 6991                    len,
 6992                    is_entire_line,
 6993                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6994                });
 6995            }
 6996        }
 6997
 6998        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6999            text,
 7000            clipboard_selections,
 7001        ));
 7002    }
 7003
 7004    pub fn do_paste(
 7005        &mut self,
 7006        text: &String,
 7007        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7008        handle_entire_lines: bool,
 7009        cx: &mut ViewContext<Self>,
 7010    ) {
 7011        if self.read_only(cx) {
 7012            return;
 7013        }
 7014
 7015        let clipboard_text = Cow::Borrowed(text);
 7016
 7017        self.transact(cx, |this, cx| {
 7018            if let Some(mut clipboard_selections) = clipboard_selections {
 7019                let old_selections = this.selections.all::<usize>(cx);
 7020                let all_selections_were_entire_line =
 7021                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7022                let first_selection_indent_column =
 7023                    clipboard_selections.first().map(|s| s.first_line_indent);
 7024                if clipboard_selections.len() != old_selections.len() {
 7025                    clipboard_selections.drain(..);
 7026                }
 7027                let cursor_offset = this.selections.last::<usize>(cx).head();
 7028                let mut auto_indent_on_paste = true;
 7029
 7030                this.buffer.update(cx, |buffer, cx| {
 7031                    let snapshot = buffer.read(cx);
 7032                    auto_indent_on_paste =
 7033                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7034
 7035                    let mut start_offset = 0;
 7036                    let mut edits = Vec::new();
 7037                    let mut original_indent_columns = Vec::new();
 7038                    for (ix, selection) in old_selections.iter().enumerate() {
 7039                        let to_insert;
 7040                        let entire_line;
 7041                        let original_indent_column;
 7042                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7043                            let end_offset = start_offset + clipboard_selection.len;
 7044                            to_insert = &clipboard_text[start_offset..end_offset];
 7045                            entire_line = clipboard_selection.is_entire_line;
 7046                            start_offset = end_offset + 1;
 7047                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7048                        } else {
 7049                            to_insert = clipboard_text.as_str();
 7050                            entire_line = all_selections_were_entire_line;
 7051                            original_indent_column = first_selection_indent_column
 7052                        }
 7053
 7054                        // If the corresponding selection was empty when this slice of the
 7055                        // clipboard text was written, then the entire line containing the
 7056                        // selection was copied. If this selection is also currently empty,
 7057                        // then paste the line before the current line of the buffer.
 7058                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7059                            let column = selection.start.to_point(&snapshot).column as usize;
 7060                            let line_start = selection.start - column;
 7061                            line_start..line_start
 7062                        } else {
 7063                            selection.range()
 7064                        };
 7065
 7066                        edits.push((range, to_insert));
 7067                        original_indent_columns.extend(original_indent_column);
 7068                    }
 7069                    drop(snapshot);
 7070
 7071                    buffer.edit(
 7072                        edits,
 7073                        if auto_indent_on_paste {
 7074                            Some(AutoindentMode::Block {
 7075                                original_indent_columns,
 7076                            })
 7077                        } else {
 7078                            None
 7079                        },
 7080                        cx,
 7081                    );
 7082                });
 7083
 7084                let selections = this.selections.all::<usize>(cx);
 7085                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7086            } else {
 7087                this.insert(&clipboard_text, cx);
 7088            }
 7089        });
 7090    }
 7091
 7092    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7093        if let Some(item) = cx.read_from_clipboard() {
 7094            let entries = item.entries();
 7095
 7096            match entries.first() {
 7097                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7098                // of all the pasted entries.
 7099                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7100                    .do_paste(
 7101                        clipboard_string.text(),
 7102                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7103                        true,
 7104                        cx,
 7105                    ),
 7106                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7107            }
 7108        }
 7109    }
 7110
 7111    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7112        if self.read_only(cx) {
 7113            return;
 7114        }
 7115
 7116        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7117            if let Some((selections, _)) =
 7118                self.selection_history.transaction(transaction_id).cloned()
 7119            {
 7120                self.change_selections(None, cx, |s| {
 7121                    s.select_anchors(selections.to_vec());
 7122                });
 7123            }
 7124            self.request_autoscroll(Autoscroll::fit(), cx);
 7125            self.unmark_text(cx);
 7126            self.refresh_inline_completion(true, false, cx);
 7127            cx.emit(EditorEvent::Edited { transaction_id });
 7128            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7129        }
 7130    }
 7131
 7132    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7133        if self.read_only(cx) {
 7134            return;
 7135        }
 7136
 7137        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7138            if let Some((_, Some(selections))) =
 7139                self.selection_history.transaction(transaction_id).cloned()
 7140            {
 7141                self.change_selections(None, cx, |s| {
 7142                    s.select_anchors(selections.to_vec());
 7143                });
 7144            }
 7145            self.request_autoscroll(Autoscroll::fit(), cx);
 7146            self.unmark_text(cx);
 7147            self.refresh_inline_completion(true, false, cx);
 7148            cx.emit(EditorEvent::Edited { transaction_id });
 7149        }
 7150    }
 7151
 7152    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7153        self.buffer
 7154            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7155    }
 7156
 7157    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7158        self.buffer
 7159            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7160    }
 7161
 7162    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7163        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7164            let line_mode = s.line_mode;
 7165            s.move_with(|map, selection| {
 7166                let cursor = if selection.is_empty() && !line_mode {
 7167                    movement::left(map, selection.start)
 7168                } else {
 7169                    selection.start
 7170                };
 7171                selection.collapse_to(cursor, SelectionGoal::None);
 7172            });
 7173        })
 7174    }
 7175
 7176    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7177        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7178            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7179        })
 7180    }
 7181
 7182    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7183        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7184            let line_mode = s.line_mode;
 7185            s.move_with(|map, selection| {
 7186                let cursor = if selection.is_empty() && !line_mode {
 7187                    movement::right(map, selection.end)
 7188                } else {
 7189                    selection.end
 7190                };
 7191                selection.collapse_to(cursor, SelectionGoal::None)
 7192            });
 7193        })
 7194    }
 7195
 7196    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7197        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7198            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7199        })
 7200    }
 7201
 7202    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7203        if self.take_rename(true, cx).is_some() {
 7204            return;
 7205        }
 7206
 7207        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7208            cx.propagate();
 7209            return;
 7210        }
 7211
 7212        let text_layout_details = &self.text_layout_details(cx);
 7213        let selection_count = self.selections.count();
 7214        let first_selection = self.selections.first_anchor();
 7215
 7216        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7217            let line_mode = s.line_mode;
 7218            s.move_with(|map, selection| {
 7219                if !selection.is_empty() && !line_mode {
 7220                    selection.goal = SelectionGoal::None;
 7221                }
 7222                let (cursor, goal) = movement::up(
 7223                    map,
 7224                    selection.start,
 7225                    selection.goal,
 7226                    false,
 7227                    text_layout_details,
 7228                );
 7229                selection.collapse_to(cursor, goal);
 7230            });
 7231        });
 7232
 7233        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7234        {
 7235            cx.propagate();
 7236        }
 7237    }
 7238
 7239    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7240        if self.take_rename(true, cx).is_some() {
 7241            return;
 7242        }
 7243
 7244        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7245            cx.propagate();
 7246            return;
 7247        }
 7248
 7249        let text_layout_details = &self.text_layout_details(cx);
 7250
 7251        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7252            let line_mode = s.line_mode;
 7253            s.move_with(|map, selection| {
 7254                if !selection.is_empty() && !line_mode {
 7255                    selection.goal = SelectionGoal::None;
 7256                }
 7257                let (cursor, goal) = movement::up_by_rows(
 7258                    map,
 7259                    selection.start,
 7260                    action.lines,
 7261                    selection.goal,
 7262                    false,
 7263                    text_layout_details,
 7264                );
 7265                selection.collapse_to(cursor, goal);
 7266            });
 7267        })
 7268    }
 7269
 7270    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7271        if self.take_rename(true, cx).is_some() {
 7272            return;
 7273        }
 7274
 7275        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7276            cx.propagate();
 7277            return;
 7278        }
 7279
 7280        let text_layout_details = &self.text_layout_details(cx);
 7281
 7282        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7283            let line_mode = s.line_mode;
 7284            s.move_with(|map, selection| {
 7285                if !selection.is_empty() && !line_mode {
 7286                    selection.goal = SelectionGoal::None;
 7287                }
 7288                let (cursor, goal) = movement::down_by_rows(
 7289                    map,
 7290                    selection.start,
 7291                    action.lines,
 7292                    selection.goal,
 7293                    false,
 7294                    text_layout_details,
 7295                );
 7296                selection.collapse_to(cursor, goal);
 7297            });
 7298        })
 7299    }
 7300
 7301    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7302        let text_layout_details = &self.text_layout_details(cx);
 7303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304            s.move_heads_with(|map, head, goal| {
 7305                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7306            })
 7307        })
 7308    }
 7309
 7310    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7311        let text_layout_details = &self.text_layout_details(cx);
 7312        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7313            s.move_heads_with(|map, head, goal| {
 7314                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7315            })
 7316        })
 7317    }
 7318
 7319    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7320        let Some(row_count) = self.visible_row_count() else {
 7321            return;
 7322        };
 7323
 7324        let text_layout_details = &self.text_layout_details(cx);
 7325
 7326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327            s.move_heads_with(|map, head, goal| {
 7328                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7329            })
 7330        })
 7331    }
 7332
 7333    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7334        if self.take_rename(true, cx).is_some() {
 7335            return;
 7336        }
 7337
 7338        if self
 7339            .context_menu
 7340            .borrow_mut()
 7341            .as_mut()
 7342            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7343            .unwrap_or(false)
 7344        {
 7345            return;
 7346        }
 7347
 7348        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7349            cx.propagate();
 7350            return;
 7351        }
 7352
 7353        let Some(row_count) = self.visible_row_count() else {
 7354            return;
 7355        };
 7356
 7357        let autoscroll = if action.center_cursor {
 7358            Autoscroll::center()
 7359        } else {
 7360            Autoscroll::fit()
 7361        };
 7362
 7363        let text_layout_details = &self.text_layout_details(cx);
 7364
 7365        self.change_selections(Some(autoscroll), cx, |s| {
 7366            let line_mode = s.line_mode;
 7367            s.move_with(|map, selection| {
 7368                if !selection.is_empty() && !line_mode {
 7369                    selection.goal = SelectionGoal::None;
 7370                }
 7371                let (cursor, goal) = movement::up_by_rows(
 7372                    map,
 7373                    selection.end,
 7374                    row_count,
 7375                    selection.goal,
 7376                    false,
 7377                    text_layout_details,
 7378                );
 7379                selection.collapse_to(cursor, goal);
 7380            });
 7381        });
 7382    }
 7383
 7384    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7385        let text_layout_details = &self.text_layout_details(cx);
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            s.move_heads_with(|map, head, goal| {
 7388                movement::up(map, head, goal, false, text_layout_details)
 7389            })
 7390        })
 7391    }
 7392
 7393    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7394        self.take_rename(true, cx);
 7395
 7396        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7397            cx.propagate();
 7398            return;
 7399        }
 7400
 7401        let text_layout_details = &self.text_layout_details(cx);
 7402        let selection_count = self.selections.count();
 7403        let first_selection = self.selections.first_anchor();
 7404
 7405        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7406            let line_mode = s.line_mode;
 7407            s.move_with(|map, selection| {
 7408                if !selection.is_empty() && !line_mode {
 7409                    selection.goal = SelectionGoal::None;
 7410                }
 7411                let (cursor, goal) = movement::down(
 7412                    map,
 7413                    selection.end,
 7414                    selection.goal,
 7415                    false,
 7416                    text_layout_details,
 7417                );
 7418                selection.collapse_to(cursor, goal);
 7419            });
 7420        });
 7421
 7422        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7423        {
 7424            cx.propagate();
 7425        }
 7426    }
 7427
 7428    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7429        let Some(row_count) = self.visible_row_count() else {
 7430            return;
 7431        };
 7432
 7433        let text_layout_details = &self.text_layout_details(cx);
 7434
 7435        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436            s.move_heads_with(|map, head, goal| {
 7437                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7438            })
 7439        })
 7440    }
 7441
 7442    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7443        if self.take_rename(true, cx).is_some() {
 7444            return;
 7445        }
 7446
 7447        if self
 7448            .context_menu
 7449            .borrow_mut()
 7450            .as_mut()
 7451            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7452            .unwrap_or(false)
 7453        {
 7454            return;
 7455        }
 7456
 7457        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7458            cx.propagate();
 7459            return;
 7460        }
 7461
 7462        let Some(row_count) = self.visible_row_count() else {
 7463            return;
 7464        };
 7465
 7466        let autoscroll = if action.center_cursor {
 7467            Autoscroll::center()
 7468        } else {
 7469            Autoscroll::fit()
 7470        };
 7471
 7472        let text_layout_details = &self.text_layout_details(cx);
 7473        self.change_selections(Some(autoscroll), cx, |s| {
 7474            let line_mode = s.line_mode;
 7475            s.move_with(|map, selection| {
 7476                if !selection.is_empty() && !line_mode {
 7477                    selection.goal = SelectionGoal::None;
 7478                }
 7479                let (cursor, goal) = movement::down_by_rows(
 7480                    map,
 7481                    selection.end,
 7482                    row_count,
 7483                    selection.goal,
 7484                    false,
 7485                    text_layout_details,
 7486                );
 7487                selection.collapse_to(cursor, goal);
 7488            });
 7489        });
 7490    }
 7491
 7492    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7493        let text_layout_details = &self.text_layout_details(cx);
 7494        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7495            s.move_heads_with(|map, head, goal| {
 7496                movement::down(map, head, goal, false, text_layout_details)
 7497            })
 7498        });
 7499    }
 7500
 7501    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7502        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7503            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7504        }
 7505    }
 7506
 7507    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7508        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7509            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7510        }
 7511    }
 7512
 7513    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7514        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7515            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7516        }
 7517    }
 7518
 7519    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7520        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7521            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7522        }
 7523    }
 7524
 7525    pub fn move_to_previous_word_start(
 7526        &mut self,
 7527        _: &MoveToPreviousWordStart,
 7528        cx: &mut ViewContext<Self>,
 7529    ) {
 7530        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7531            s.move_cursors_with(|map, head, _| {
 7532                (
 7533                    movement::previous_word_start(map, head),
 7534                    SelectionGoal::None,
 7535                )
 7536            });
 7537        })
 7538    }
 7539
 7540    pub fn move_to_previous_subword_start(
 7541        &mut self,
 7542        _: &MoveToPreviousSubwordStart,
 7543        cx: &mut ViewContext<Self>,
 7544    ) {
 7545        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7546            s.move_cursors_with(|map, head, _| {
 7547                (
 7548                    movement::previous_subword_start(map, head),
 7549                    SelectionGoal::None,
 7550                )
 7551            });
 7552        })
 7553    }
 7554
 7555    pub fn select_to_previous_word_start(
 7556        &mut self,
 7557        _: &SelectToPreviousWordStart,
 7558        cx: &mut ViewContext<Self>,
 7559    ) {
 7560        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7561            s.move_heads_with(|map, head, _| {
 7562                (
 7563                    movement::previous_word_start(map, head),
 7564                    SelectionGoal::None,
 7565                )
 7566            });
 7567        })
 7568    }
 7569
 7570    pub fn select_to_previous_subword_start(
 7571        &mut self,
 7572        _: &SelectToPreviousSubwordStart,
 7573        cx: &mut ViewContext<Self>,
 7574    ) {
 7575        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7576            s.move_heads_with(|map, head, _| {
 7577                (
 7578                    movement::previous_subword_start(map, head),
 7579                    SelectionGoal::None,
 7580                )
 7581            });
 7582        })
 7583    }
 7584
 7585    pub fn delete_to_previous_word_start(
 7586        &mut self,
 7587        action: &DeleteToPreviousWordStart,
 7588        cx: &mut ViewContext<Self>,
 7589    ) {
 7590        self.transact(cx, |this, cx| {
 7591            this.select_autoclose_pair(cx);
 7592            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7593                let line_mode = s.line_mode;
 7594                s.move_with(|map, selection| {
 7595                    if selection.is_empty() && !line_mode {
 7596                        let cursor = if action.ignore_newlines {
 7597                            movement::previous_word_start(map, selection.head())
 7598                        } else {
 7599                            movement::previous_word_start_or_newline(map, selection.head())
 7600                        };
 7601                        selection.set_head(cursor, SelectionGoal::None);
 7602                    }
 7603                });
 7604            });
 7605            this.insert("", cx);
 7606        });
 7607    }
 7608
 7609    pub fn delete_to_previous_subword_start(
 7610        &mut self,
 7611        _: &DeleteToPreviousSubwordStart,
 7612        cx: &mut ViewContext<Self>,
 7613    ) {
 7614        self.transact(cx, |this, cx| {
 7615            this.select_autoclose_pair(cx);
 7616            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617                let line_mode = s.line_mode;
 7618                s.move_with(|map, selection| {
 7619                    if selection.is_empty() && !line_mode {
 7620                        let cursor = movement::previous_subword_start(map, selection.head());
 7621                        selection.set_head(cursor, SelectionGoal::None);
 7622                    }
 7623                });
 7624            });
 7625            this.insert("", cx);
 7626        });
 7627    }
 7628
 7629    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7630        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7631            s.move_cursors_with(|map, head, _| {
 7632                (movement::next_word_end(map, head), SelectionGoal::None)
 7633            });
 7634        })
 7635    }
 7636
 7637    pub fn move_to_next_subword_end(
 7638        &mut self,
 7639        _: &MoveToNextSubwordEnd,
 7640        cx: &mut ViewContext<Self>,
 7641    ) {
 7642        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7643            s.move_cursors_with(|map, head, _| {
 7644                (movement::next_subword_end(map, head), SelectionGoal::None)
 7645            });
 7646        })
 7647    }
 7648
 7649    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7651            s.move_heads_with(|map, head, _| {
 7652                (movement::next_word_end(map, head), SelectionGoal::None)
 7653            });
 7654        })
 7655    }
 7656
 7657    pub fn select_to_next_subword_end(
 7658        &mut self,
 7659        _: &SelectToNextSubwordEnd,
 7660        cx: &mut ViewContext<Self>,
 7661    ) {
 7662        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7663            s.move_heads_with(|map, head, _| {
 7664                (movement::next_subword_end(map, head), SelectionGoal::None)
 7665            });
 7666        })
 7667    }
 7668
 7669    pub fn delete_to_next_word_end(
 7670        &mut self,
 7671        action: &DeleteToNextWordEnd,
 7672        cx: &mut ViewContext<Self>,
 7673    ) {
 7674        self.transact(cx, |this, cx| {
 7675            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7676                let line_mode = s.line_mode;
 7677                s.move_with(|map, selection| {
 7678                    if selection.is_empty() && !line_mode {
 7679                        let cursor = if action.ignore_newlines {
 7680                            movement::next_word_end(map, selection.head())
 7681                        } else {
 7682                            movement::next_word_end_or_newline(map, selection.head())
 7683                        };
 7684                        selection.set_head(cursor, SelectionGoal::None);
 7685                    }
 7686                });
 7687            });
 7688            this.insert("", cx);
 7689        });
 7690    }
 7691
 7692    pub fn delete_to_next_subword_end(
 7693        &mut self,
 7694        _: &DeleteToNextSubwordEnd,
 7695        cx: &mut ViewContext<Self>,
 7696    ) {
 7697        self.transact(cx, |this, cx| {
 7698            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7699                s.move_with(|map, selection| {
 7700                    if selection.is_empty() {
 7701                        let cursor = movement::next_subword_end(map, selection.head());
 7702                        selection.set_head(cursor, SelectionGoal::None);
 7703                    }
 7704                });
 7705            });
 7706            this.insert("", cx);
 7707        });
 7708    }
 7709
 7710    pub fn move_to_beginning_of_line(
 7711        &mut self,
 7712        action: &MoveToBeginningOfLine,
 7713        cx: &mut ViewContext<Self>,
 7714    ) {
 7715        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7716            s.move_cursors_with(|map, head, _| {
 7717                (
 7718                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7719                    SelectionGoal::None,
 7720                )
 7721            });
 7722        })
 7723    }
 7724
 7725    pub fn select_to_beginning_of_line(
 7726        &mut self,
 7727        action: &SelectToBeginningOfLine,
 7728        cx: &mut ViewContext<Self>,
 7729    ) {
 7730        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7731            s.move_heads_with(|map, head, _| {
 7732                (
 7733                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7734                    SelectionGoal::None,
 7735                )
 7736            });
 7737        });
 7738    }
 7739
 7740    pub fn delete_to_beginning_of_line(
 7741        &mut self,
 7742        _: &DeleteToBeginningOfLine,
 7743        cx: &mut ViewContext<Self>,
 7744    ) {
 7745        self.transact(cx, |this, cx| {
 7746            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7747                s.move_with(|_, selection| {
 7748                    selection.reversed = true;
 7749                });
 7750            });
 7751
 7752            this.select_to_beginning_of_line(
 7753                &SelectToBeginningOfLine {
 7754                    stop_at_soft_wraps: false,
 7755                },
 7756                cx,
 7757            );
 7758            this.backspace(&Backspace, cx);
 7759        });
 7760    }
 7761
 7762    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7763        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7764            s.move_cursors_with(|map, head, _| {
 7765                (
 7766                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7767                    SelectionGoal::None,
 7768                )
 7769            });
 7770        })
 7771    }
 7772
 7773    pub fn select_to_end_of_line(
 7774        &mut self,
 7775        action: &SelectToEndOfLine,
 7776        cx: &mut ViewContext<Self>,
 7777    ) {
 7778        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7779            s.move_heads_with(|map, head, _| {
 7780                (
 7781                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7782                    SelectionGoal::None,
 7783                )
 7784            });
 7785        })
 7786    }
 7787
 7788    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7789        self.transact(cx, |this, cx| {
 7790            this.select_to_end_of_line(
 7791                &SelectToEndOfLine {
 7792                    stop_at_soft_wraps: false,
 7793                },
 7794                cx,
 7795            );
 7796            this.delete(&Delete, cx);
 7797        });
 7798    }
 7799
 7800    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7801        self.transact(cx, |this, cx| {
 7802            this.select_to_end_of_line(
 7803                &SelectToEndOfLine {
 7804                    stop_at_soft_wraps: false,
 7805                },
 7806                cx,
 7807            );
 7808            this.cut(&Cut, cx);
 7809        });
 7810    }
 7811
 7812    pub fn move_to_start_of_paragraph(
 7813        &mut self,
 7814        _: &MoveToStartOfParagraph,
 7815        cx: &mut ViewContext<Self>,
 7816    ) {
 7817        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7818            cx.propagate();
 7819            return;
 7820        }
 7821
 7822        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7823            s.move_with(|map, selection| {
 7824                selection.collapse_to(
 7825                    movement::start_of_paragraph(map, selection.head(), 1),
 7826                    SelectionGoal::None,
 7827                )
 7828            });
 7829        })
 7830    }
 7831
 7832    pub fn move_to_end_of_paragraph(
 7833        &mut self,
 7834        _: &MoveToEndOfParagraph,
 7835        cx: &mut ViewContext<Self>,
 7836    ) {
 7837        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7838            cx.propagate();
 7839            return;
 7840        }
 7841
 7842        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7843            s.move_with(|map, selection| {
 7844                selection.collapse_to(
 7845                    movement::end_of_paragraph(map, selection.head(), 1),
 7846                    SelectionGoal::None,
 7847                )
 7848            });
 7849        })
 7850    }
 7851
 7852    pub fn select_to_start_of_paragraph(
 7853        &mut self,
 7854        _: &SelectToStartOfParagraph,
 7855        cx: &mut ViewContext<Self>,
 7856    ) {
 7857        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7858            cx.propagate();
 7859            return;
 7860        }
 7861
 7862        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7863            s.move_heads_with(|map, head, _| {
 7864                (
 7865                    movement::start_of_paragraph(map, head, 1),
 7866                    SelectionGoal::None,
 7867                )
 7868            });
 7869        })
 7870    }
 7871
 7872    pub fn select_to_end_of_paragraph(
 7873        &mut self,
 7874        _: &SelectToEndOfParagraph,
 7875        cx: &mut ViewContext<Self>,
 7876    ) {
 7877        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7878            cx.propagate();
 7879            return;
 7880        }
 7881
 7882        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7883            s.move_heads_with(|map, head, _| {
 7884                (
 7885                    movement::end_of_paragraph(map, head, 1),
 7886                    SelectionGoal::None,
 7887                )
 7888            });
 7889        })
 7890    }
 7891
 7892    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7893        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7894            cx.propagate();
 7895            return;
 7896        }
 7897
 7898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7899            s.select_ranges(vec![0..0]);
 7900        });
 7901    }
 7902
 7903    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7904        let mut selection = self.selections.last::<Point>(cx);
 7905        selection.set_head(Point::zero(), SelectionGoal::None);
 7906
 7907        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7908            s.select(vec![selection]);
 7909        });
 7910    }
 7911
 7912    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7913        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7914            cx.propagate();
 7915            return;
 7916        }
 7917
 7918        let cursor = self.buffer.read(cx).read(cx).len();
 7919        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7920            s.select_ranges(vec![cursor..cursor])
 7921        });
 7922    }
 7923
 7924    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7925        self.nav_history = nav_history;
 7926    }
 7927
 7928    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7929        self.nav_history.as_ref()
 7930    }
 7931
 7932    fn push_to_nav_history(
 7933        &mut self,
 7934        cursor_anchor: Anchor,
 7935        new_position: Option<Point>,
 7936        cx: &mut ViewContext<Self>,
 7937    ) {
 7938        if let Some(nav_history) = self.nav_history.as_mut() {
 7939            let buffer = self.buffer.read(cx).read(cx);
 7940            let cursor_position = cursor_anchor.to_point(&buffer);
 7941            let scroll_state = self.scroll_manager.anchor();
 7942            let scroll_top_row = scroll_state.top_row(&buffer);
 7943            drop(buffer);
 7944
 7945            if let Some(new_position) = new_position {
 7946                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7947                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7948                    return;
 7949                }
 7950            }
 7951
 7952            nav_history.push(
 7953                Some(NavigationData {
 7954                    cursor_anchor,
 7955                    cursor_position,
 7956                    scroll_anchor: scroll_state,
 7957                    scroll_top_row,
 7958                }),
 7959                cx,
 7960            );
 7961        }
 7962    }
 7963
 7964    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7965        let buffer = self.buffer.read(cx).snapshot(cx);
 7966        let mut selection = self.selections.first::<usize>(cx);
 7967        selection.set_head(buffer.len(), SelectionGoal::None);
 7968        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7969            s.select(vec![selection]);
 7970        });
 7971    }
 7972
 7973    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7974        let end = self.buffer.read(cx).read(cx).len();
 7975        self.change_selections(None, cx, |s| {
 7976            s.select_ranges(vec![0..end]);
 7977        });
 7978    }
 7979
 7980    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7982        let mut selections = self.selections.all::<Point>(cx);
 7983        let max_point = display_map.buffer_snapshot.max_point();
 7984        for selection in &mut selections {
 7985            let rows = selection.spanned_rows(true, &display_map);
 7986            selection.start = Point::new(rows.start.0, 0);
 7987            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7988            selection.reversed = false;
 7989        }
 7990        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7991            s.select(selections);
 7992        });
 7993    }
 7994
 7995    pub fn split_selection_into_lines(
 7996        &mut self,
 7997        _: &SplitSelectionIntoLines,
 7998        cx: &mut ViewContext<Self>,
 7999    ) {
 8000        let mut to_unfold = Vec::new();
 8001        let mut new_selection_ranges = Vec::new();
 8002        {
 8003            let selections = self.selections.all::<Point>(cx);
 8004            let buffer = self.buffer.read(cx).read(cx);
 8005            for selection in selections {
 8006                for row in selection.start.row..selection.end.row {
 8007                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8008                    new_selection_ranges.push(cursor..cursor);
 8009                }
 8010                new_selection_ranges.push(selection.end..selection.end);
 8011                to_unfold.push(selection.start..selection.end);
 8012            }
 8013        }
 8014        self.unfold_ranges(&to_unfold, true, true, cx);
 8015        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8016            s.select_ranges(new_selection_ranges);
 8017        });
 8018    }
 8019
 8020    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8021        self.add_selection(true, cx);
 8022    }
 8023
 8024    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8025        self.add_selection(false, cx);
 8026    }
 8027
 8028    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8030        let mut selections = self.selections.all::<Point>(cx);
 8031        let text_layout_details = self.text_layout_details(cx);
 8032        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8033            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8034            let range = oldest_selection.display_range(&display_map).sorted();
 8035
 8036            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8037            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8038            let positions = start_x.min(end_x)..start_x.max(end_x);
 8039
 8040            selections.clear();
 8041            let mut stack = Vec::new();
 8042            for row in range.start.row().0..=range.end.row().0 {
 8043                if let Some(selection) = self.selections.build_columnar_selection(
 8044                    &display_map,
 8045                    DisplayRow(row),
 8046                    &positions,
 8047                    oldest_selection.reversed,
 8048                    &text_layout_details,
 8049                ) {
 8050                    stack.push(selection.id);
 8051                    selections.push(selection);
 8052                }
 8053            }
 8054
 8055            if above {
 8056                stack.reverse();
 8057            }
 8058
 8059            AddSelectionsState { above, stack }
 8060        });
 8061
 8062        let last_added_selection = *state.stack.last().unwrap();
 8063        let mut new_selections = Vec::new();
 8064        if above == state.above {
 8065            let end_row = if above {
 8066                DisplayRow(0)
 8067            } else {
 8068                display_map.max_point().row()
 8069            };
 8070
 8071            'outer: for selection in selections {
 8072                if selection.id == last_added_selection {
 8073                    let range = selection.display_range(&display_map).sorted();
 8074                    debug_assert_eq!(range.start.row(), range.end.row());
 8075                    let mut row = range.start.row();
 8076                    let positions =
 8077                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8078                            px(start)..px(end)
 8079                        } else {
 8080                            let start_x =
 8081                                display_map.x_for_display_point(range.start, &text_layout_details);
 8082                            let end_x =
 8083                                display_map.x_for_display_point(range.end, &text_layout_details);
 8084                            start_x.min(end_x)..start_x.max(end_x)
 8085                        };
 8086
 8087                    while row != end_row {
 8088                        if above {
 8089                            row.0 -= 1;
 8090                        } else {
 8091                            row.0 += 1;
 8092                        }
 8093
 8094                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8095                            &display_map,
 8096                            row,
 8097                            &positions,
 8098                            selection.reversed,
 8099                            &text_layout_details,
 8100                        ) {
 8101                            state.stack.push(new_selection.id);
 8102                            if above {
 8103                                new_selections.push(new_selection);
 8104                                new_selections.push(selection);
 8105                            } else {
 8106                                new_selections.push(selection);
 8107                                new_selections.push(new_selection);
 8108                            }
 8109
 8110                            continue 'outer;
 8111                        }
 8112                    }
 8113                }
 8114
 8115                new_selections.push(selection);
 8116            }
 8117        } else {
 8118            new_selections = selections;
 8119            new_selections.retain(|s| s.id != last_added_selection);
 8120            state.stack.pop();
 8121        }
 8122
 8123        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8124            s.select(new_selections);
 8125        });
 8126        if state.stack.len() > 1 {
 8127            self.add_selections_state = Some(state);
 8128        }
 8129    }
 8130
 8131    pub fn select_next_match_internal(
 8132        &mut self,
 8133        display_map: &DisplaySnapshot,
 8134        replace_newest: bool,
 8135        autoscroll: Option<Autoscroll>,
 8136        cx: &mut ViewContext<Self>,
 8137    ) -> Result<()> {
 8138        fn select_next_match_ranges(
 8139            this: &mut Editor,
 8140            range: Range<usize>,
 8141            replace_newest: bool,
 8142            auto_scroll: Option<Autoscroll>,
 8143            cx: &mut ViewContext<Editor>,
 8144        ) {
 8145            this.unfold_ranges(&[range.clone()], false, true, cx);
 8146            this.change_selections(auto_scroll, cx, |s| {
 8147                if replace_newest {
 8148                    s.delete(s.newest_anchor().id);
 8149                }
 8150                s.insert_range(range.clone());
 8151            });
 8152        }
 8153
 8154        let buffer = &display_map.buffer_snapshot;
 8155        let mut selections = self.selections.all::<usize>(cx);
 8156        if let Some(mut select_next_state) = self.select_next_state.take() {
 8157            let query = &select_next_state.query;
 8158            if !select_next_state.done {
 8159                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8160                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8161                let mut next_selected_range = None;
 8162
 8163                let bytes_after_last_selection =
 8164                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8165                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8166                let query_matches = query
 8167                    .stream_find_iter(bytes_after_last_selection)
 8168                    .map(|result| (last_selection.end, result))
 8169                    .chain(
 8170                        query
 8171                            .stream_find_iter(bytes_before_first_selection)
 8172                            .map(|result| (0, result)),
 8173                    );
 8174
 8175                for (start_offset, query_match) in query_matches {
 8176                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8177                    let offset_range =
 8178                        start_offset + query_match.start()..start_offset + query_match.end();
 8179                    let display_range = offset_range.start.to_display_point(display_map)
 8180                        ..offset_range.end.to_display_point(display_map);
 8181
 8182                    if !select_next_state.wordwise
 8183                        || (!movement::is_inside_word(display_map, display_range.start)
 8184                            && !movement::is_inside_word(display_map, display_range.end))
 8185                    {
 8186                        // TODO: This is n^2, because we might check all the selections
 8187                        if !selections
 8188                            .iter()
 8189                            .any(|selection| selection.range().overlaps(&offset_range))
 8190                        {
 8191                            next_selected_range = Some(offset_range);
 8192                            break;
 8193                        }
 8194                    }
 8195                }
 8196
 8197                if let Some(next_selected_range) = next_selected_range {
 8198                    select_next_match_ranges(
 8199                        self,
 8200                        next_selected_range,
 8201                        replace_newest,
 8202                        autoscroll,
 8203                        cx,
 8204                    );
 8205                } else {
 8206                    select_next_state.done = true;
 8207                }
 8208            }
 8209
 8210            self.select_next_state = Some(select_next_state);
 8211        } else {
 8212            let mut only_carets = true;
 8213            let mut same_text_selected = true;
 8214            let mut selected_text = None;
 8215
 8216            let mut selections_iter = selections.iter().peekable();
 8217            while let Some(selection) = selections_iter.next() {
 8218                if selection.start != selection.end {
 8219                    only_carets = false;
 8220                }
 8221
 8222                if same_text_selected {
 8223                    if selected_text.is_none() {
 8224                        selected_text =
 8225                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8226                    }
 8227
 8228                    if let Some(next_selection) = selections_iter.peek() {
 8229                        if next_selection.range().len() == selection.range().len() {
 8230                            let next_selected_text = buffer
 8231                                .text_for_range(next_selection.range())
 8232                                .collect::<String>();
 8233                            if Some(next_selected_text) != selected_text {
 8234                                same_text_selected = false;
 8235                                selected_text = None;
 8236                            }
 8237                        } else {
 8238                            same_text_selected = false;
 8239                            selected_text = None;
 8240                        }
 8241                    }
 8242                }
 8243            }
 8244
 8245            if only_carets {
 8246                for selection in &mut selections {
 8247                    let word_range = movement::surrounding_word(
 8248                        display_map,
 8249                        selection.start.to_display_point(display_map),
 8250                    );
 8251                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8252                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8253                    selection.goal = SelectionGoal::None;
 8254                    selection.reversed = false;
 8255                    select_next_match_ranges(
 8256                        self,
 8257                        selection.start..selection.end,
 8258                        replace_newest,
 8259                        autoscroll,
 8260                        cx,
 8261                    );
 8262                }
 8263
 8264                if selections.len() == 1 {
 8265                    let selection = selections
 8266                        .last()
 8267                        .expect("ensured that there's only one selection");
 8268                    let query = buffer
 8269                        .text_for_range(selection.start..selection.end)
 8270                        .collect::<String>();
 8271                    let is_empty = query.is_empty();
 8272                    let select_state = SelectNextState {
 8273                        query: AhoCorasick::new(&[query])?,
 8274                        wordwise: true,
 8275                        done: is_empty,
 8276                    };
 8277                    self.select_next_state = Some(select_state);
 8278                } else {
 8279                    self.select_next_state = None;
 8280                }
 8281            } else if let Some(selected_text) = selected_text {
 8282                self.select_next_state = Some(SelectNextState {
 8283                    query: AhoCorasick::new(&[selected_text])?,
 8284                    wordwise: false,
 8285                    done: false,
 8286                });
 8287                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8288            }
 8289        }
 8290        Ok(())
 8291    }
 8292
 8293    pub fn select_all_matches(
 8294        &mut self,
 8295        _action: &SelectAllMatches,
 8296        cx: &mut ViewContext<Self>,
 8297    ) -> Result<()> {
 8298        self.push_to_selection_history();
 8299        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8300
 8301        self.select_next_match_internal(&display_map, false, None, cx)?;
 8302        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8303            return Ok(());
 8304        };
 8305        if select_next_state.done {
 8306            return Ok(());
 8307        }
 8308
 8309        let mut new_selections = self.selections.all::<usize>(cx);
 8310
 8311        let buffer = &display_map.buffer_snapshot;
 8312        let query_matches = select_next_state
 8313            .query
 8314            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8315
 8316        for query_match in query_matches {
 8317            let query_match = query_match.unwrap(); // can only fail due to I/O
 8318            let offset_range = query_match.start()..query_match.end();
 8319            let display_range = offset_range.start.to_display_point(&display_map)
 8320                ..offset_range.end.to_display_point(&display_map);
 8321
 8322            if !select_next_state.wordwise
 8323                || (!movement::is_inside_word(&display_map, display_range.start)
 8324                    && !movement::is_inside_word(&display_map, display_range.end))
 8325            {
 8326                self.selections.change_with(cx, |selections| {
 8327                    new_selections.push(Selection {
 8328                        id: selections.new_selection_id(),
 8329                        start: offset_range.start,
 8330                        end: offset_range.end,
 8331                        reversed: false,
 8332                        goal: SelectionGoal::None,
 8333                    });
 8334                });
 8335            }
 8336        }
 8337
 8338        new_selections.sort_by_key(|selection| selection.start);
 8339        let mut ix = 0;
 8340        while ix + 1 < new_selections.len() {
 8341            let current_selection = &new_selections[ix];
 8342            let next_selection = &new_selections[ix + 1];
 8343            if current_selection.range().overlaps(&next_selection.range()) {
 8344                if current_selection.id < next_selection.id {
 8345                    new_selections.remove(ix + 1);
 8346                } else {
 8347                    new_selections.remove(ix);
 8348                }
 8349            } else {
 8350                ix += 1;
 8351            }
 8352        }
 8353
 8354        select_next_state.done = true;
 8355        self.unfold_ranges(
 8356            &new_selections
 8357                .iter()
 8358                .map(|selection| selection.range())
 8359                .collect::<Vec<_>>(),
 8360            false,
 8361            false,
 8362            cx,
 8363        );
 8364        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8365            selections.select(new_selections)
 8366        });
 8367
 8368        Ok(())
 8369    }
 8370
 8371    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8372        self.push_to_selection_history();
 8373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8374        self.select_next_match_internal(
 8375            &display_map,
 8376            action.replace_newest,
 8377            Some(Autoscroll::newest()),
 8378            cx,
 8379        )?;
 8380        Ok(())
 8381    }
 8382
 8383    pub fn select_previous(
 8384        &mut self,
 8385        action: &SelectPrevious,
 8386        cx: &mut ViewContext<Self>,
 8387    ) -> Result<()> {
 8388        self.push_to_selection_history();
 8389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8390        let buffer = &display_map.buffer_snapshot;
 8391        let mut selections = self.selections.all::<usize>(cx);
 8392        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8393            let query = &select_prev_state.query;
 8394            if !select_prev_state.done {
 8395                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8396                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8397                let mut next_selected_range = None;
 8398                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8399                let bytes_before_last_selection =
 8400                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8401                let bytes_after_first_selection =
 8402                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8403                let query_matches = query
 8404                    .stream_find_iter(bytes_before_last_selection)
 8405                    .map(|result| (last_selection.start, result))
 8406                    .chain(
 8407                        query
 8408                            .stream_find_iter(bytes_after_first_selection)
 8409                            .map(|result| (buffer.len(), result)),
 8410                    );
 8411                for (end_offset, query_match) in query_matches {
 8412                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8413                    let offset_range =
 8414                        end_offset - query_match.end()..end_offset - query_match.start();
 8415                    let display_range = offset_range.start.to_display_point(&display_map)
 8416                        ..offset_range.end.to_display_point(&display_map);
 8417
 8418                    if !select_prev_state.wordwise
 8419                        || (!movement::is_inside_word(&display_map, display_range.start)
 8420                            && !movement::is_inside_word(&display_map, display_range.end))
 8421                    {
 8422                        next_selected_range = Some(offset_range);
 8423                        break;
 8424                    }
 8425                }
 8426
 8427                if let Some(next_selected_range) = next_selected_range {
 8428                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8429                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8430                        if action.replace_newest {
 8431                            s.delete(s.newest_anchor().id);
 8432                        }
 8433                        s.insert_range(next_selected_range);
 8434                    });
 8435                } else {
 8436                    select_prev_state.done = true;
 8437                }
 8438            }
 8439
 8440            self.select_prev_state = Some(select_prev_state);
 8441        } else {
 8442            let mut only_carets = true;
 8443            let mut same_text_selected = true;
 8444            let mut selected_text = None;
 8445
 8446            let mut selections_iter = selections.iter().peekable();
 8447            while let Some(selection) = selections_iter.next() {
 8448                if selection.start != selection.end {
 8449                    only_carets = false;
 8450                }
 8451
 8452                if same_text_selected {
 8453                    if selected_text.is_none() {
 8454                        selected_text =
 8455                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8456                    }
 8457
 8458                    if let Some(next_selection) = selections_iter.peek() {
 8459                        if next_selection.range().len() == selection.range().len() {
 8460                            let next_selected_text = buffer
 8461                                .text_for_range(next_selection.range())
 8462                                .collect::<String>();
 8463                            if Some(next_selected_text) != selected_text {
 8464                                same_text_selected = false;
 8465                                selected_text = None;
 8466                            }
 8467                        } else {
 8468                            same_text_selected = false;
 8469                            selected_text = None;
 8470                        }
 8471                    }
 8472                }
 8473            }
 8474
 8475            if only_carets {
 8476                for selection in &mut selections {
 8477                    let word_range = movement::surrounding_word(
 8478                        &display_map,
 8479                        selection.start.to_display_point(&display_map),
 8480                    );
 8481                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8482                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8483                    selection.goal = SelectionGoal::None;
 8484                    selection.reversed = false;
 8485                }
 8486                if selections.len() == 1 {
 8487                    let selection = selections
 8488                        .last()
 8489                        .expect("ensured that there's only one selection");
 8490                    let query = buffer
 8491                        .text_for_range(selection.start..selection.end)
 8492                        .collect::<String>();
 8493                    let is_empty = query.is_empty();
 8494                    let select_state = SelectNextState {
 8495                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8496                        wordwise: true,
 8497                        done: is_empty,
 8498                    };
 8499                    self.select_prev_state = Some(select_state);
 8500                } else {
 8501                    self.select_prev_state = None;
 8502                }
 8503
 8504                self.unfold_ranges(
 8505                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8506                    false,
 8507                    true,
 8508                    cx,
 8509                );
 8510                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8511                    s.select(selections);
 8512                });
 8513            } else if let Some(selected_text) = selected_text {
 8514                self.select_prev_state = Some(SelectNextState {
 8515                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8516                    wordwise: false,
 8517                    done: false,
 8518                });
 8519                self.select_previous(action, cx)?;
 8520            }
 8521        }
 8522        Ok(())
 8523    }
 8524
 8525    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8526        if self.read_only(cx) {
 8527            return;
 8528        }
 8529        let text_layout_details = &self.text_layout_details(cx);
 8530        self.transact(cx, |this, cx| {
 8531            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8532            let mut edits = Vec::new();
 8533            let mut selection_edit_ranges = Vec::new();
 8534            let mut last_toggled_row = None;
 8535            let snapshot = this.buffer.read(cx).read(cx);
 8536            let empty_str: Arc<str> = Arc::default();
 8537            let mut suffixes_inserted = Vec::new();
 8538            let ignore_indent = action.ignore_indent;
 8539
 8540            fn comment_prefix_range(
 8541                snapshot: &MultiBufferSnapshot,
 8542                row: MultiBufferRow,
 8543                comment_prefix: &str,
 8544                comment_prefix_whitespace: &str,
 8545                ignore_indent: bool,
 8546            ) -> Range<Point> {
 8547                let indent_size = if ignore_indent {
 8548                    0
 8549                } else {
 8550                    snapshot.indent_size_for_line(row).len
 8551                };
 8552
 8553                let start = Point::new(row.0, indent_size);
 8554
 8555                let mut line_bytes = snapshot
 8556                    .bytes_in_range(start..snapshot.max_point())
 8557                    .flatten()
 8558                    .copied();
 8559
 8560                // If this line currently begins with the line comment prefix, then record
 8561                // the range containing the prefix.
 8562                if line_bytes
 8563                    .by_ref()
 8564                    .take(comment_prefix.len())
 8565                    .eq(comment_prefix.bytes())
 8566                {
 8567                    // Include any whitespace that matches the comment prefix.
 8568                    let matching_whitespace_len = line_bytes
 8569                        .zip(comment_prefix_whitespace.bytes())
 8570                        .take_while(|(a, b)| a == b)
 8571                        .count() as u32;
 8572                    let end = Point::new(
 8573                        start.row,
 8574                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8575                    );
 8576                    start..end
 8577                } else {
 8578                    start..start
 8579                }
 8580            }
 8581
 8582            fn comment_suffix_range(
 8583                snapshot: &MultiBufferSnapshot,
 8584                row: MultiBufferRow,
 8585                comment_suffix: &str,
 8586                comment_suffix_has_leading_space: bool,
 8587            ) -> Range<Point> {
 8588                let end = Point::new(row.0, snapshot.line_len(row));
 8589                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8590
 8591                let mut line_end_bytes = snapshot
 8592                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8593                    .flatten()
 8594                    .copied();
 8595
 8596                let leading_space_len = if suffix_start_column > 0
 8597                    && line_end_bytes.next() == Some(b' ')
 8598                    && comment_suffix_has_leading_space
 8599                {
 8600                    1
 8601                } else {
 8602                    0
 8603                };
 8604
 8605                // If this line currently begins with the line comment prefix, then record
 8606                // the range containing the prefix.
 8607                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8608                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8609                    start..end
 8610                } else {
 8611                    end..end
 8612                }
 8613            }
 8614
 8615            // TODO: Handle selections that cross excerpts
 8616            for selection in &mut selections {
 8617                let start_column = snapshot
 8618                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8619                    .len;
 8620                let language = if let Some(language) =
 8621                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8622                {
 8623                    language
 8624                } else {
 8625                    continue;
 8626                };
 8627
 8628                selection_edit_ranges.clear();
 8629
 8630                // If multiple selections contain a given row, avoid processing that
 8631                // row more than once.
 8632                let mut start_row = MultiBufferRow(selection.start.row);
 8633                if last_toggled_row == Some(start_row) {
 8634                    start_row = start_row.next_row();
 8635                }
 8636                let end_row =
 8637                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8638                        MultiBufferRow(selection.end.row - 1)
 8639                    } else {
 8640                        MultiBufferRow(selection.end.row)
 8641                    };
 8642                last_toggled_row = Some(end_row);
 8643
 8644                if start_row > end_row {
 8645                    continue;
 8646                }
 8647
 8648                // If the language has line comments, toggle those.
 8649                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8650
 8651                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8652                if ignore_indent {
 8653                    full_comment_prefixes = full_comment_prefixes
 8654                        .into_iter()
 8655                        .map(|s| Arc::from(s.trim_end()))
 8656                        .collect();
 8657                }
 8658
 8659                if !full_comment_prefixes.is_empty() {
 8660                    let first_prefix = full_comment_prefixes
 8661                        .first()
 8662                        .expect("prefixes is non-empty");
 8663                    let prefix_trimmed_lengths = full_comment_prefixes
 8664                        .iter()
 8665                        .map(|p| p.trim_end_matches(' ').len())
 8666                        .collect::<SmallVec<[usize; 4]>>();
 8667
 8668                    let mut all_selection_lines_are_comments = true;
 8669
 8670                    for row in start_row.0..=end_row.0 {
 8671                        let row = MultiBufferRow(row);
 8672                        if start_row < end_row && snapshot.is_line_blank(row) {
 8673                            continue;
 8674                        }
 8675
 8676                        let prefix_range = full_comment_prefixes
 8677                            .iter()
 8678                            .zip(prefix_trimmed_lengths.iter().copied())
 8679                            .map(|(prefix, trimmed_prefix_len)| {
 8680                                comment_prefix_range(
 8681                                    snapshot.deref(),
 8682                                    row,
 8683                                    &prefix[..trimmed_prefix_len],
 8684                                    &prefix[trimmed_prefix_len..],
 8685                                    ignore_indent,
 8686                                )
 8687                            })
 8688                            .max_by_key(|range| range.end.column - range.start.column)
 8689                            .expect("prefixes is non-empty");
 8690
 8691                        if prefix_range.is_empty() {
 8692                            all_selection_lines_are_comments = false;
 8693                        }
 8694
 8695                        selection_edit_ranges.push(prefix_range);
 8696                    }
 8697
 8698                    if all_selection_lines_are_comments {
 8699                        edits.extend(
 8700                            selection_edit_ranges
 8701                                .iter()
 8702                                .cloned()
 8703                                .map(|range| (range, empty_str.clone())),
 8704                        );
 8705                    } else {
 8706                        let min_column = selection_edit_ranges
 8707                            .iter()
 8708                            .map(|range| range.start.column)
 8709                            .min()
 8710                            .unwrap_or(0);
 8711                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8712                            let position = Point::new(range.start.row, min_column);
 8713                            (position..position, first_prefix.clone())
 8714                        }));
 8715                    }
 8716                } else if let Some((full_comment_prefix, comment_suffix)) =
 8717                    language.block_comment_delimiters()
 8718                {
 8719                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8720                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8721                    let prefix_range = comment_prefix_range(
 8722                        snapshot.deref(),
 8723                        start_row,
 8724                        comment_prefix,
 8725                        comment_prefix_whitespace,
 8726                        ignore_indent,
 8727                    );
 8728                    let suffix_range = comment_suffix_range(
 8729                        snapshot.deref(),
 8730                        end_row,
 8731                        comment_suffix.trim_start_matches(' '),
 8732                        comment_suffix.starts_with(' '),
 8733                    );
 8734
 8735                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8736                        edits.push((
 8737                            prefix_range.start..prefix_range.start,
 8738                            full_comment_prefix.clone(),
 8739                        ));
 8740                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8741                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8742                    } else {
 8743                        edits.push((prefix_range, empty_str.clone()));
 8744                        edits.push((suffix_range, empty_str.clone()));
 8745                    }
 8746                } else {
 8747                    continue;
 8748                }
 8749            }
 8750
 8751            drop(snapshot);
 8752            this.buffer.update(cx, |buffer, cx| {
 8753                buffer.edit(edits, None, cx);
 8754            });
 8755
 8756            // Adjust selections so that they end before any comment suffixes that
 8757            // were inserted.
 8758            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8759            let mut selections = this.selections.all::<Point>(cx);
 8760            let snapshot = this.buffer.read(cx).read(cx);
 8761            for selection in &mut selections {
 8762                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8763                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8764                        Ordering::Less => {
 8765                            suffixes_inserted.next();
 8766                            continue;
 8767                        }
 8768                        Ordering::Greater => break,
 8769                        Ordering::Equal => {
 8770                            if selection.end.column == snapshot.line_len(row) {
 8771                                if selection.is_empty() {
 8772                                    selection.start.column -= suffix_len as u32;
 8773                                }
 8774                                selection.end.column -= suffix_len as u32;
 8775                            }
 8776                            break;
 8777                        }
 8778                    }
 8779                }
 8780            }
 8781
 8782            drop(snapshot);
 8783            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8784
 8785            let selections = this.selections.all::<Point>(cx);
 8786            let selections_on_single_row = selections.windows(2).all(|selections| {
 8787                selections[0].start.row == selections[1].start.row
 8788                    && selections[0].end.row == selections[1].end.row
 8789                    && selections[0].start.row == selections[0].end.row
 8790            });
 8791            let selections_selecting = selections
 8792                .iter()
 8793                .any(|selection| selection.start != selection.end);
 8794            let advance_downwards = action.advance_downwards
 8795                && selections_on_single_row
 8796                && !selections_selecting
 8797                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8798
 8799            if advance_downwards {
 8800                let snapshot = this.buffer.read(cx).snapshot(cx);
 8801
 8802                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8803                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8804                        let mut point = display_point.to_point(display_snapshot);
 8805                        point.row += 1;
 8806                        point = snapshot.clip_point(point, Bias::Left);
 8807                        let display_point = point.to_display_point(display_snapshot);
 8808                        let goal = SelectionGoal::HorizontalPosition(
 8809                            display_snapshot
 8810                                .x_for_display_point(display_point, text_layout_details)
 8811                                .into(),
 8812                        );
 8813                        (display_point, goal)
 8814                    })
 8815                });
 8816            }
 8817        });
 8818    }
 8819
 8820    pub fn select_enclosing_symbol(
 8821        &mut self,
 8822        _: &SelectEnclosingSymbol,
 8823        cx: &mut ViewContext<Self>,
 8824    ) {
 8825        let buffer = self.buffer.read(cx).snapshot(cx);
 8826        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8827
 8828        fn update_selection(
 8829            selection: &Selection<usize>,
 8830            buffer_snap: &MultiBufferSnapshot,
 8831        ) -> Option<Selection<usize>> {
 8832            let cursor = selection.head();
 8833            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8834            for symbol in symbols.iter().rev() {
 8835                let start = symbol.range.start.to_offset(buffer_snap);
 8836                let end = symbol.range.end.to_offset(buffer_snap);
 8837                let new_range = start..end;
 8838                if start < selection.start || end > selection.end {
 8839                    return Some(Selection {
 8840                        id: selection.id,
 8841                        start: new_range.start,
 8842                        end: new_range.end,
 8843                        goal: SelectionGoal::None,
 8844                        reversed: selection.reversed,
 8845                    });
 8846                }
 8847            }
 8848            None
 8849        }
 8850
 8851        let mut selected_larger_symbol = false;
 8852        let new_selections = old_selections
 8853            .iter()
 8854            .map(|selection| match update_selection(selection, &buffer) {
 8855                Some(new_selection) => {
 8856                    if new_selection.range() != selection.range() {
 8857                        selected_larger_symbol = true;
 8858                    }
 8859                    new_selection
 8860                }
 8861                None => selection.clone(),
 8862            })
 8863            .collect::<Vec<_>>();
 8864
 8865        if selected_larger_symbol {
 8866            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8867                s.select(new_selections);
 8868            });
 8869        }
 8870    }
 8871
 8872    pub fn select_larger_syntax_node(
 8873        &mut self,
 8874        _: &SelectLargerSyntaxNode,
 8875        cx: &mut ViewContext<Self>,
 8876    ) {
 8877        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8878        let buffer = self.buffer.read(cx).snapshot(cx);
 8879        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8880
 8881        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8882        let mut selected_larger_node = false;
 8883        let new_selections = old_selections
 8884            .iter()
 8885            .map(|selection| {
 8886                let old_range = selection.start..selection.end;
 8887                let mut new_range = old_range.clone();
 8888                let mut new_node = None;
 8889                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8890                {
 8891                    new_node = Some(node);
 8892                    new_range = containing_range;
 8893                    if !display_map.intersects_fold(new_range.start)
 8894                        && !display_map.intersects_fold(new_range.end)
 8895                    {
 8896                        break;
 8897                    }
 8898                }
 8899
 8900                if let Some(node) = new_node {
 8901                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8902                    // nodes. Parent and grandparent are also logged because this operation will not
 8903                    // visit nodes that have the same range as their parent.
 8904                    log::info!("Node: {node:?}");
 8905                    let parent = node.parent();
 8906                    log::info!("Parent: {parent:?}");
 8907                    let grandparent = parent.and_then(|x| x.parent());
 8908                    log::info!("Grandparent: {grandparent:?}");
 8909                }
 8910
 8911                selected_larger_node |= new_range != old_range;
 8912                Selection {
 8913                    id: selection.id,
 8914                    start: new_range.start,
 8915                    end: new_range.end,
 8916                    goal: SelectionGoal::None,
 8917                    reversed: selection.reversed,
 8918                }
 8919            })
 8920            .collect::<Vec<_>>();
 8921
 8922        if selected_larger_node {
 8923            stack.push(old_selections);
 8924            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8925                s.select(new_selections);
 8926            });
 8927        }
 8928        self.select_larger_syntax_node_stack = stack;
 8929    }
 8930
 8931    pub fn select_smaller_syntax_node(
 8932        &mut self,
 8933        _: &SelectSmallerSyntaxNode,
 8934        cx: &mut ViewContext<Self>,
 8935    ) {
 8936        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8937        if let Some(selections) = stack.pop() {
 8938            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8939                s.select(selections.to_vec());
 8940            });
 8941        }
 8942        self.select_larger_syntax_node_stack = stack;
 8943    }
 8944
 8945    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8946        if !EditorSettings::get_global(cx).gutter.runnables {
 8947            self.clear_tasks();
 8948            return Task::ready(());
 8949        }
 8950        let project = self.project.as_ref().map(Model::downgrade);
 8951        cx.spawn(|this, mut cx| async move {
 8952            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8953            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8954                return;
 8955            };
 8956            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8957                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8958            }) else {
 8959                return;
 8960            };
 8961
 8962            let hide_runnables = project
 8963                .update(&mut cx, |project, cx| {
 8964                    // Do not display any test indicators in non-dev server remote projects.
 8965                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8966                })
 8967                .unwrap_or(true);
 8968            if hide_runnables {
 8969                return;
 8970            }
 8971            let new_rows =
 8972                cx.background_executor()
 8973                    .spawn({
 8974                        let snapshot = display_snapshot.clone();
 8975                        async move {
 8976                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8977                        }
 8978                    })
 8979                    .await;
 8980            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8981
 8982            this.update(&mut cx, |this, _| {
 8983                this.clear_tasks();
 8984                for (key, value) in rows {
 8985                    this.insert_tasks(key, value);
 8986                }
 8987            })
 8988            .ok();
 8989        })
 8990    }
 8991    fn fetch_runnable_ranges(
 8992        snapshot: &DisplaySnapshot,
 8993        range: Range<Anchor>,
 8994    ) -> Vec<language::RunnableRange> {
 8995        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8996    }
 8997
 8998    fn runnable_rows(
 8999        project: Model<Project>,
 9000        snapshot: DisplaySnapshot,
 9001        runnable_ranges: Vec<RunnableRange>,
 9002        mut cx: AsyncWindowContext,
 9003    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9004        runnable_ranges
 9005            .into_iter()
 9006            .filter_map(|mut runnable| {
 9007                let tasks = cx
 9008                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9009                    .ok()?;
 9010                if tasks.is_empty() {
 9011                    return None;
 9012                }
 9013
 9014                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9015
 9016                let row = snapshot
 9017                    .buffer_snapshot
 9018                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9019                    .1
 9020                    .start
 9021                    .row;
 9022
 9023                let context_range =
 9024                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9025                Some((
 9026                    (runnable.buffer_id, row),
 9027                    RunnableTasks {
 9028                        templates: tasks,
 9029                        offset: MultiBufferOffset(runnable.run_range.start),
 9030                        context_range,
 9031                        column: point.column,
 9032                        extra_variables: runnable.extra_captures,
 9033                    },
 9034                ))
 9035            })
 9036            .collect()
 9037    }
 9038
 9039    fn templates_with_tags(
 9040        project: &Model<Project>,
 9041        runnable: &mut Runnable,
 9042        cx: &WindowContext,
 9043    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9044        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9045            let (worktree_id, file) = project
 9046                .buffer_for_id(runnable.buffer, cx)
 9047                .and_then(|buffer| buffer.read(cx).file())
 9048                .map(|file| (file.worktree_id(cx), file.clone()))
 9049                .unzip();
 9050
 9051            (
 9052                project.task_store().read(cx).task_inventory().cloned(),
 9053                worktree_id,
 9054                file,
 9055            )
 9056        });
 9057
 9058        let tags = mem::take(&mut runnable.tags);
 9059        let mut tags: Vec<_> = tags
 9060            .into_iter()
 9061            .flat_map(|tag| {
 9062                let tag = tag.0.clone();
 9063                inventory
 9064                    .as_ref()
 9065                    .into_iter()
 9066                    .flat_map(|inventory| {
 9067                        inventory.read(cx).list_tasks(
 9068                            file.clone(),
 9069                            Some(runnable.language.clone()),
 9070                            worktree_id,
 9071                            cx,
 9072                        )
 9073                    })
 9074                    .filter(move |(_, template)| {
 9075                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9076                    })
 9077            })
 9078            .sorted_by_key(|(kind, _)| kind.to_owned())
 9079            .collect();
 9080        if let Some((leading_tag_source, _)) = tags.first() {
 9081            // Strongest source wins; if we have worktree tag binding, prefer that to
 9082            // global and language bindings;
 9083            // if we have a global binding, prefer that to language binding.
 9084            let first_mismatch = tags
 9085                .iter()
 9086                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9087            if let Some(index) = first_mismatch {
 9088                tags.truncate(index);
 9089            }
 9090        }
 9091
 9092        tags
 9093    }
 9094
 9095    pub fn move_to_enclosing_bracket(
 9096        &mut self,
 9097        _: &MoveToEnclosingBracket,
 9098        cx: &mut ViewContext<Self>,
 9099    ) {
 9100        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9101            s.move_offsets_with(|snapshot, selection| {
 9102                let Some(enclosing_bracket_ranges) =
 9103                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9104                else {
 9105                    return;
 9106                };
 9107
 9108                let mut best_length = usize::MAX;
 9109                let mut best_inside = false;
 9110                let mut best_in_bracket_range = false;
 9111                let mut best_destination = None;
 9112                for (open, close) in enclosing_bracket_ranges {
 9113                    let close = close.to_inclusive();
 9114                    let length = close.end() - open.start;
 9115                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9116                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9117                        || close.contains(&selection.head());
 9118
 9119                    // If best is next to a bracket and current isn't, skip
 9120                    if !in_bracket_range && best_in_bracket_range {
 9121                        continue;
 9122                    }
 9123
 9124                    // Prefer smaller lengths unless best is inside and current isn't
 9125                    if length > best_length && (best_inside || !inside) {
 9126                        continue;
 9127                    }
 9128
 9129                    best_length = length;
 9130                    best_inside = inside;
 9131                    best_in_bracket_range = in_bracket_range;
 9132                    best_destination = Some(
 9133                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9134                            if inside {
 9135                                open.end
 9136                            } else {
 9137                                open.start
 9138                            }
 9139                        } else if inside {
 9140                            *close.start()
 9141                        } else {
 9142                            *close.end()
 9143                        },
 9144                    );
 9145                }
 9146
 9147                if let Some(destination) = best_destination {
 9148                    selection.collapse_to(destination, SelectionGoal::None);
 9149                }
 9150            })
 9151        });
 9152    }
 9153
 9154    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9155        self.end_selection(cx);
 9156        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9157        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9158            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9159            self.select_next_state = entry.select_next_state;
 9160            self.select_prev_state = entry.select_prev_state;
 9161            self.add_selections_state = entry.add_selections_state;
 9162            self.request_autoscroll(Autoscroll::newest(), cx);
 9163        }
 9164        self.selection_history.mode = SelectionHistoryMode::Normal;
 9165    }
 9166
 9167    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9168        self.end_selection(cx);
 9169        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9170        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9171            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9172            self.select_next_state = entry.select_next_state;
 9173            self.select_prev_state = entry.select_prev_state;
 9174            self.add_selections_state = entry.add_selections_state;
 9175            self.request_autoscroll(Autoscroll::newest(), cx);
 9176        }
 9177        self.selection_history.mode = SelectionHistoryMode::Normal;
 9178    }
 9179
 9180    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9181        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9182    }
 9183
 9184    pub fn expand_excerpts_down(
 9185        &mut self,
 9186        action: &ExpandExcerptsDown,
 9187        cx: &mut ViewContext<Self>,
 9188    ) {
 9189        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9190    }
 9191
 9192    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9193        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9194    }
 9195
 9196    pub fn expand_excerpts_for_direction(
 9197        &mut self,
 9198        lines: u32,
 9199        direction: ExpandExcerptDirection,
 9200        cx: &mut ViewContext<Self>,
 9201    ) {
 9202        let selections = self.selections.disjoint_anchors();
 9203
 9204        let lines = if lines == 0 {
 9205            EditorSettings::get_global(cx).expand_excerpt_lines
 9206        } else {
 9207            lines
 9208        };
 9209
 9210        self.buffer.update(cx, |buffer, cx| {
 9211            let snapshot = buffer.snapshot(cx);
 9212            let mut excerpt_ids = selections
 9213                .iter()
 9214                .flat_map(|selection| {
 9215                    snapshot
 9216                        .excerpts_for_range(selection.range())
 9217                        .map(|excerpt| excerpt.id())
 9218                })
 9219                .collect::<Vec<_>>();
 9220            excerpt_ids.sort();
 9221            excerpt_ids.dedup();
 9222            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9223        })
 9224    }
 9225
 9226    pub fn expand_excerpt(
 9227        &mut self,
 9228        excerpt: ExcerptId,
 9229        direction: ExpandExcerptDirection,
 9230        cx: &mut ViewContext<Self>,
 9231    ) {
 9232        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9233        self.buffer.update(cx, |buffer, cx| {
 9234            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9235        })
 9236    }
 9237
 9238    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9239        self.go_to_diagnostic_impl(Direction::Next, cx)
 9240    }
 9241
 9242    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9243        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9244    }
 9245
 9246    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9247        let buffer = self.buffer.read(cx).snapshot(cx);
 9248        let selection = self.selections.newest::<usize>(cx);
 9249
 9250        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9251        if direction == Direction::Next {
 9252            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9253                self.activate_diagnostics(popover.group_id(), cx);
 9254                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9255                    let primary_range_start = active_diagnostics.primary_range.start;
 9256                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9257                        let mut new_selection = s.newest_anchor().clone();
 9258                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9259                        s.select_anchors(vec![new_selection.clone()]);
 9260                    });
 9261                    self.refresh_inline_completion(false, true, cx);
 9262                }
 9263                return;
 9264            }
 9265        }
 9266
 9267        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9268            active_diagnostics
 9269                .primary_range
 9270                .to_offset(&buffer)
 9271                .to_inclusive()
 9272        });
 9273        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9274            if active_primary_range.contains(&selection.head()) {
 9275                *active_primary_range.start()
 9276            } else {
 9277                selection.head()
 9278            }
 9279        } else {
 9280            selection.head()
 9281        };
 9282        let snapshot = self.snapshot(cx);
 9283        loop {
 9284            let diagnostics = if direction == Direction::Prev {
 9285                buffer.diagnostics_in_range(0..search_start, true)
 9286            } else {
 9287                buffer.diagnostics_in_range(search_start..buffer.len(), false)
 9288            }
 9289            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9290            let search_start_anchor = buffer.anchor_after(search_start);
 9291            let group = diagnostics
 9292                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9293                // be sorted in a stable way
 9294                // skip until we are at current active diagnostic, if it exists
 9295                .skip_while(|entry| {
 9296                    let is_in_range = match direction {
 9297                        Direction::Prev => {
 9298                            entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
 9299                        }
 9300                        Direction::Next => {
 9301                            entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
 9302                        }
 9303                    };
 9304                    is_in_range
 9305                        && self
 9306                            .active_diagnostics
 9307                            .as_ref()
 9308                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9309                })
 9310                .find_map(|entry| {
 9311                    if entry.diagnostic.is_primary
 9312                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9313                        && !(entry.range.start == entry.range.end)
 9314                        // if we match with the active diagnostic, skip it
 9315                        && Some(entry.diagnostic.group_id)
 9316                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9317                    {
 9318                        Some((entry.range, entry.diagnostic.group_id))
 9319                    } else {
 9320                        None
 9321                    }
 9322                });
 9323
 9324            if let Some((primary_range, group_id)) = group {
 9325                self.activate_diagnostics(group_id, cx);
 9326                let primary_range = primary_range.to_offset(&buffer);
 9327                if self.active_diagnostics.is_some() {
 9328                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9329                        s.select(vec![Selection {
 9330                            id: selection.id,
 9331                            start: primary_range.start,
 9332                            end: primary_range.start,
 9333                            reversed: false,
 9334                            goal: SelectionGoal::None,
 9335                        }]);
 9336                    });
 9337                    self.refresh_inline_completion(false, true, cx);
 9338                }
 9339                break;
 9340            } else {
 9341                // Cycle around to the start of the buffer, potentially moving back to the start of
 9342                // the currently active diagnostic.
 9343                active_primary_range.take();
 9344                if direction == Direction::Prev {
 9345                    if search_start == buffer.len() {
 9346                        break;
 9347                    } else {
 9348                        search_start = buffer.len();
 9349                    }
 9350                } else if search_start == 0 {
 9351                    break;
 9352                } else {
 9353                    search_start = 0;
 9354                }
 9355            }
 9356        }
 9357    }
 9358
 9359    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9360        let snapshot = self.snapshot(cx);
 9361        let selection = self.selections.newest::<Point>(cx);
 9362        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9363    }
 9364
 9365    fn go_to_hunk_after_position(
 9366        &mut self,
 9367        snapshot: &EditorSnapshot,
 9368        position: Point,
 9369        cx: &mut ViewContext<Editor>,
 9370    ) -> Option<MultiBufferDiffHunk> {
 9371        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9372            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9373                snapshot,
 9374                position,
 9375                ix > 0,
 9376                snapshot.diff_map.diff_hunks_in_range(
 9377                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9378                    &snapshot.buffer_snapshot,
 9379                ),
 9380                cx,
 9381            ) {
 9382                return Some(hunk);
 9383            }
 9384        }
 9385        None
 9386    }
 9387
 9388    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9389        let snapshot = self.snapshot(cx);
 9390        let selection = self.selections.newest::<Point>(cx);
 9391        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9392    }
 9393
 9394    fn go_to_hunk_before_position(
 9395        &mut self,
 9396        snapshot: &EditorSnapshot,
 9397        position: Point,
 9398        cx: &mut ViewContext<Editor>,
 9399    ) -> Option<MultiBufferDiffHunk> {
 9400        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9401            .into_iter()
 9402            .enumerate()
 9403        {
 9404            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9405                snapshot,
 9406                position,
 9407                ix > 0,
 9408                snapshot
 9409                    .diff_map
 9410                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9411                cx,
 9412            ) {
 9413                return Some(hunk);
 9414            }
 9415        }
 9416        None
 9417    }
 9418
 9419    fn go_to_next_hunk_in_direction(
 9420        &mut self,
 9421        snapshot: &DisplaySnapshot,
 9422        initial_point: Point,
 9423        is_wrapped: bool,
 9424        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9425        cx: &mut ViewContext<Editor>,
 9426    ) -> Option<MultiBufferDiffHunk> {
 9427        let display_point = initial_point.to_display_point(snapshot);
 9428        let mut hunks = hunks
 9429            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9430            .filter(|(display_hunk, _)| {
 9431                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9432            })
 9433            .dedup();
 9434
 9435        if let Some((display_hunk, hunk)) = hunks.next() {
 9436            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9437                let row = display_hunk.start_display_row();
 9438                let point = DisplayPoint::new(row, 0);
 9439                s.select_display_ranges([point..point]);
 9440            });
 9441
 9442            Some(hunk)
 9443        } else {
 9444            None
 9445        }
 9446    }
 9447
 9448    pub fn go_to_definition(
 9449        &mut self,
 9450        _: &GoToDefinition,
 9451        cx: &mut ViewContext<Self>,
 9452    ) -> Task<Result<Navigated>> {
 9453        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9454        cx.spawn(|editor, mut cx| async move {
 9455            if definition.await? == Navigated::Yes {
 9456                return Ok(Navigated::Yes);
 9457            }
 9458            match editor.update(&mut cx, |editor, cx| {
 9459                editor.find_all_references(&FindAllReferences, cx)
 9460            })? {
 9461                Some(references) => references.await,
 9462                None => Ok(Navigated::No),
 9463            }
 9464        })
 9465    }
 9466
 9467    pub fn go_to_declaration(
 9468        &mut self,
 9469        _: &GoToDeclaration,
 9470        cx: &mut ViewContext<Self>,
 9471    ) -> Task<Result<Navigated>> {
 9472        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9473    }
 9474
 9475    pub fn go_to_declaration_split(
 9476        &mut self,
 9477        _: &GoToDeclaration,
 9478        cx: &mut ViewContext<Self>,
 9479    ) -> Task<Result<Navigated>> {
 9480        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9481    }
 9482
 9483    pub fn go_to_implementation(
 9484        &mut self,
 9485        _: &GoToImplementation,
 9486        cx: &mut ViewContext<Self>,
 9487    ) -> Task<Result<Navigated>> {
 9488        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9489    }
 9490
 9491    pub fn go_to_implementation_split(
 9492        &mut self,
 9493        _: &GoToImplementationSplit,
 9494        cx: &mut ViewContext<Self>,
 9495    ) -> Task<Result<Navigated>> {
 9496        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9497    }
 9498
 9499    pub fn go_to_type_definition(
 9500        &mut self,
 9501        _: &GoToTypeDefinition,
 9502        cx: &mut ViewContext<Self>,
 9503    ) -> Task<Result<Navigated>> {
 9504        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9505    }
 9506
 9507    pub fn go_to_definition_split(
 9508        &mut self,
 9509        _: &GoToDefinitionSplit,
 9510        cx: &mut ViewContext<Self>,
 9511    ) -> Task<Result<Navigated>> {
 9512        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9513    }
 9514
 9515    pub fn go_to_type_definition_split(
 9516        &mut self,
 9517        _: &GoToTypeDefinitionSplit,
 9518        cx: &mut ViewContext<Self>,
 9519    ) -> Task<Result<Navigated>> {
 9520        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9521    }
 9522
 9523    fn go_to_definition_of_kind(
 9524        &mut self,
 9525        kind: GotoDefinitionKind,
 9526        split: bool,
 9527        cx: &mut ViewContext<Self>,
 9528    ) -> Task<Result<Navigated>> {
 9529        let Some(provider) = self.semantics_provider.clone() else {
 9530            return Task::ready(Ok(Navigated::No));
 9531        };
 9532        let head = self.selections.newest::<usize>(cx).head();
 9533        let buffer = self.buffer.read(cx);
 9534        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9535            text_anchor
 9536        } else {
 9537            return Task::ready(Ok(Navigated::No));
 9538        };
 9539
 9540        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9541            return Task::ready(Ok(Navigated::No));
 9542        };
 9543
 9544        cx.spawn(|editor, mut cx| async move {
 9545            let definitions = definitions.await?;
 9546            let navigated = editor
 9547                .update(&mut cx, |editor, cx| {
 9548                    editor.navigate_to_hover_links(
 9549                        Some(kind),
 9550                        definitions
 9551                            .into_iter()
 9552                            .filter(|location| {
 9553                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9554                            })
 9555                            .map(HoverLink::Text)
 9556                            .collect::<Vec<_>>(),
 9557                        split,
 9558                        cx,
 9559                    )
 9560                })?
 9561                .await?;
 9562            anyhow::Ok(navigated)
 9563        })
 9564    }
 9565
 9566    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9567        let selection = self.selections.newest_anchor();
 9568        let head = selection.head();
 9569        let tail = selection.tail();
 9570
 9571        let Some((buffer, start_position)) =
 9572            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9573        else {
 9574            return;
 9575        };
 9576
 9577        let end_position = if head != tail {
 9578            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9579                return;
 9580            };
 9581            Some(pos)
 9582        } else {
 9583            None
 9584        };
 9585
 9586        let url_finder = cx.spawn(|editor, mut cx| async move {
 9587            let url = if let Some(end_pos) = end_position {
 9588                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9589            } else {
 9590                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9591            };
 9592
 9593            if let Some(url) = url {
 9594                editor.update(&mut cx, |_, cx| {
 9595                    cx.open_url(&url);
 9596                })
 9597            } else {
 9598                Ok(())
 9599            }
 9600        });
 9601
 9602        url_finder.detach();
 9603    }
 9604
 9605    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9606        let Some(workspace) = self.workspace() else {
 9607            return;
 9608        };
 9609
 9610        let position = self.selections.newest_anchor().head();
 9611
 9612        let Some((buffer, buffer_position)) =
 9613            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9614        else {
 9615            return;
 9616        };
 9617
 9618        let project = self.project.clone();
 9619
 9620        cx.spawn(|_, mut cx| async move {
 9621            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9622
 9623            if let Some((_, path)) = result {
 9624                workspace
 9625                    .update(&mut cx, |workspace, cx| {
 9626                        workspace.open_resolved_path(path, cx)
 9627                    })?
 9628                    .await?;
 9629            }
 9630            anyhow::Ok(())
 9631        })
 9632        .detach();
 9633    }
 9634
 9635    pub(crate) fn navigate_to_hover_links(
 9636        &mut self,
 9637        kind: Option<GotoDefinitionKind>,
 9638        mut definitions: Vec<HoverLink>,
 9639        split: bool,
 9640        cx: &mut ViewContext<Editor>,
 9641    ) -> Task<Result<Navigated>> {
 9642        // If there is one definition, just open it directly
 9643        if definitions.len() == 1 {
 9644            let definition = definitions.pop().unwrap();
 9645
 9646            enum TargetTaskResult {
 9647                Location(Option<Location>),
 9648                AlreadyNavigated,
 9649            }
 9650
 9651            let target_task = match definition {
 9652                HoverLink::Text(link) => {
 9653                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9654                }
 9655                HoverLink::InlayHint(lsp_location, server_id) => {
 9656                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9657                    cx.background_executor().spawn(async move {
 9658                        let location = computation.await?;
 9659                        Ok(TargetTaskResult::Location(location))
 9660                    })
 9661                }
 9662                HoverLink::Url(url) => {
 9663                    cx.open_url(&url);
 9664                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9665                }
 9666                HoverLink::File(path) => {
 9667                    if let Some(workspace) = self.workspace() {
 9668                        cx.spawn(|_, mut cx| async move {
 9669                            workspace
 9670                                .update(&mut cx, |workspace, cx| {
 9671                                    workspace.open_resolved_path(path, cx)
 9672                                })?
 9673                                .await
 9674                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9675                        })
 9676                    } else {
 9677                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9678                    }
 9679                }
 9680            };
 9681            cx.spawn(|editor, mut cx| async move {
 9682                let target = match target_task.await.context("target resolution task")? {
 9683                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9684                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9685                    TargetTaskResult::Location(Some(target)) => target,
 9686                };
 9687
 9688                editor.update(&mut cx, |editor, cx| {
 9689                    let Some(workspace) = editor.workspace() else {
 9690                        return Navigated::No;
 9691                    };
 9692                    let pane = workspace.read(cx).active_pane().clone();
 9693
 9694                    let range = target.range.to_offset(target.buffer.read(cx));
 9695                    let range = editor.range_for_match(&range);
 9696
 9697                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9698                        let buffer = target.buffer.read(cx);
 9699                        let range = check_multiline_range(buffer, range);
 9700                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9701                            s.select_ranges([range]);
 9702                        });
 9703                    } else {
 9704                        cx.window_context().defer(move |cx| {
 9705                            let target_editor: View<Self> =
 9706                                workspace.update(cx, |workspace, cx| {
 9707                                    let pane = if split {
 9708                                        workspace.adjacent_pane(cx)
 9709                                    } else {
 9710                                        workspace.active_pane().clone()
 9711                                    };
 9712
 9713                                    workspace.open_project_item(
 9714                                        pane,
 9715                                        target.buffer.clone(),
 9716                                        true,
 9717                                        true,
 9718                                        cx,
 9719                                    )
 9720                                });
 9721                            target_editor.update(cx, |target_editor, cx| {
 9722                                // When selecting a definition in a different buffer, disable the nav history
 9723                                // to avoid creating a history entry at the previous cursor location.
 9724                                pane.update(cx, |pane, _| pane.disable_history());
 9725                                let buffer = target.buffer.read(cx);
 9726                                let range = check_multiline_range(buffer, range);
 9727                                target_editor.change_selections(
 9728                                    Some(Autoscroll::focused()),
 9729                                    cx,
 9730                                    |s| {
 9731                                        s.select_ranges([range]);
 9732                                    },
 9733                                );
 9734                                pane.update(cx, |pane, _| pane.enable_history());
 9735                            });
 9736                        });
 9737                    }
 9738                    Navigated::Yes
 9739                })
 9740            })
 9741        } else if !definitions.is_empty() {
 9742            cx.spawn(|editor, mut cx| async move {
 9743                let (title, location_tasks, workspace) = editor
 9744                    .update(&mut cx, |editor, cx| {
 9745                        let tab_kind = match kind {
 9746                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9747                            _ => "Definitions",
 9748                        };
 9749                        let title = definitions
 9750                            .iter()
 9751                            .find_map(|definition| match definition {
 9752                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9753                                    let buffer = origin.buffer.read(cx);
 9754                                    format!(
 9755                                        "{} for {}",
 9756                                        tab_kind,
 9757                                        buffer
 9758                                            .text_for_range(origin.range.clone())
 9759                                            .collect::<String>()
 9760                                    )
 9761                                }),
 9762                                HoverLink::InlayHint(_, _) => None,
 9763                                HoverLink::Url(_) => None,
 9764                                HoverLink::File(_) => None,
 9765                            })
 9766                            .unwrap_or(tab_kind.to_string());
 9767                        let location_tasks = definitions
 9768                            .into_iter()
 9769                            .map(|definition| match definition {
 9770                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9771                                HoverLink::InlayHint(lsp_location, server_id) => {
 9772                                    editor.compute_target_location(lsp_location, server_id, cx)
 9773                                }
 9774                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9775                                HoverLink::File(_) => Task::ready(Ok(None)),
 9776                            })
 9777                            .collect::<Vec<_>>();
 9778                        (title, location_tasks, editor.workspace().clone())
 9779                    })
 9780                    .context("location tasks preparation")?;
 9781
 9782                let locations = future::join_all(location_tasks)
 9783                    .await
 9784                    .into_iter()
 9785                    .filter_map(|location| location.transpose())
 9786                    .collect::<Result<_>>()
 9787                    .context("location tasks")?;
 9788
 9789                let Some(workspace) = workspace else {
 9790                    return Ok(Navigated::No);
 9791                };
 9792                let opened = workspace
 9793                    .update(&mut cx, |workspace, cx| {
 9794                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9795                    })
 9796                    .ok();
 9797
 9798                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9799            })
 9800        } else {
 9801            Task::ready(Ok(Navigated::No))
 9802        }
 9803    }
 9804
 9805    fn compute_target_location(
 9806        &self,
 9807        lsp_location: lsp::Location,
 9808        server_id: LanguageServerId,
 9809        cx: &mut ViewContext<Self>,
 9810    ) -> Task<anyhow::Result<Option<Location>>> {
 9811        let Some(project) = self.project.clone() else {
 9812            return Task::ready(Ok(None));
 9813        };
 9814
 9815        cx.spawn(move |editor, mut cx| async move {
 9816            let location_task = editor.update(&mut cx, |_, cx| {
 9817                project.update(cx, |project, cx| {
 9818                    let language_server_name = project
 9819                        .language_server_statuses(cx)
 9820                        .find(|(id, _)| server_id == *id)
 9821                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9822                    language_server_name.map(|language_server_name| {
 9823                        project.open_local_buffer_via_lsp(
 9824                            lsp_location.uri.clone(),
 9825                            server_id,
 9826                            language_server_name,
 9827                            cx,
 9828                        )
 9829                    })
 9830                })
 9831            })?;
 9832            let location = match location_task {
 9833                Some(task) => Some({
 9834                    let target_buffer_handle = task.await.context("open local buffer")?;
 9835                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9836                        let target_start = target_buffer
 9837                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9838                        let target_end = target_buffer
 9839                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9840                        target_buffer.anchor_after(target_start)
 9841                            ..target_buffer.anchor_before(target_end)
 9842                    })?;
 9843                    Location {
 9844                        buffer: target_buffer_handle,
 9845                        range,
 9846                    }
 9847                }),
 9848                None => None,
 9849            };
 9850            Ok(location)
 9851        })
 9852    }
 9853
 9854    pub fn find_all_references(
 9855        &mut self,
 9856        _: &FindAllReferences,
 9857        cx: &mut ViewContext<Self>,
 9858    ) -> Option<Task<Result<Navigated>>> {
 9859        let selection = self.selections.newest::<usize>(cx);
 9860        let multi_buffer = self.buffer.read(cx);
 9861        let head = selection.head();
 9862
 9863        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9864        let head_anchor = multi_buffer_snapshot.anchor_at(
 9865            head,
 9866            if head < selection.tail() {
 9867                Bias::Right
 9868            } else {
 9869                Bias::Left
 9870            },
 9871        );
 9872
 9873        match self
 9874            .find_all_references_task_sources
 9875            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9876        {
 9877            Ok(_) => {
 9878                log::info!(
 9879                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9880                );
 9881                return None;
 9882            }
 9883            Err(i) => {
 9884                self.find_all_references_task_sources.insert(i, head_anchor);
 9885            }
 9886        }
 9887
 9888        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9889        let workspace = self.workspace()?;
 9890        let project = workspace.read(cx).project().clone();
 9891        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9892        Some(cx.spawn(|editor, mut cx| async move {
 9893            let _cleanup = defer({
 9894                let mut cx = cx.clone();
 9895                move || {
 9896                    let _ = editor.update(&mut cx, |editor, _| {
 9897                        if let Ok(i) =
 9898                            editor
 9899                                .find_all_references_task_sources
 9900                                .binary_search_by(|anchor| {
 9901                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9902                                })
 9903                        {
 9904                            editor.find_all_references_task_sources.remove(i);
 9905                        }
 9906                    });
 9907                }
 9908            });
 9909
 9910            let locations = references.await?;
 9911            if locations.is_empty() {
 9912                return anyhow::Ok(Navigated::No);
 9913            }
 9914
 9915            workspace.update(&mut cx, |workspace, cx| {
 9916                let title = locations
 9917                    .first()
 9918                    .as_ref()
 9919                    .map(|location| {
 9920                        let buffer = location.buffer.read(cx);
 9921                        format!(
 9922                            "References to `{}`",
 9923                            buffer
 9924                                .text_for_range(location.range.clone())
 9925                                .collect::<String>()
 9926                        )
 9927                    })
 9928                    .unwrap();
 9929                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9930                Navigated::Yes
 9931            })
 9932        }))
 9933    }
 9934
 9935    /// Opens a multibuffer with the given project locations in it
 9936    pub fn open_locations_in_multibuffer(
 9937        workspace: &mut Workspace,
 9938        mut locations: Vec<Location>,
 9939        title: String,
 9940        split: bool,
 9941        cx: &mut ViewContext<Workspace>,
 9942    ) {
 9943        // If there are multiple definitions, open them in a multibuffer
 9944        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9945        let mut locations = locations.into_iter().peekable();
 9946        let mut ranges_to_highlight = Vec::new();
 9947        let capability = workspace.project().read(cx).capability();
 9948
 9949        let excerpt_buffer = cx.new_model(|cx| {
 9950            let mut multibuffer = MultiBuffer::new(capability);
 9951            while let Some(location) = locations.next() {
 9952                let buffer = location.buffer.read(cx);
 9953                let mut ranges_for_buffer = Vec::new();
 9954                let range = location.range.to_offset(buffer);
 9955                ranges_for_buffer.push(range.clone());
 9956
 9957                while let Some(next_location) = locations.peek() {
 9958                    if next_location.buffer == location.buffer {
 9959                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9960                        locations.next();
 9961                    } else {
 9962                        break;
 9963                    }
 9964                }
 9965
 9966                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9967                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9968                    location.buffer.clone(),
 9969                    ranges_for_buffer,
 9970                    DEFAULT_MULTIBUFFER_CONTEXT,
 9971                    cx,
 9972                ))
 9973            }
 9974
 9975            multibuffer.with_title(title)
 9976        });
 9977
 9978        let editor = cx.new_view(|cx| {
 9979            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9980        });
 9981        editor.update(cx, |editor, cx| {
 9982            if let Some(first_range) = ranges_to_highlight.first() {
 9983                editor.change_selections(None, cx, |selections| {
 9984                    selections.clear_disjoint();
 9985                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9986                });
 9987            }
 9988            editor.highlight_background::<Self>(
 9989                &ranges_to_highlight,
 9990                |theme| theme.editor_highlighted_line_background,
 9991                cx,
 9992            );
 9993            editor.register_buffers_with_language_servers(cx);
 9994        });
 9995
 9996        let item = Box::new(editor);
 9997        let item_id = item.item_id();
 9998
 9999        if split {
10000            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10001        } else {
10002            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10003                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10004                    pane.close_current_preview_item(cx)
10005                } else {
10006                    None
10007                }
10008            });
10009            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10010        }
10011        workspace.active_pane().update(cx, |pane, cx| {
10012            pane.set_preview_item_id(Some(item_id), cx);
10013        });
10014    }
10015
10016    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10017        use language::ToOffset as _;
10018
10019        let provider = self.semantics_provider.clone()?;
10020        let selection = self.selections.newest_anchor().clone();
10021        let (cursor_buffer, cursor_buffer_position) = self
10022            .buffer
10023            .read(cx)
10024            .text_anchor_for_position(selection.head(), cx)?;
10025        let (tail_buffer, cursor_buffer_position_end) = self
10026            .buffer
10027            .read(cx)
10028            .text_anchor_for_position(selection.tail(), cx)?;
10029        if tail_buffer != cursor_buffer {
10030            return None;
10031        }
10032
10033        let snapshot = cursor_buffer.read(cx).snapshot();
10034        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10035        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10036        let prepare_rename = provider
10037            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10038            .unwrap_or_else(|| Task::ready(Ok(None)));
10039        drop(snapshot);
10040
10041        Some(cx.spawn(|this, mut cx| async move {
10042            let rename_range = if let Some(range) = prepare_rename.await? {
10043                Some(range)
10044            } else {
10045                this.update(&mut cx, |this, cx| {
10046                    let buffer = this.buffer.read(cx).snapshot(cx);
10047                    let mut buffer_highlights = this
10048                        .document_highlights_for_position(selection.head(), &buffer)
10049                        .filter(|highlight| {
10050                            highlight.start.excerpt_id == selection.head().excerpt_id
10051                                && highlight.end.excerpt_id == selection.head().excerpt_id
10052                        });
10053                    buffer_highlights
10054                        .next()
10055                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10056                })?
10057            };
10058            if let Some(rename_range) = rename_range {
10059                this.update(&mut cx, |this, cx| {
10060                    let snapshot = cursor_buffer.read(cx).snapshot();
10061                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10062                    let cursor_offset_in_rename_range =
10063                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10064                    let cursor_offset_in_rename_range_end =
10065                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10066
10067                    this.take_rename(false, cx);
10068                    let buffer = this.buffer.read(cx).read(cx);
10069                    let cursor_offset = selection.head().to_offset(&buffer);
10070                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10071                    let rename_end = rename_start + rename_buffer_range.len();
10072                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10073                    let mut old_highlight_id = None;
10074                    let old_name: Arc<str> = buffer
10075                        .chunks(rename_start..rename_end, true)
10076                        .map(|chunk| {
10077                            if old_highlight_id.is_none() {
10078                                old_highlight_id = chunk.syntax_highlight_id;
10079                            }
10080                            chunk.text
10081                        })
10082                        .collect::<String>()
10083                        .into();
10084
10085                    drop(buffer);
10086
10087                    // Position the selection in the rename editor so that it matches the current selection.
10088                    this.show_local_selections = false;
10089                    let rename_editor = cx.new_view(|cx| {
10090                        let mut editor = Editor::single_line(cx);
10091                        editor.buffer.update(cx, |buffer, cx| {
10092                            buffer.edit([(0..0, old_name.clone())], None, cx)
10093                        });
10094                        let rename_selection_range = match cursor_offset_in_rename_range
10095                            .cmp(&cursor_offset_in_rename_range_end)
10096                        {
10097                            Ordering::Equal => {
10098                                editor.select_all(&SelectAll, cx);
10099                                return editor;
10100                            }
10101                            Ordering::Less => {
10102                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10103                            }
10104                            Ordering::Greater => {
10105                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10106                            }
10107                        };
10108                        if rename_selection_range.end > old_name.len() {
10109                            editor.select_all(&SelectAll, cx);
10110                        } else {
10111                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10112                                s.select_ranges([rename_selection_range]);
10113                            });
10114                        }
10115                        editor
10116                    });
10117                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10118                        if e == &EditorEvent::Focused {
10119                            cx.emit(EditorEvent::FocusedIn)
10120                        }
10121                    })
10122                    .detach();
10123
10124                    let write_highlights =
10125                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10126                    let read_highlights =
10127                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10128                    let ranges = write_highlights
10129                        .iter()
10130                        .flat_map(|(_, ranges)| ranges.iter())
10131                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10132                        .cloned()
10133                        .collect();
10134
10135                    this.highlight_text::<Rename>(
10136                        ranges,
10137                        HighlightStyle {
10138                            fade_out: Some(0.6),
10139                            ..Default::default()
10140                        },
10141                        cx,
10142                    );
10143                    let rename_focus_handle = rename_editor.focus_handle(cx);
10144                    cx.focus(&rename_focus_handle);
10145                    let block_id = this.insert_blocks(
10146                        [BlockProperties {
10147                            style: BlockStyle::Flex,
10148                            placement: BlockPlacement::Below(range.start),
10149                            height: 1,
10150                            render: Arc::new({
10151                                let rename_editor = rename_editor.clone();
10152                                move |cx: &mut BlockContext| {
10153                                    let mut text_style = cx.editor_style.text.clone();
10154                                    if let Some(highlight_style) = old_highlight_id
10155                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10156                                    {
10157                                        text_style = text_style.highlight(highlight_style);
10158                                    }
10159                                    div()
10160                                        .block_mouse_down()
10161                                        .pl(cx.anchor_x)
10162                                        .child(EditorElement::new(
10163                                            &rename_editor,
10164                                            EditorStyle {
10165                                                background: cx.theme().system().transparent,
10166                                                local_player: cx.editor_style.local_player,
10167                                                text: text_style,
10168                                                scrollbar_width: cx.editor_style.scrollbar_width,
10169                                                syntax: cx.editor_style.syntax.clone(),
10170                                                status: cx.editor_style.status.clone(),
10171                                                inlay_hints_style: HighlightStyle {
10172                                                    font_weight: Some(FontWeight::BOLD),
10173                                                    ..make_inlay_hints_style(cx)
10174                                                },
10175                                                inline_completion_styles: make_suggestion_styles(
10176                                                    cx,
10177                                                ),
10178                                                ..EditorStyle::default()
10179                                            },
10180                                        ))
10181                                        .into_any_element()
10182                                }
10183                            }),
10184                            priority: 0,
10185                        }],
10186                        Some(Autoscroll::fit()),
10187                        cx,
10188                    )[0];
10189                    this.pending_rename = Some(RenameState {
10190                        range,
10191                        old_name,
10192                        editor: rename_editor,
10193                        block_id,
10194                    });
10195                })?;
10196            }
10197
10198            Ok(())
10199        }))
10200    }
10201
10202    pub fn confirm_rename(
10203        &mut self,
10204        _: &ConfirmRename,
10205        cx: &mut ViewContext<Self>,
10206    ) -> Option<Task<Result<()>>> {
10207        let rename = self.take_rename(false, cx)?;
10208        let workspace = self.workspace()?.downgrade();
10209        let (buffer, start) = self
10210            .buffer
10211            .read(cx)
10212            .text_anchor_for_position(rename.range.start, cx)?;
10213        let (end_buffer, _) = self
10214            .buffer
10215            .read(cx)
10216            .text_anchor_for_position(rename.range.end, cx)?;
10217        if buffer != end_buffer {
10218            return None;
10219        }
10220
10221        let old_name = rename.old_name;
10222        let new_name = rename.editor.read(cx).text(cx);
10223
10224        let rename = self.semantics_provider.as_ref()?.perform_rename(
10225            &buffer,
10226            start,
10227            new_name.clone(),
10228            cx,
10229        )?;
10230
10231        Some(cx.spawn(|editor, mut cx| async move {
10232            let project_transaction = rename.await?;
10233            Self::open_project_transaction(
10234                &editor,
10235                workspace,
10236                project_transaction,
10237                format!("Rename: {}{}", old_name, new_name),
10238                cx.clone(),
10239            )
10240            .await?;
10241
10242            editor.update(&mut cx, |editor, cx| {
10243                editor.refresh_document_highlights(cx);
10244            })?;
10245            Ok(())
10246        }))
10247    }
10248
10249    fn take_rename(
10250        &mut self,
10251        moving_cursor: bool,
10252        cx: &mut ViewContext<Self>,
10253    ) -> Option<RenameState> {
10254        let rename = self.pending_rename.take()?;
10255        if rename.editor.focus_handle(cx).is_focused(cx) {
10256            cx.focus(&self.focus_handle);
10257        }
10258
10259        self.remove_blocks(
10260            [rename.block_id].into_iter().collect(),
10261            Some(Autoscroll::fit()),
10262            cx,
10263        );
10264        self.clear_highlights::<Rename>(cx);
10265        self.show_local_selections = true;
10266
10267        if moving_cursor {
10268            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10269                editor.selections.newest::<usize>(cx).head()
10270            });
10271
10272            // Update the selection to match the position of the selection inside
10273            // the rename editor.
10274            let snapshot = self.buffer.read(cx).read(cx);
10275            let rename_range = rename.range.to_offset(&snapshot);
10276            let cursor_in_editor = snapshot
10277                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10278                .min(rename_range.end);
10279            drop(snapshot);
10280
10281            self.change_selections(None, cx, |s| {
10282                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10283            });
10284        } else {
10285            self.refresh_document_highlights(cx);
10286        }
10287
10288        Some(rename)
10289    }
10290
10291    pub fn pending_rename(&self) -> Option<&RenameState> {
10292        self.pending_rename.as_ref()
10293    }
10294
10295    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10296        let project = match &self.project {
10297            Some(project) => project.clone(),
10298            None => return None,
10299        };
10300
10301        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10302    }
10303
10304    fn format_selections(
10305        &mut self,
10306        _: &FormatSelections,
10307        cx: &mut ViewContext<Self>,
10308    ) -> Option<Task<Result<()>>> {
10309        let project = match &self.project {
10310            Some(project) => project.clone(),
10311            None => return None,
10312        };
10313
10314        let ranges = self
10315            .selections
10316            .all_adjusted(cx)
10317            .into_iter()
10318            .map(|selection| selection.range())
10319            .collect_vec();
10320
10321        Some(self.perform_format(
10322            project,
10323            FormatTrigger::Manual,
10324            FormatTarget::Ranges(ranges),
10325            cx,
10326        ))
10327    }
10328
10329    fn perform_format(
10330        &mut self,
10331        project: Model<Project>,
10332        trigger: FormatTrigger,
10333        target: FormatTarget,
10334        cx: &mut ViewContext<Self>,
10335    ) -> Task<Result<()>> {
10336        let buffer = self.buffer.clone();
10337        let (buffers, target) = match target {
10338            FormatTarget::Buffers => {
10339                let mut buffers = buffer.read(cx).all_buffers();
10340                if trigger == FormatTrigger::Save {
10341                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10342                }
10343                (buffers, LspFormatTarget::Buffers)
10344            }
10345            FormatTarget::Ranges(selection_ranges) => {
10346                let multi_buffer = buffer.read(cx);
10347                let snapshot = multi_buffer.read(cx);
10348                let mut buffers = HashSet::default();
10349                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10350                    BTreeMap::new();
10351                for selection_range in selection_ranges {
10352                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10353                    {
10354                        let buffer_id = excerpt.buffer_id();
10355                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10356                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10357                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10358                        buffer_id_to_ranges
10359                            .entry(buffer_id)
10360                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10361                            .or_insert_with(|| vec![start..end]);
10362                    }
10363                }
10364                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10365            }
10366        };
10367
10368        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10369        let format = project.update(cx, |project, cx| {
10370            project.format(buffers, target, true, trigger, cx)
10371        });
10372
10373        cx.spawn(|_, mut cx| async move {
10374            let transaction = futures::select_biased! {
10375                () = timeout => {
10376                    log::warn!("timed out waiting for formatting");
10377                    None
10378                }
10379                transaction = format.log_err().fuse() => transaction,
10380            };
10381
10382            buffer
10383                .update(&mut cx, |buffer, cx| {
10384                    if let Some(transaction) = transaction {
10385                        if !buffer.is_singleton() {
10386                            buffer.push_transaction(&transaction.0, cx);
10387                        }
10388                    }
10389
10390                    cx.notify();
10391                })
10392                .ok();
10393
10394            Ok(())
10395        })
10396    }
10397
10398    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10399        if let Some(project) = self.project.clone() {
10400            self.buffer.update(cx, |multi_buffer, cx| {
10401                project.update(cx, |project, cx| {
10402                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10403                });
10404            })
10405        }
10406    }
10407
10408    fn cancel_language_server_work(
10409        &mut self,
10410        _: &actions::CancelLanguageServerWork,
10411        cx: &mut ViewContext<Self>,
10412    ) {
10413        if let Some(project) = self.project.clone() {
10414            self.buffer.update(cx, |multi_buffer, cx| {
10415                project.update(cx, |project, cx| {
10416                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10417                });
10418            })
10419        }
10420    }
10421
10422    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10423        cx.show_character_palette();
10424    }
10425
10426    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10427        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10428            let buffer = self.buffer.read(cx).snapshot(cx);
10429            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10430            let is_valid = buffer
10431                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10432                .any(|entry| {
10433                    let range = entry.range.to_offset(&buffer);
10434                    entry.diagnostic.is_primary
10435                        && !range.is_empty()
10436                        && range.start == primary_range_start
10437                        && entry.diagnostic.message == active_diagnostics.primary_message
10438                });
10439
10440            if is_valid != active_diagnostics.is_valid {
10441                active_diagnostics.is_valid = is_valid;
10442                let mut new_styles = HashMap::default();
10443                for (block_id, diagnostic) in &active_diagnostics.blocks {
10444                    new_styles.insert(
10445                        *block_id,
10446                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10447                    );
10448                }
10449                self.display_map.update(cx, |display_map, _cx| {
10450                    display_map.replace_blocks(new_styles)
10451                });
10452            }
10453        }
10454    }
10455
10456    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10457        self.dismiss_diagnostics(cx);
10458        let snapshot = self.snapshot(cx);
10459        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10460            let buffer = self.buffer.read(cx).snapshot(cx);
10461
10462            let mut primary_range = None;
10463            let mut primary_message = None;
10464            let mut group_end = Point::zero();
10465            let diagnostic_group = buffer
10466                .diagnostic_group(group_id)
10467                .filter_map(|entry| {
10468                    let start = entry.range.start.to_point(&buffer);
10469                    let end = entry.range.end.to_point(&buffer);
10470                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10471                        && (start.row == end.row
10472                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10473                    {
10474                        return None;
10475                    }
10476                    if end > group_end {
10477                        group_end = end;
10478                    }
10479                    if entry.diagnostic.is_primary {
10480                        primary_range = Some(entry.range.clone());
10481                        primary_message = Some(entry.diagnostic.message.clone());
10482                    }
10483                    Some(entry)
10484                })
10485                .collect::<Vec<_>>();
10486            let primary_range = primary_range?;
10487            let primary_message = primary_message?;
10488
10489            let blocks = display_map
10490                .insert_blocks(
10491                    diagnostic_group.iter().map(|entry| {
10492                        let diagnostic = entry.diagnostic.clone();
10493                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10494                        BlockProperties {
10495                            style: BlockStyle::Fixed,
10496                            placement: BlockPlacement::Below(
10497                                buffer.anchor_after(entry.range.start),
10498                            ),
10499                            height: message_height,
10500                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10501                            priority: 0,
10502                        }
10503                    }),
10504                    cx,
10505                )
10506                .into_iter()
10507                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10508                .collect();
10509
10510            Some(ActiveDiagnosticGroup {
10511                primary_range,
10512                primary_message,
10513                group_id,
10514                blocks,
10515                is_valid: true,
10516            })
10517        });
10518    }
10519
10520    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10521        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10522            self.display_map.update(cx, |display_map, cx| {
10523                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10524            });
10525            cx.notify();
10526        }
10527    }
10528
10529    pub fn set_selections_from_remote(
10530        &mut self,
10531        selections: Vec<Selection<Anchor>>,
10532        pending_selection: Option<Selection<Anchor>>,
10533        cx: &mut ViewContext<Self>,
10534    ) {
10535        let old_cursor_position = self.selections.newest_anchor().head();
10536        self.selections.change_with(cx, |s| {
10537            s.select_anchors(selections);
10538            if let Some(pending_selection) = pending_selection {
10539                s.set_pending(pending_selection, SelectMode::Character);
10540            } else {
10541                s.clear_pending();
10542            }
10543        });
10544        self.selections_did_change(false, &old_cursor_position, true, cx);
10545    }
10546
10547    fn push_to_selection_history(&mut self) {
10548        self.selection_history.push(SelectionHistoryEntry {
10549            selections: self.selections.disjoint_anchors(),
10550            select_next_state: self.select_next_state.clone(),
10551            select_prev_state: self.select_prev_state.clone(),
10552            add_selections_state: self.add_selections_state.clone(),
10553        });
10554    }
10555
10556    pub fn transact(
10557        &mut self,
10558        cx: &mut ViewContext<Self>,
10559        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10560    ) -> Option<TransactionId> {
10561        self.start_transaction_at(Instant::now(), cx);
10562        update(self, cx);
10563        self.end_transaction_at(Instant::now(), cx)
10564    }
10565
10566    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10567        self.end_selection(cx);
10568        if let Some(tx_id) = self
10569            .buffer
10570            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10571        {
10572            self.selection_history
10573                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10574            cx.emit(EditorEvent::TransactionBegun {
10575                transaction_id: tx_id,
10576            })
10577        }
10578    }
10579
10580    pub fn end_transaction_at(
10581        &mut self,
10582        now: Instant,
10583        cx: &mut ViewContext<Self>,
10584    ) -> Option<TransactionId> {
10585        if let Some(transaction_id) = self
10586            .buffer
10587            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10588        {
10589            if let Some((_, end_selections)) =
10590                self.selection_history.transaction_mut(transaction_id)
10591            {
10592                *end_selections = Some(self.selections.disjoint_anchors());
10593            } else {
10594                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10595            }
10596
10597            cx.emit(EditorEvent::Edited { transaction_id });
10598            Some(transaction_id)
10599        } else {
10600            None
10601        }
10602    }
10603
10604    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10605        if self.is_singleton(cx) {
10606            let selection = self.selections.newest::<Point>(cx);
10607
10608            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10609            let range = if selection.is_empty() {
10610                let point = selection.head().to_display_point(&display_map);
10611                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10612                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10613                    .to_point(&display_map);
10614                start..end
10615            } else {
10616                selection.range()
10617            };
10618            if display_map.folds_in_range(range).next().is_some() {
10619                self.unfold_lines(&Default::default(), cx)
10620            } else {
10621                self.fold(&Default::default(), cx)
10622            }
10623        } else {
10624            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10625            let mut toggled_buffers = HashSet::default();
10626            for (_, buffer_snapshot, _) in
10627                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10628            {
10629                let buffer_id = buffer_snapshot.remote_id();
10630                if toggled_buffers.insert(buffer_id) {
10631                    if self.buffer_folded(buffer_id, cx) {
10632                        self.unfold_buffer(buffer_id, cx);
10633                    } else {
10634                        self.fold_buffer(buffer_id, cx);
10635                    }
10636                }
10637            }
10638        }
10639    }
10640
10641    pub fn toggle_fold_recursive(
10642        &mut self,
10643        _: &actions::ToggleFoldRecursive,
10644        cx: &mut ViewContext<Self>,
10645    ) {
10646        let selection = self.selections.newest::<Point>(cx);
10647
10648        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10649        let range = if selection.is_empty() {
10650            let point = selection.head().to_display_point(&display_map);
10651            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10652            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10653                .to_point(&display_map);
10654            start..end
10655        } else {
10656            selection.range()
10657        };
10658        if display_map.folds_in_range(range).next().is_some() {
10659            self.unfold_recursive(&Default::default(), cx)
10660        } else {
10661            self.fold_recursive(&Default::default(), cx)
10662        }
10663    }
10664
10665    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10666        if self.is_singleton(cx) {
10667            let mut to_fold = Vec::new();
10668            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10669            let selections = self.selections.all_adjusted(cx);
10670
10671            for selection in selections {
10672                let range = selection.range().sorted();
10673                let buffer_start_row = range.start.row;
10674
10675                if range.start.row != range.end.row {
10676                    let mut found = false;
10677                    let mut row = range.start.row;
10678                    while row <= range.end.row {
10679                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10680                        {
10681                            found = true;
10682                            row = crease.range().end.row + 1;
10683                            to_fold.push(crease);
10684                        } else {
10685                            row += 1
10686                        }
10687                    }
10688                    if found {
10689                        continue;
10690                    }
10691                }
10692
10693                for row in (0..=range.start.row).rev() {
10694                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10695                        if crease.range().end.row >= buffer_start_row {
10696                            to_fold.push(crease);
10697                            if row <= range.start.row {
10698                                break;
10699                            }
10700                        }
10701                    }
10702                }
10703            }
10704
10705            self.fold_creases(to_fold, true, cx);
10706        } else {
10707            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10708            let mut folded_buffers = HashSet::default();
10709            for (_, buffer_snapshot, _) in
10710                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10711            {
10712                let buffer_id = buffer_snapshot.remote_id();
10713                if folded_buffers.insert(buffer_id) {
10714                    self.fold_buffer(buffer_id, cx);
10715                }
10716            }
10717        }
10718    }
10719
10720    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10721        if !self.buffer.read(cx).is_singleton() {
10722            return;
10723        }
10724
10725        let fold_at_level = fold_at.level;
10726        let snapshot = self.buffer.read(cx).snapshot(cx);
10727        let mut to_fold = Vec::new();
10728        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10729
10730        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10731            while start_row < end_row {
10732                match self
10733                    .snapshot(cx)
10734                    .crease_for_buffer_row(MultiBufferRow(start_row))
10735                {
10736                    Some(crease) => {
10737                        let nested_start_row = crease.range().start.row + 1;
10738                        let nested_end_row = crease.range().end.row;
10739
10740                        if current_level < fold_at_level {
10741                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10742                        } else if current_level == fold_at_level {
10743                            to_fold.push(crease);
10744                        }
10745
10746                        start_row = nested_end_row + 1;
10747                    }
10748                    None => start_row += 1,
10749                }
10750            }
10751        }
10752
10753        self.fold_creases(to_fold, true, cx);
10754    }
10755
10756    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10757        if self.buffer.read(cx).is_singleton() {
10758            let mut fold_ranges = Vec::new();
10759            let snapshot = self.buffer.read(cx).snapshot(cx);
10760
10761            for row in 0..snapshot.max_row().0 {
10762                if let Some(foldable_range) =
10763                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10764                {
10765                    fold_ranges.push(foldable_range);
10766                }
10767            }
10768
10769            self.fold_creases(fold_ranges, true, cx);
10770        } else {
10771            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10772                editor
10773                    .update(&mut cx, |editor, cx| {
10774                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10775                            editor.fold_buffer(buffer_id, cx);
10776                        }
10777                    })
10778                    .ok();
10779            });
10780        }
10781    }
10782
10783    pub fn fold_function_bodies(
10784        &mut self,
10785        _: &actions::FoldFunctionBodies,
10786        cx: &mut ViewContext<Self>,
10787    ) {
10788        let snapshot = self.buffer.read(cx).snapshot(cx);
10789        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10790            return;
10791        };
10792        let creases = buffer
10793            .function_body_fold_ranges(0..buffer.len())
10794            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10795            .collect();
10796
10797        self.fold_creases(creases, true, cx);
10798    }
10799
10800    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10801        let mut to_fold = Vec::new();
10802        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10803        let selections = self.selections.all_adjusted(cx);
10804
10805        for selection in selections {
10806            let range = selection.range().sorted();
10807            let buffer_start_row = range.start.row;
10808
10809            if range.start.row != range.end.row {
10810                let mut found = false;
10811                for row in range.start.row..=range.end.row {
10812                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10813                        found = true;
10814                        to_fold.push(crease);
10815                    }
10816                }
10817                if found {
10818                    continue;
10819                }
10820            }
10821
10822            for row in (0..=range.start.row).rev() {
10823                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10824                    if crease.range().end.row >= buffer_start_row {
10825                        to_fold.push(crease);
10826                    } else {
10827                        break;
10828                    }
10829                }
10830            }
10831        }
10832
10833        self.fold_creases(to_fold, true, cx);
10834    }
10835
10836    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10837        let buffer_row = fold_at.buffer_row;
10838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839
10840        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10841            let autoscroll = self
10842                .selections
10843                .all::<Point>(cx)
10844                .iter()
10845                .any(|selection| crease.range().overlaps(&selection.range()));
10846
10847            self.fold_creases(vec![crease], autoscroll, cx);
10848        }
10849    }
10850
10851    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10852        if self.is_singleton(cx) {
10853            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10854            let buffer = &display_map.buffer_snapshot;
10855            let selections = self.selections.all::<Point>(cx);
10856            let ranges = selections
10857                .iter()
10858                .map(|s| {
10859                    let range = s.display_range(&display_map).sorted();
10860                    let mut start = range.start.to_point(&display_map);
10861                    let mut end = range.end.to_point(&display_map);
10862                    start.column = 0;
10863                    end.column = buffer.line_len(MultiBufferRow(end.row));
10864                    start..end
10865                })
10866                .collect::<Vec<_>>();
10867
10868            self.unfold_ranges(&ranges, true, true, cx);
10869        } else {
10870            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10871            let mut unfolded_buffers = HashSet::default();
10872            for (_, buffer_snapshot, _) in
10873                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10874            {
10875                let buffer_id = buffer_snapshot.remote_id();
10876                if unfolded_buffers.insert(buffer_id) {
10877                    self.unfold_buffer(buffer_id, cx);
10878                }
10879            }
10880        }
10881    }
10882
10883    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10885        let selections = self.selections.all::<Point>(cx);
10886        let ranges = selections
10887            .iter()
10888            .map(|s| {
10889                let mut range = s.display_range(&display_map).sorted();
10890                *range.start.column_mut() = 0;
10891                *range.end.column_mut() = display_map.line_len(range.end.row());
10892                let start = range.start.to_point(&display_map);
10893                let end = range.end.to_point(&display_map);
10894                start..end
10895            })
10896            .collect::<Vec<_>>();
10897
10898        self.unfold_ranges(&ranges, true, true, cx);
10899    }
10900
10901    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10902        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10903
10904        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10905            ..Point::new(
10906                unfold_at.buffer_row.0,
10907                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10908            );
10909
10910        let autoscroll = self
10911            .selections
10912            .all::<Point>(cx)
10913            .iter()
10914            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10915
10916        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10917    }
10918
10919    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10920        if self.buffer.read(cx).is_singleton() {
10921            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10922            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10923        } else {
10924            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10925                editor
10926                    .update(&mut cx, |editor, cx| {
10927                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10928                            editor.unfold_buffer(buffer_id, cx);
10929                        }
10930                    })
10931                    .ok();
10932            });
10933        }
10934    }
10935
10936    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10937        let selections = self.selections.all::<Point>(cx);
10938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10939        let line_mode = self.selections.line_mode;
10940        let ranges = selections
10941            .into_iter()
10942            .map(|s| {
10943                if line_mode {
10944                    let start = Point::new(s.start.row, 0);
10945                    let end = Point::new(
10946                        s.end.row,
10947                        display_map
10948                            .buffer_snapshot
10949                            .line_len(MultiBufferRow(s.end.row)),
10950                    );
10951                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10952                } else {
10953                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10954                }
10955            })
10956            .collect::<Vec<_>>();
10957        self.fold_creases(ranges, true, cx);
10958    }
10959
10960    pub fn fold_ranges<T: ToOffset + Clone>(
10961        &mut self,
10962        ranges: Vec<Range<T>>,
10963        auto_scroll: bool,
10964        cx: &mut ViewContext<Self>,
10965    ) {
10966        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10967        let ranges = ranges
10968            .into_iter()
10969            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10970            .collect::<Vec<_>>();
10971        self.fold_creases(ranges, auto_scroll, cx);
10972    }
10973
10974    pub fn fold_creases<T: ToOffset + Clone>(
10975        &mut self,
10976        creases: Vec<Crease<T>>,
10977        auto_scroll: bool,
10978        cx: &mut ViewContext<Self>,
10979    ) {
10980        if creases.is_empty() {
10981            return;
10982        }
10983
10984        let mut buffers_affected = HashSet::default();
10985        let multi_buffer = self.buffer().read(cx);
10986        for crease in &creases {
10987            if let Some((_, buffer, _)) =
10988                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10989            {
10990                buffers_affected.insert(buffer.read(cx).remote_id());
10991            };
10992        }
10993
10994        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10995
10996        if auto_scroll {
10997            self.request_autoscroll(Autoscroll::fit(), cx);
10998        }
10999
11000        for buffer_id in buffers_affected {
11001            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11002        }
11003
11004        cx.notify();
11005
11006        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11007            // Clear diagnostics block when folding a range that contains it.
11008            let snapshot = self.snapshot(cx);
11009            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11010                drop(snapshot);
11011                self.active_diagnostics = Some(active_diagnostics);
11012                self.dismiss_diagnostics(cx);
11013            } else {
11014                self.active_diagnostics = Some(active_diagnostics);
11015            }
11016        }
11017
11018        self.scrollbar_marker_state.dirty = true;
11019    }
11020
11021    /// Removes any folds whose ranges intersect any of the given ranges.
11022    pub fn unfold_ranges<T: ToOffset + Clone>(
11023        &mut self,
11024        ranges: &[Range<T>],
11025        inclusive: bool,
11026        auto_scroll: bool,
11027        cx: &mut ViewContext<Self>,
11028    ) {
11029        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11030            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11031        });
11032    }
11033
11034    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11035        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11036            return;
11037        }
11038        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11039            return;
11040        };
11041        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11042        self.display_map
11043            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11044        cx.emit(EditorEvent::BufferFoldToggled {
11045            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11046            folded: true,
11047        });
11048        cx.notify();
11049    }
11050
11051    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11052        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11053            return;
11054        }
11055        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11056            return;
11057        };
11058        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11059        self.display_map.update(cx, |display_map, cx| {
11060            display_map.unfold_buffer(buffer_id, cx);
11061        });
11062        cx.emit(EditorEvent::BufferFoldToggled {
11063            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11064            folded: false,
11065        });
11066        cx.notify();
11067    }
11068
11069    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11070        self.display_map.read(cx).buffer_folded(buffer)
11071    }
11072
11073    /// Removes any folds with the given ranges.
11074    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11075        &mut self,
11076        ranges: &[Range<T>],
11077        type_id: TypeId,
11078        auto_scroll: bool,
11079        cx: &mut ViewContext<Self>,
11080    ) {
11081        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11082            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11083        });
11084    }
11085
11086    fn remove_folds_with<T: ToOffset + Clone>(
11087        &mut self,
11088        ranges: &[Range<T>],
11089        auto_scroll: bool,
11090        cx: &mut ViewContext<Self>,
11091        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11092    ) {
11093        if ranges.is_empty() {
11094            return;
11095        }
11096
11097        let mut buffers_affected = HashSet::default();
11098        let multi_buffer = self.buffer().read(cx);
11099        for range in ranges {
11100            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11101                buffers_affected.insert(buffer.read(cx).remote_id());
11102            };
11103        }
11104
11105        self.display_map.update(cx, update);
11106
11107        if auto_scroll {
11108            self.request_autoscroll(Autoscroll::fit(), cx);
11109        }
11110
11111        for buffer_id in buffers_affected {
11112            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11113        }
11114
11115        cx.notify();
11116        self.scrollbar_marker_state.dirty = true;
11117        self.active_indent_guides_state.dirty = true;
11118    }
11119
11120    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11121        self.display_map.read(cx).fold_placeholder.clone()
11122    }
11123
11124    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11125        if hovered != self.gutter_hovered {
11126            self.gutter_hovered = hovered;
11127            cx.notify();
11128        }
11129    }
11130
11131    pub fn insert_blocks(
11132        &mut self,
11133        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11134        autoscroll: Option<Autoscroll>,
11135        cx: &mut ViewContext<Self>,
11136    ) -> Vec<CustomBlockId> {
11137        let blocks = self
11138            .display_map
11139            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11140        if let Some(autoscroll) = autoscroll {
11141            self.request_autoscroll(autoscroll, cx);
11142        }
11143        cx.notify();
11144        blocks
11145    }
11146
11147    pub fn resize_blocks(
11148        &mut self,
11149        heights: HashMap<CustomBlockId, u32>,
11150        autoscroll: Option<Autoscroll>,
11151        cx: &mut ViewContext<Self>,
11152    ) {
11153        self.display_map
11154            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11155        if let Some(autoscroll) = autoscroll {
11156            self.request_autoscroll(autoscroll, cx);
11157        }
11158        cx.notify();
11159    }
11160
11161    pub fn replace_blocks(
11162        &mut self,
11163        renderers: HashMap<CustomBlockId, RenderBlock>,
11164        autoscroll: Option<Autoscroll>,
11165        cx: &mut ViewContext<Self>,
11166    ) {
11167        self.display_map
11168            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11169        if let Some(autoscroll) = autoscroll {
11170            self.request_autoscroll(autoscroll, cx);
11171        }
11172        cx.notify();
11173    }
11174
11175    pub fn remove_blocks(
11176        &mut self,
11177        block_ids: HashSet<CustomBlockId>,
11178        autoscroll: Option<Autoscroll>,
11179        cx: &mut ViewContext<Self>,
11180    ) {
11181        self.display_map.update(cx, |display_map, cx| {
11182            display_map.remove_blocks(block_ids, cx)
11183        });
11184        if let Some(autoscroll) = autoscroll {
11185            self.request_autoscroll(autoscroll, cx);
11186        }
11187        cx.notify();
11188    }
11189
11190    pub fn row_for_block(
11191        &self,
11192        block_id: CustomBlockId,
11193        cx: &mut ViewContext<Self>,
11194    ) -> Option<DisplayRow> {
11195        self.display_map
11196            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11197    }
11198
11199    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11200        self.focused_block = Some(focused_block);
11201    }
11202
11203    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11204        self.focused_block.take()
11205    }
11206
11207    pub fn insert_creases(
11208        &mut self,
11209        creases: impl IntoIterator<Item = Crease<Anchor>>,
11210        cx: &mut ViewContext<Self>,
11211    ) -> Vec<CreaseId> {
11212        self.display_map
11213            .update(cx, |map, cx| map.insert_creases(creases, cx))
11214    }
11215
11216    pub fn remove_creases(
11217        &mut self,
11218        ids: impl IntoIterator<Item = CreaseId>,
11219        cx: &mut ViewContext<Self>,
11220    ) {
11221        self.display_map
11222            .update(cx, |map, cx| map.remove_creases(ids, cx));
11223    }
11224
11225    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11226        self.display_map
11227            .update(cx, |map, cx| map.snapshot(cx))
11228            .longest_row()
11229    }
11230
11231    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11232        self.display_map
11233            .update(cx, |map, cx| map.snapshot(cx))
11234            .max_point()
11235    }
11236
11237    pub fn text(&self, cx: &AppContext) -> String {
11238        self.buffer.read(cx).read(cx).text()
11239    }
11240
11241    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11242        let text = self.text(cx);
11243        let text = text.trim();
11244
11245        if text.is_empty() {
11246            return None;
11247        }
11248
11249        Some(text.to_string())
11250    }
11251
11252    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11253        self.transact(cx, |this, cx| {
11254            this.buffer
11255                .read(cx)
11256                .as_singleton()
11257                .expect("you can only call set_text on editors for singleton buffers")
11258                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11259        });
11260    }
11261
11262    pub fn display_text(&self, cx: &mut AppContext) -> String {
11263        self.display_map
11264            .update(cx, |map, cx| map.snapshot(cx))
11265            .text()
11266    }
11267
11268    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11269        let mut wrap_guides = smallvec::smallvec![];
11270
11271        if self.show_wrap_guides == Some(false) {
11272            return wrap_guides;
11273        }
11274
11275        let settings = self.buffer.read(cx).settings_at(0, cx);
11276        if settings.show_wrap_guides {
11277            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11278                wrap_guides.push((soft_wrap as usize, true));
11279            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11280                wrap_guides.push((soft_wrap as usize, true));
11281            }
11282            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11283        }
11284
11285        wrap_guides
11286    }
11287
11288    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11289        let settings = self.buffer.read(cx).settings_at(0, cx);
11290        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11291        match mode {
11292            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11293                SoftWrap::None
11294            }
11295            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11296            language_settings::SoftWrap::PreferredLineLength => {
11297                SoftWrap::Column(settings.preferred_line_length)
11298            }
11299            language_settings::SoftWrap::Bounded => {
11300                SoftWrap::Bounded(settings.preferred_line_length)
11301            }
11302        }
11303    }
11304
11305    pub fn set_soft_wrap_mode(
11306        &mut self,
11307        mode: language_settings::SoftWrap,
11308        cx: &mut ViewContext<Self>,
11309    ) {
11310        self.soft_wrap_mode_override = Some(mode);
11311        cx.notify();
11312    }
11313
11314    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11315        self.text_style_refinement = Some(style);
11316    }
11317
11318    /// called by the Element so we know what style we were most recently rendered with.
11319    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11320        let rem_size = cx.rem_size();
11321        self.display_map.update(cx, |map, cx| {
11322            map.set_font(
11323                style.text.font(),
11324                style.text.font_size.to_pixels(rem_size),
11325                cx,
11326            )
11327        });
11328        self.style = Some(style);
11329    }
11330
11331    pub fn style(&self) -> Option<&EditorStyle> {
11332        self.style.as_ref()
11333    }
11334
11335    // Called by the element. This method is not designed to be called outside of the editor
11336    // element's layout code because it does not notify when rewrapping is computed synchronously.
11337    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11338        self.display_map
11339            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11340    }
11341
11342    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11343        if self.soft_wrap_mode_override.is_some() {
11344            self.soft_wrap_mode_override.take();
11345        } else {
11346            let soft_wrap = match self.soft_wrap_mode(cx) {
11347                SoftWrap::GitDiff => return,
11348                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11349                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11350                    language_settings::SoftWrap::None
11351                }
11352            };
11353            self.soft_wrap_mode_override = Some(soft_wrap);
11354        }
11355        cx.notify();
11356    }
11357
11358    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11359        let Some(workspace) = self.workspace() else {
11360            return;
11361        };
11362        let fs = workspace.read(cx).app_state().fs.clone();
11363        let current_show = TabBarSettings::get_global(cx).show;
11364        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11365            setting.show = Some(!current_show);
11366        });
11367    }
11368
11369    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11370        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11371            self.buffer
11372                .read(cx)
11373                .settings_at(0, cx)
11374                .indent_guides
11375                .enabled
11376        });
11377        self.show_indent_guides = Some(!currently_enabled);
11378        cx.notify();
11379    }
11380
11381    fn should_show_indent_guides(&self) -> Option<bool> {
11382        self.show_indent_guides
11383    }
11384
11385    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11386        let mut editor_settings = EditorSettings::get_global(cx).clone();
11387        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11388        EditorSettings::override_global(editor_settings, cx);
11389    }
11390
11391    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11392        self.use_relative_line_numbers
11393            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11394    }
11395
11396    pub fn toggle_relative_line_numbers(
11397        &mut self,
11398        _: &ToggleRelativeLineNumbers,
11399        cx: &mut ViewContext<Self>,
11400    ) {
11401        let is_relative = self.should_use_relative_line_numbers(cx);
11402        self.set_relative_line_number(Some(!is_relative), cx)
11403    }
11404
11405    pub fn set_relative_line_number(
11406        &mut self,
11407        is_relative: Option<bool>,
11408        cx: &mut ViewContext<Self>,
11409    ) {
11410        self.use_relative_line_numbers = is_relative;
11411        cx.notify();
11412    }
11413
11414    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11415        self.show_gutter = show_gutter;
11416        cx.notify();
11417    }
11418
11419    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11420        self.show_scrollbars = show_scrollbars;
11421        cx.notify();
11422    }
11423
11424    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11425        self.show_line_numbers = Some(show_line_numbers);
11426        cx.notify();
11427    }
11428
11429    pub fn set_show_git_diff_gutter(
11430        &mut self,
11431        show_git_diff_gutter: bool,
11432        cx: &mut ViewContext<Self>,
11433    ) {
11434        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11435        cx.notify();
11436    }
11437
11438    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11439        self.show_code_actions = Some(show_code_actions);
11440        cx.notify();
11441    }
11442
11443    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11444        self.show_runnables = Some(show_runnables);
11445        cx.notify();
11446    }
11447
11448    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11449        if self.display_map.read(cx).masked != masked {
11450            self.display_map.update(cx, |map, _| map.masked = masked);
11451        }
11452        cx.notify()
11453    }
11454
11455    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11456        self.show_wrap_guides = Some(show_wrap_guides);
11457        cx.notify();
11458    }
11459
11460    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11461        self.show_indent_guides = Some(show_indent_guides);
11462        cx.notify();
11463    }
11464
11465    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11466        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11467            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11468                if let Some(dir) = file.abs_path(cx).parent() {
11469                    return Some(dir.to_owned());
11470                }
11471            }
11472
11473            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11474                return Some(project_path.path.to_path_buf());
11475            }
11476        }
11477
11478        None
11479    }
11480
11481    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11482        self.active_excerpt(cx)?
11483            .1
11484            .read(cx)
11485            .file()
11486            .and_then(|f| f.as_local())
11487    }
11488
11489    fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11490        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11491            let project_path = buffer.read(cx).project_path(cx)?;
11492            let project = self.project.as_ref()?.read(cx);
11493            project.absolute_path(&project_path, cx)
11494        })
11495    }
11496
11497    fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11498        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11499            let project_path = buffer.read(cx).project_path(cx)?;
11500            let project = self.project.as_ref()?.read(cx);
11501            let entry = project.entry_for_path(&project_path, cx)?;
11502            let path = entry.path.to_path_buf();
11503            Some(path)
11504        })
11505    }
11506
11507    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11508        if let Some(target) = self.target_file(cx) {
11509            cx.reveal_path(&target.abs_path(cx));
11510        }
11511    }
11512
11513    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11514        if let Some(path) = self.target_file_abs_path(cx) {
11515            if let Some(path) = path.to_str() {
11516                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11517            }
11518        }
11519    }
11520
11521    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11522        if let Some(path) = self.target_file_path(cx) {
11523            if let Some(path) = path.to_str() {
11524                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11525            }
11526        }
11527    }
11528
11529    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11530        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11531
11532        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11533            self.start_git_blame(true, cx);
11534        }
11535
11536        cx.notify();
11537    }
11538
11539    pub fn toggle_git_blame_inline(
11540        &mut self,
11541        _: &ToggleGitBlameInline,
11542        cx: &mut ViewContext<Self>,
11543    ) {
11544        self.toggle_git_blame_inline_internal(true, cx);
11545        cx.notify();
11546    }
11547
11548    pub fn git_blame_inline_enabled(&self) -> bool {
11549        self.git_blame_inline_enabled
11550    }
11551
11552    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11553        self.show_selection_menu = self
11554            .show_selection_menu
11555            .map(|show_selections_menu| !show_selections_menu)
11556            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11557
11558        cx.notify();
11559    }
11560
11561    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11562        self.show_selection_menu
11563            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11564    }
11565
11566    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11567        if let Some(project) = self.project.as_ref() {
11568            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11569                return;
11570            };
11571
11572            if buffer.read(cx).file().is_none() {
11573                return;
11574            }
11575
11576            let focused = self.focus_handle(cx).contains_focused(cx);
11577
11578            let project = project.clone();
11579            let blame =
11580                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11581            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11582            self.blame = Some(blame);
11583        }
11584    }
11585
11586    fn toggle_git_blame_inline_internal(
11587        &mut self,
11588        user_triggered: bool,
11589        cx: &mut ViewContext<Self>,
11590    ) {
11591        if self.git_blame_inline_enabled {
11592            self.git_blame_inline_enabled = false;
11593            self.show_git_blame_inline = false;
11594            self.show_git_blame_inline_delay_task.take();
11595        } else {
11596            self.git_blame_inline_enabled = true;
11597            self.start_git_blame_inline(user_triggered, cx);
11598        }
11599
11600        cx.notify();
11601    }
11602
11603    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11604        self.start_git_blame(user_triggered, cx);
11605
11606        if ProjectSettings::get_global(cx)
11607            .git
11608            .inline_blame_delay()
11609            .is_some()
11610        {
11611            self.start_inline_blame_timer(cx);
11612        } else {
11613            self.show_git_blame_inline = true
11614        }
11615    }
11616
11617    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11618        self.blame.as_ref()
11619    }
11620
11621    pub fn show_git_blame_gutter(&self) -> bool {
11622        self.show_git_blame_gutter
11623    }
11624
11625    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11626        self.show_git_blame_gutter && self.has_blame_entries(cx)
11627    }
11628
11629    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11630        self.show_git_blame_inline
11631            && self.focus_handle.is_focused(cx)
11632            && !self.newest_selection_head_on_empty_line(cx)
11633            && self.has_blame_entries(cx)
11634    }
11635
11636    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11637        self.blame()
11638            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11639    }
11640
11641    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11642        let cursor_anchor = self.selections.newest_anchor().head();
11643
11644        let snapshot = self.buffer.read(cx).snapshot(cx);
11645        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11646
11647        snapshot.line_len(buffer_row) == 0
11648    }
11649
11650    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11651        let buffer_and_selection = maybe!({
11652            let selection = self.selections.newest::<Point>(cx);
11653            let selection_range = selection.range();
11654
11655            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11656                (buffer, selection_range.start.row..selection_range.end.row)
11657            } else {
11658                let multi_buffer = self.buffer().read(cx);
11659                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11660                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11661
11662                let (excerpt, range) = if selection.reversed {
11663                    buffer_ranges.first()
11664                } else {
11665                    buffer_ranges.last()
11666                }?;
11667
11668                let snapshot = excerpt.buffer();
11669                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11670                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11671                (
11672                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11673                    selection,
11674                )
11675            };
11676
11677            Some((buffer, selection))
11678        });
11679
11680        let Some((buffer, selection)) = buffer_and_selection else {
11681            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11682        };
11683
11684        let Some(project) = self.project.as_ref() else {
11685            return Task::ready(Err(anyhow!("editor does not have project")));
11686        };
11687
11688        project.update(cx, |project, cx| {
11689            project.get_permalink_to_line(&buffer, selection, cx)
11690        })
11691    }
11692
11693    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11694        let permalink_task = self.get_permalink_to_line(cx);
11695        let workspace = self.workspace();
11696
11697        cx.spawn(|_, mut cx| async move {
11698            match permalink_task.await {
11699                Ok(permalink) => {
11700                    cx.update(|cx| {
11701                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11702                    })
11703                    .ok();
11704                }
11705                Err(err) => {
11706                    let message = format!("Failed to copy permalink: {err}");
11707
11708                    Err::<(), anyhow::Error>(err).log_err();
11709
11710                    if let Some(workspace) = workspace {
11711                        workspace
11712                            .update(&mut cx, |workspace, cx| {
11713                                struct CopyPermalinkToLine;
11714
11715                                workspace.show_toast(
11716                                    Toast::new(
11717                                        NotificationId::unique::<CopyPermalinkToLine>(),
11718                                        message,
11719                                    ),
11720                                    cx,
11721                                )
11722                            })
11723                            .ok();
11724                    }
11725                }
11726            }
11727        })
11728        .detach();
11729    }
11730
11731    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11732        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11733        if let Some(file) = self.target_file(cx) {
11734            if let Some(path) = file.path().to_str() {
11735                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11736            }
11737        }
11738    }
11739
11740    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11741        let permalink_task = self.get_permalink_to_line(cx);
11742        let workspace = self.workspace();
11743
11744        cx.spawn(|_, mut cx| async move {
11745            match permalink_task.await {
11746                Ok(permalink) => {
11747                    cx.update(|cx| {
11748                        cx.open_url(permalink.as_ref());
11749                    })
11750                    .ok();
11751                }
11752                Err(err) => {
11753                    let message = format!("Failed to open permalink: {err}");
11754
11755                    Err::<(), anyhow::Error>(err).log_err();
11756
11757                    if let Some(workspace) = workspace {
11758                        workspace
11759                            .update(&mut cx, |workspace, cx| {
11760                                struct OpenPermalinkToLine;
11761
11762                                workspace.show_toast(
11763                                    Toast::new(
11764                                        NotificationId::unique::<OpenPermalinkToLine>(),
11765                                        message,
11766                                    ),
11767                                    cx,
11768                                )
11769                            })
11770                            .ok();
11771                    }
11772                }
11773            }
11774        })
11775        .detach();
11776    }
11777
11778    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11779        self.insert_uuid(UuidVersion::V4, cx);
11780    }
11781
11782    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11783        self.insert_uuid(UuidVersion::V7, cx);
11784    }
11785
11786    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11787        self.transact(cx, |this, cx| {
11788            let edits = this
11789                .selections
11790                .all::<Point>(cx)
11791                .into_iter()
11792                .map(|selection| {
11793                    let uuid = match version {
11794                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11795                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11796                    };
11797
11798                    (selection.range(), uuid.to_string())
11799                });
11800            this.edit(edits, cx);
11801            this.refresh_inline_completion(true, false, cx);
11802        });
11803    }
11804
11805    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11806    /// last highlight added will be used.
11807    ///
11808    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11809    pub fn highlight_rows<T: 'static>(
11810        &mut self,
11811        range: Range<Anchor>,
11812        color: Hsla,
11813        should_autoscroll: bool,
11814        cx: &mut ViewContext<Self>,
11815    ) {
11816        let snapshot = self.buffer().read(cx).snapshot(cx);
11817        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11818        let ix = row_highlights.binary_search_by(|highlight| {
11819            Ordering::Equal
11820                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11821                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11822        });
11823
11824        if let Err(mut ix) = ix {
11825            let index = post_inc(&mut self.highlight_order);
11826
11827            // If this range intersects with the preceding highlight, then merge it with
11828            // the preceding highlight. Otherwise insert a new highlight.
11829            let mut merged = false;
11830            if ix > 0 {
11831                let prev_highlight = &mut row_highlights[ix - 1];
11832                if prev_highlight
11833                    .range
11834                    .end
11835                    .cmp(&range.start, &snapshot)
11836                    .is_ge()
11837                {
11838                    ix -= 1;
11839                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11840                        prev_highlight.range.end = range.end;
11841                    }
11842                    merged = true;
11843                    prev_highlight.index = index;
11844                    prev_highlight.color = color;
11845                    prev_highlight.should_autoscroll = should_autoscroll;
11846                }
11847            }
11848
11849            if !merged {
11850                row_highlights.insert(
11851                    ix,
11852                    RowHighlight {
11853                        range: range.clone(),
11854                        index,
11855                        color,
11856                        should_autoscroll,
11857                    },
11858                );
11859            }
11860
11861            // If any of the following highlights intersect with this one, merge them.
11862            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11863                let highlight = &row_highlights[ix];
11864                if next_highlight
11865                    .range
11866                    .start
11867                    .cmp(&highlight.range.end, &snapshot)
11868                    .is_le()
11869                {
11870                    if next_highlight
11871                        .range
11872                        .end
11873                        .cmp(&highlight.range.end, &snapshot)
11874                        .is_gt()
11875                    {
11876                        row_highlights[ix].range.end = next_highlight.range.end;
11877                    }
11878                    row_highlights.remove(ix + 1);
11879                } else {
11880                    break;
11881                }
11882            }
11883        }
11884    }
11885
11886    /// Remove any highlighted row ranges of the given type that intersect the
11887    /// given ranges.
11888    pub fn remove_highlighted_rows<T: 'static>(
11889        &mut self,
11890        ranges_to_remove: Vec<Range<Anchor>>,
11891        cx: &mut ViewContext<Self>,
11892    ) {
11893        let snapshot = self.buffer().read(cx).snapshot(cx);
11894        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11895        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11896        row_highlights.retain(|highlight| {
11897            while let Some(range_to_remove) = ranges_to_remove.peek() {
11898                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11899                    Ordering::Less | Ordering::Equal => {
11900                        ranges_to_remove.next();
11901                    }
11902                    Ordering::Greater => {
11903                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11904                            Ordering::Less | Ordering::Equal => {
11905                                return false;
11906                            }
11907                            Ordering::Greater => break,
11908                        }
11909                    }
11910                }
11911            }
11912
11913            true
11914        })
11915    }
11916
11917    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11918    pub fn clear_row_highlights<T: 'static>(&mut self) {
11919        self.highlighted_rows.remove(&TypeId::of::<T>());
11920    }
11921
11922    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11923    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11924        self.highlighted_rows
11925            .get(&TypeId::of::<T>())
11926            .map_or(&[] as &[_], |vec| vec.as_slice())
11927            .iter()
11928            .map(|highlight| (highlight.range.clone(), highlight.color))
11929    }
11930
11931    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11932    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11933    /// Allows to ignore certain kinds of highlights.
11934    pub fn highlighted_display_rows(
11935        &mut self,
11936        cx: &mut WindowContext,
11937    ) -> BTreeMap<DisplayRow, Hsla> {
11938        let snapshot = self.snapshot(cx);
11939        let mut used_highlight_orders = HashMap::default();
11940        self.highlighted_rows
11941            .iter()
11942            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11943            .fold(
11944                BTreeMap::<DisplayRow, Hsla>::new(),
11945                |mut unique_rows, highlight| {
11946                    let start = highlight.range.start.to_display_point(&snapshot);
11947                    let end = highlight.range.end.to_display_point(&snapshot);
11948                    let start_row = start.row().0;
11949                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11950                        && end.column() == 0
11951                    {
11952                        end.row().0.saturating_sub(1)
11953                    } else {
11954                        end.row().0
11955                    };
11956                    for row in start_row..=end_row {
11957                        let used_index =
11958                            used_highlight_orders.entry(row).or_insert(highlight.index);
11959                        if highlight.index >= *used_index {
11960                            *used_index = highlight.index;
11961                            unique_rows.insert(DisplayRow(row), highlight.color);
11962                        }
11963                    }
11964                    unique_rows
11965                },
11966            )
11967    }
11968
11969    pub fn highlighted_display_row_for_autoscroll(
11970        &self,
11971        snapshot: &DisplaySnapshot,
11972    ) -> Option<DisplayRow> {
11973        self.highlighted_rows
11974            .values()
11975            .flat_map(|highlighted_rows| highlighted_rows.iter())
11976            .filter_map(|highlight| {
11977                if highlight.should_autoscroll {
11978                    Some(highlight.range.start.to_display_point(snapshot).row())
11979                } else {
11980                    None
11981                }
11982            })
11983            .min()
11984    }
11985
11986    pub fn set_search_within_ranges(
11987        &mut self,
11988        ranges: &[Range<Anchor>],
11989        cx: &mut ViewContext<Self>,
11990    ) {
11991        self.highlight_background::<SearchWithinRange>(
11992            ranges,
11993            |colors| colors.editor_document_highlight_read_background,
11994            cx,
11995        )
11996    }
11997
11998    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11999        self.breadcrumb_header = Some(new_header);
12000    }
12001
12002    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12003        self.clear_background_highlights::<SearchWithinRange>(cx);
12004    }
12005
12006    pub fn highlight_background<T: 'static>(
12007        &mut self,
12008        ranges: &[Range<Anchor>],
12009        color_fetcher: fn(&ThemeColors) -> Hsla,
12010        cx: &mut ViewContext<Self>,
12011    ) {
12012        self.background_highlights
12013            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12014        self.scrollbar_marker_state.dirty = true;
12015        cx.notify();
12016    }
12017
12018    pub fn clear_background_highlights<T: 'static>(
12019        &mut self,
12020        cx: &mut ViewContext<Self>,
12021    ) -> Option<BackgroundHighlight> {
12022        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12023        if !text_highlights.1.is_empty() {
12024            self.scrollbar_marker_state.dirty = true;
12025            cx.notify();
12026        }
12027        Some(text_highlights)
12028    }
12029
12030    pub fn highlight_gutter<T: 'static>(
12031        &mut self,
12032        ranges: &[Range<Anchor>],
12033        color_fetcher: fn(&AppContext) -> Hsla,
12034        cx: &mut ViewContext<Self>,
12035    ) {
12036        self.gutter_highlights
12037            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12038        cx.notify();
12039    }
12040
12041    pub fn clear_gutter_highlights<T: 'static>(
12042        &mut self,
12043        cx: &mut ViewContext<Self>,
12044    ) -> Option<GutterHighlight> {
12045        cx.notify();
12046        self.gutter_highlights.remove(&TypeId::of::<T>())
12047    }
12048
12049    #[cfg(feature = "test-support")]
12050    pub fn all_text_background_highlights(
12051        &mut self,
12052        cx: &mut ViewContext<Self>,
12053    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12054        let snapshot = self.snapshot(cx);
12055        let buffer = &snapshot.buffer_snapshot;
12056        let start = buffer.anchor_before(0);
12057        let end = buffer.anchor_after(buffer.len());
12058        let theme = cx.theme().colors();
12059        self.background_highlights_in_range(start..end, &snapshot, theme)
12060    }
12061
12062    #[cfg(feature = "test-support")]
12063    pub fn search_background_highlights(
12064        &mut self,
12065        cx: &mut ViewContext<Self>,
12066    ) -> Vec<Range<Point>> {
12067        let snapshot = self.buffer().read(cx).snapshot(cx);
12068
12069        let highlights = self
12070            .background_highlights
12071            .get(&TypeId::of::<items::BufferSearchHighlights>());
12072
12073        if let Some((_color, ranges)) = highlights {
12074            ranges
12075                .iter()
12076                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12077                .collect_vec()
12078        } else {
12079            vec![]
12080        }
12081    }
12082
12083    fn document_highlights_for_position<'a>(
12084        &'a self,
12085        position: Anchor,
12086        buffer: &'a MultiBufferSnapshot,
12087    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12088        let read_highlights = self
12089            .background_highlights
12090            .get(&TypeId::of::<DocumentHighlightRead>())
12091            .map(|h| &h.1);
12092        let write_highlights = self
12093            .background_highlights
12094            .get(&TypeId::of::<DocumentHighlightWrite>())
12095            .map(|h| &h.1);
12096        let left_position = position.bias_left(buffer);
12097        let right_position = position.bias_right(buffer);
12098        read_highlights
12099            .into_iter()
12100            .chain(write_highlights)
12101            .flat_map(move |ranges| {
12102                let start_ix = match ranges.binary_search_by(|probe| {
12103                    let cmp = probe.end.cmp(&left_position, buffer);
12104                    if cmp.is_ge() {
12105                        Ordering::Greater
12106                    } else {
12107                        Ordering::Less
12108                    }
12109                }) {
12110                    Ok(i) | Err(i) => i,
12111                };
12112
12113                ranges[start_ix..]
12114                    .iter()
12115                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12116            })
12117    }
12118
12119    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12120        self.background_highlights
12121            .get(&TypeId::of::<T>())
12122            .map_or(false, |(_, highlights)| !highlights.is_empty())
12123    }
12124
12125    pub fn background_highlights_in_range(
12126        &self,
12127        search_range: Range<Anchor>,
12128        display_snapshot: &DisplaySnapshot,
12129        theme: &ThemeColors,
12130    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12131        let mut results = Vec::new();
12132        for (color_fetcher, ranges) in self.background_highlights.values() {
12133            let color = color_fetcher(theme);
12134            let start_ix = match ranges.binary_search_by(|probe| {
12135                let cmp = probe
12136                    .end
12137                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12138                if cmp.is_gt() {
12139                    Ordering::Greater
12140                } else {
12141                    Ordering::Less
12142                }
12143            }) {
12144                Ok(i) | Err(i) => i,
12145            };
12146            for range in &ranges[start_ix..] {
12147                if range
12148                    .start
12149                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12150                    .is_ge()
12151                {
12152                    break;
12153                }
12154
12155                let start = range.start.to_display_point(display_snapshot);
12156                let end = range.end.to_display_point(display_snapshot);
12157                results.push((start..end, color))
12158            }
12159        }
12160        results
12161    }
12162
12163    pub fn background_highlight_row_ranges<T: 'static>(
12164        &self,
12165        search_range: Range<Anchor>,
12166        display_snapshot: &DisplaySnapshot,
12167        count: usize,
12168    ) -> Vec<RangeInclusive<DisplayPoint>> {
12169        let mut results = Vec::new();
12170        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12171            return vec![];
12172        };
12173
12174        let start_ix = match ranges.binary_search_by(|probe| {
12175            let cmp = probe
12176                .end
12177                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12178            if cmp.is_gt() {
12179                Ordering::Greater
12180            } else {
12181                Ordering::Less
12182            }
12183        }) {
12184            Ok(i) | Err(i) => i,
12185        };
12186        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12187            if let (Some(start_display), Some(end_display)) = (start, end) {
12188                results.push(
12189                    start_display.to_display_point(display_snapshot)
12190                        ..=end_display.to_display_point(display_snapshot),
12191                );
12192            }
12193        };
12194        let mut start_row: Option<Point> = None;
12195        let mut end_row: Option<Point> = None;
12196        if ranges.len() > count {
12197            return Vec::new();
12198        }
12199        for range in &ranges[start_ix..] {
12200            if range
12201                .start
12202                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12203                .is_ge()
12204            {
12205                break;
12206            }
12207            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12208            if let Some(current_row) = &end_row {
12209                if end.row == current_row.row {
12210                    continue;
12211                }
12212            }
12213            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12214            if start_row.is_none() {
12215                assert_eq!(end_row, None);
12216                start_row = Some(start);
12217                end_row = Some(end);
12218                continue;
12219            }
12220            if let Some(current_end) = end_row.as_mut() {
12221                if start.row > current_end.row + 1 {
12222                    push_region(start_row, end_row);
12223                    start_row = Some(start);
12224                    end_row = Some(end);
12225                } else {
12226                    // Merge two hunks.
12227                    *current_end = end;
12228                }
12229            } else {
12230                unreachable!();
12231            }
12232        }
12233        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12234        push_region(start_row, end_row);
12235        results
12236    }
12237
12238    pub fn gutter_highlights_in_range(
12239        &self,
12240        search_range: Range<Anchor>,
12241        display_snapshot: &DisplaySnapshot,
12242        cx: &AppContext,
12243    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12244        let mut results = Vec::new();
12245        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12246            let color = color_fetcher(cx);
12247            let start_ix = match ranges.binary_search_by(|probe| {
12248                let cmp = probe
12249                    .end
12250                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12251                if cmp.is_gt() {
12252                    Ordering::Greater
12253                } else {
12254                    Ordering::Less
12255                }
12256            }) {
12257                Ok(i) | Err(i) => i,
12258            };
12259            for range in &ranges[start_ix..] {
12260                if range
12261                    .start
12262                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12263                    .is_ge()
12264                {
12265                    break;
12266                }
12267
12268                let start = range.start.to_display_point(display_snapshot);
12269                let end = range.end.to_display_point(display_snapshot);
12270                results.push((start..end, color))
12271            }
12272        }
12273        results
12274    }
12275
12276    /// Get the text ranges corresponding to the redaction query
12277    pub fn redacted_ranges(
12278        &self,
12279        search_range: Range<Anchor>,
12280        display_snapshot: &DisplaySnapshot,
12281        cx: &WindowContext,
12282    ) -> Vec<Range<DisplayPoint>> {
12283        display_snapshot
12284            .buffer_snapshot
12285            .redacted_ranges(search_range, |file| {
12286                if let Some(file) = file {
12287                    file.is_private()
12288                        && EditorSettings::get(
12289                            Some(SettingsLocation {
12290                                worktree_id: file.worktree_id(cx),
12291                                path: file.path().as_ref(),
12292                            }),
12293                            cx,
12294                        )
12295                        .redact_private_values
12296                } else {
12297                    false
12298                }
12299            })
12300            .map(|range| {
12301                range.start.to_display_point(display_snapshot)
12302                    ..range.end.to_display_point(display_snapshot)
12303            })
12304            .collect()
12305    }
12306
12307    pub fn highlight_text<T: 'static>(
12308        &mut self,
12309        ranges: Vec<Range<Anchor>>,
12310        style: HighlightStyle,
12311        cx: &mut ViewContext<Self>,
12312    ) {
12313        self.display_map.update(cx, |map, _| {
12314            map.highlight_text(TypeId::of::<T>(), ranges, style)
12315        });
12316        cx.notify();
12317    }
12318
12319    pub(crate) fn highlight_inlays<T: 'static>(
12320        &mut self,
12321        highlights: Vec<InlayHighlight>,
12322        style: HighlightStyle,
12323        cx: &mut ViewContext<Self>,
12324    ) {
12325        self.display_map.update(cx, |map, _| {
12326            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12327        });
12328        cx.notify();
12329    }
12330
12331    pub fn text_highlights<'a, T: 'static>(
12332        &'a self,
12333        cx: &'a AppContext,
12334    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12335        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12336    }
12337
12338    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12339        let cleared = self
12340            .display_map
12341            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12342        if cleared {
12343            cx.notify();
12344        }
12345    }
12346
12347    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12348        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12349            && self.focus_handle.is_focused(cx)
12350    }
12351
12352    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12353        self.show_cursor_when_unfocused = is_enabled;
12354        cx.notify();
12355    }
12356
12357    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12358        self.project
12359            .as_ref()
12360            .map(|project| project.read(cx).lsp_store())
12361    }
12362
12363    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12364        cx.notify();
12365    }
12366
12367    fn on_buffer_event(
12368        &mut self,
12369        multibuffer: Model<MultiBuffer>,
12370        event: &multi_buffer::Event,
12371        cx: &mut ViewContext<Self>,
12372    ) {
12373        match event {
12374            multi_buffer::Event::Edited {
12375                singleton_buffer_edited,
12376                edited_buffer: buffer_edited,
12377            } => {
12378                self.scrollbar_marker_state.dirty = true;
12379                self.active_indent_guides_state.dirty = true;
12380                self.refresh_active_diagnostics(cx);
12381                self.refresh_code_actions(cx);
12382                if self.has_active_inline_completion() {
12383                    self.update_visible_inline_completion(cx);
12384                }
12385                if let Some(buffer) = buffer_edited {
12386                    let buffer_id = buffer.read(cx).remote_id();
12387                    if !self.registered_buffers.contains_key(&buffer_id) {
12388                        if let Some(lsp_store) = self.lsp_store(cx) {
12389                            lsp_store.update(cx, |lsp_store, cx| {
12390                                self.registered_buffers.insert(
12391                                    buffer_id,
12392                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12393                                );
12394                            })
12395                        }
12396                    }
12397                }
12398                cx.emit(EditorEvent::BufferEdited);
12399                cx.emit(SearchEvent::MatchesInvalidated);
12400                if *singleton_buffer_edited {
12401                    if let Some(project) = &self.project {
12402                        let project = project.read(cx);
12403                        #[allow(clippy::mutable_key_type)]
12404                        let languages_affected = multibuffer
12405                            .read(cx)
12406                            .all_buffers()
12407                            .into_iter()
12408                            .filter_map(|buffer| {
12409                                let buffer = buffer.read(cx);
12410                                let language = buffer.language()?;
12411                                if project.is_local()
12412                                    && project
12413                                        .language_servers_for_local_buffer(buffer, cx)
12414                                        .count()
12415                                        == 0
12416                                {
12417                                    None
12418                                } else {
12419                                    Some(language)
12420                                }
12421                            })
12422                            .cloned()
12423                            .collect::<HashSet<_>>();
12424                        if !languages_affected.is_empty() {
12425                            self.refresh_inlay_hints(
12426                                InlayHintRefreshReason::BufferEdited(languages_affected),
12427                                cx,
12428                            );
12429                        }
12430                    }
12431                }
12432
12433                let Some(project) = &self.project else { return };
12434                let (telemetry, is_via_ssh) = {
12435                    let project = project.read(cx);
12436                    let telemetry = project.client().telemetry().clone();
12437                    let is_via_ssh = project.is_via_ssh();
12438                    (telemetry, is_via_ssh)
12439                };
12440                refresh_linked_ranges(self, cx);
12441                telemetry.log_edit_event("editor", is_via_ssh);
12442            }
12443            multi_buffer::Event::ExcerptsAdded {
12444                buffer,
12445                predecessor,
12446                excerpts,
12447            } => {
12448                self.tasks_update_task = Some(self.refresh_runnables(cx));
12449                let buffer_id = buffer.read(cx).remote_id();
12450                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12451                    if let Some(project) = &self.project {
12452                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12453                    }
12454                }
12455                cx.emit(EditorEvent::ExcerptsAdded {
12456                    buffer: buffer.clone(),
12457                    predecessor: *predecessor,
12458                    excerpts: excerpts.clone(),
12459                });
12460                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12461            }
12462            multi_buffer::Event::ExcerptsRemoved { ids } => {
12463                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12464                let buffer = self.buffer.read(cx);
12465                self.registered_buffers
12466                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12467                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12468            }
12469            multi_buffer::Event::ExcerptsEdited { ids } => {
12470                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12471            }
12472            multi_buffer::Event::ExcerptsExpanded { ids } => {
12473                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12474                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12475            }
12476            multi_buffer::Event::Reparsed(buffer_id) => {
12477                self.tasks_update_task = Some(self.refresh_runnables(cx));
12478
12479                cx.emit(EditorEvent::Reparsed(*buffer_id));
12480            }
12481            multi_buffer::Event::LanguageChanged(buffer_id) => {
12482                linked_editing_ranges::refresh_linked_ranges(self, cx);
12483                cx.emit(EditorEvent::Reparsed(*buffer_id));
12484                cx.notify();
12485            }
12486            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12487            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12488            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12489                cx.emit(EditorEvent::TitleChanged)
12490            }
12491            // multi_buffer::Event::DiffBaseChanged => {
12492            //     self.scrollbar_marker_state.dirty = true;
12493            //     cx.emit(EditorEvent::DiffBaseChanged);
12494            //     cx.notify();
12495            // }
12496            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12497            multi_buffer::Event::DiagnosticsUpdated => {
12498                self.refresh_active_diagnostics(cx);
12499                self.scrollbar_marker_state.dirty = true;
12500                cx.notify();
12501            }
12502            _ => {}
12503        };
12504    }
12505
12506    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12507        cx.notify();
12508    }
12509
12510    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12511        self.tasks_update_task = Some(self.refresh_runnables(cx));
12512        self.refresh_inline_completion(true, false, cx);
12513        self.refresh_inlay_hints(
12514            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12515                self.selections.newest_anchor().head(),
12516                &self.buffer.read(cx).snapshot(cx),
12517                cx,
12518            )),
12519            cx,
12520        );
12521
12522        let old_cursor_shape = self.cursor_shape;
12523
12524        {
12525            let editor_settings = EditorSettings::get_global(cx);
12526            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12527            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12528            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12529        }
12530
12531        if old_cursor_shape != self.cursor_shape {
12532            cx.emit(EditorEvent::CursorShapeChanged);
12533        }
12534
12535        let project_settings = ProjectSettings::get_global(cx);
12536        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12537
12538        if self.mode == EditorMode::Full {
12539            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12540            if self.git_blame_inline_enabled != inline_blame_enabled {
12541                self.toggle_git_blame_inline_internal(false, cx);
12542            }
12543        }
12544
12545        cx.notify();
12546    }
12547
12548    pub fn set_searchable(&mut self, searchable: bool) {
12549        self.searchable = searchable;
12550    }
12551
12552    pub fn searchable(&self) -> bool {
12553        self.searchable
12554    }
12555
12556    fn open_proposed_changes_editor(
12557        &mut self,
12558        _: &OpenProposedChangesEditor,
12559        cx: &mut ViewContext<Self>,
12560    ) {
12561        let Some(workspace) = self.workspace() else {
12562            cx.propagate();
12563            return;
12564        };
12565
12566        let selections = self.selections.all::<usize>(cx);
12567        let multi_buffer = self.buffer.read(cx);
12568        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12569        let mut new_selections_by_buffer = HashMap::default();
12570        for selection in selections {
12571            for (excerpt, range) in
12572                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12573            {
12574                let mut range = range.to_point(excerpt.buffer());
12575                range.start.column = 0;
12576                range.end.column = excerpt.buffer().line_len(range.end.row);
12577                new_selections_by_buffer
12578                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12579                    .or_insert(Vec::new())
12580                    .push(range)
12581            }
12582        }
12583
12584        let proposed_changes_buffers = new_selections_by_buffer
12585            .into_iter()
12586            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12587            .collect::<Vec<_>>();
12588        let proposed_changes_editor = cx.new_view(|cx| {
12589            ProposedChangesEditor::new(
12590                "Proposed changes",
12591                proposed_changes_buffers,
12592                self.project.clone(),
12593                cx,
12594            )
12595        });
12596
12597        cx.window_context().defer(move |cx| {
12598            workspace.update(cx, |workspace, cx| {
12599                workspace.active_pane().update(cx, |pane, cx| {
12600                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12601                });
12602            });
12603        });
12604    }
12605
12606    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12607        self.open_excerpts_common(None, true, cx)
12608    }
12609
12610    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12611        self.open_excerpts_common(None, false, cx)
12612    }
12613
12614    fn open_excerpts_common(
12615        &mut self,
12616        jump_data: Option<JumpData>,
12617        split: bool,
12618        cx: &mut ViewContext<Self>,
12619    ) {
12620        let Some(workspace) = self.workspace() else {
12621            cx.propagate();
12622            return;
12623        };
12624
12625        if self.buffer.read(cx).is_singleton() {
12626            cx.propagate();
12627            return;
12628        }
12629
12630        let mut new_selections_by_buffer = HashMap::default();
12631        match &jump_data {
12632            Some(JumpData::MultiBufferPoint {
12633                excerpt_id,
12634                position,
12635                anchor,
12636                line_offset_from_top,
12637            }) => {
12638                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12639                if let Some(buffer) = multi_buffer_snapshot
12640                    .buffer_id_for_excerpt(*excerpt_id)
12641                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12642                {
12643                    let buffer_snapshot = buffer.read(cx).snapshot();
12644                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12645                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12646                    } else {
12647                        buffer_snapshot.clip_point(*position, Bias::Left)
12648                    };
12649                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12650                    new_selections_by_buffer.insert(
12651                        buffer,
12652                        (
12653                            vec![jump_to_offset..jump_to_offset],
12654                            Some(*line_offset_from_top),
12655                        ),
12656                    );
12657                }
12658            }
12659            Some(JumpData::MultiBufferRow {
12660                row,
12661                line_offset_from_top,
12662            }) => {
12663                let point = MultiBufferPoint::new(row.0, 0);
12664                if let Some((buffer, buffer_point, _)) =
12665                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12666                {
12667                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12668                    new_selections_by_buffer
12669                        .entry(buffer)
12670                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12671                        .0
12672                        .push(buffer_offset..buffer_offset)
12673                }
12674            }
12675            None => {
12676                let selections = self.selections.all::<usize>(cx);
12677                let multi_buffer = self.buffer.read(cx);
12678                for selection in selections {
12679                    for (excerpt, mut range) in multi_buffer
12680                        .snapshot(cx)
12681                        .range_to_buffer_ranges(selection.range())
12682                    {
12683                        // When editing branch buffers, jump to the corresponding location
12684                        // in their base buffer.
12685                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12686                        let buffer = buffer_handle.read(cx);
12687                        if let Some(base_buffer) = buffer.base_buffer() {
12688                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12689                            buffer_handle = base_buffer;
12690                        }
12691
12692                        if selection.reversed {
12693                            mem::swap(&mut range.start, &mut range.end);
12694                        }
12695                        new_selections_by_buffer
12696                            .entry(buffer_handle)
12697                            .or_insert((Vec::new(), None))
12698                            .0
12699                            .push(range)
12700                    }
12701                }
12702            }
12703        }
12704
12705        if new_selections_by_buffer.is_empty() {
12706            return;
12707        }
12708
12709        // We defer the pane interaction because we ourselves are a workspace item
12710        // and activating a new item causes the pane to call a method on us reentrantly,
12711        // which panics if we're on the stack.
12712        cx.window_context().defer(move |cx| {
12713            workspace.update(cx, |workspace, cx| {
12714                let pane = if split {
12715                    workspace.adjacent_pane(cx)
12716                } else {
12717                    workspace.active_pane().clone()
12718                };
12719
12720                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12721                    let editor = buffer
12722                        .read(cx)
12723                        .file()
12724                        .is_none()
12725                        .then(|| {
12726                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12727                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12728                            // Instead, we try to activate the existing editor in the pane first.
12729                            let (editor, pane_item_index) =
12730                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12731                                    let editor = item.downcast::<Editor>()?;
12732                                    let singleton_buffer =
12733                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12734                                    if singleton_buffer == buffer {
12735                                        Some((editor, i))
12736                                    } else {
12737                                        None
12738                                    }
12739                                })?;
12740                            pane.update(cx, |pane, cx| {
12741                                pane.activate_item(pane_item_index, true, true, cx)
12742                            });
12743                            Some(editor)
12744                        })
12745                        .flatten()
12746                        .unwrap_or_else(|| {
12747                            workspace.open_project_item::<Self>(
12748                                pane.clone(),
12749                                buffer,
12750                                true,
12751                                true,
12752                                cx,
12753                            )
12754                        });
12755
12756                    editor.update(cx, |editor, cx| {
12757                        let autoscroll = match scroll_offset {
12758                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12759                            None => Autoscroll::newest(),
12760                        };
12761                        let nav_history = editor.nav_history.take();
12762                        editor.change_selections(Some(autoscroll), cx, |s| {
12763                            s.select_ranges(ranges);
12764                        });
12765                        editor.nav_history = nav_history;
12766                    });
12767                }
12768            })
12769        });
12770    }
12771
12772    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12773        let snapshot = self.buffer.read(cx).read(cx);
12774        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12775        Some(
12776            ranges
12777                .iter()
12778                .map(move |range| {
12779                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12780                })
12781                .collect(),
12782        )
12783    }
12784
12785    fn selection_replacement_ranges(
12786        &self,
12787        range: Range<OffsetUtf16>,
12788        cx: &mut AppContext,
12789    ) -> Vec<Range<OffsetUtf16>> {
12790        let selections = self.selections.all::<OffsetUtf16>(cx);
12791        let newest_selection = selections
12792            .iter()
12793            .max_by_key(|selection| selection.id)
12794            .unwrap();
12795        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12796        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12797        let snapshot = self.buffer.read(cx).read(cx);
12798        selections
12799            .into_iter()
12800            .map(|mut selection| {
12801                selection.start.0 =
12802                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12803                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12804                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12805                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12806            })
12807            .collect()
12808    }
12809
12810    fn report_editor_event(
12811        &self,
12812        event_type: &'static str,
12813        file_extension: Option<String>,
12814        cx: &AppContext,
12815    ) {
12816        if cfg!(any(test, feature = "test-support")) {
12817            return;
12818        }
12819
12820        let Some(project) = &self.project else { return };
12821
12822        // If None, we are in a file without an extension
12823        let file = self
12824            .buffer
12825            .read(cx)
12826            .as_singleton()
12827            .and_then(|b| b.read(cx).file());
12828        let file_extension = file_extension.or(file
12829            .as_ref()
12830            .and_then(|file| Path::new(file.file_name(cx)).extension())
12831            .and_then(|e| e.to_str())
12832            .map(|a| a.to_string()));
12833
12834        let vim_mode = cx
12835            .global::<SettingsStore>()
12836            .raw_user_settings()
12837            .get("vim_mode")
12838            == Some(&serde_json::Value::Bool(true));
12839
12840        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12841            == language::language_settings::InlineCompletionProvider::Copilot;
12842        let copilot_enabled_for_language = self
12843            .buffer
12844            .read(cx)
12845            .settings_at(0, cx)
12846            .show_inline_completions;
12847
12848        let project = project.read(cx);
12849        telemetry::event!(
12850            event_type,
12851            file_extension,
12852            vim_mode,
12853            copilot_enabled,
12854            copilot_enabled_for_language,
12855            is_via_ssh = project.is_via_ssh(),
12856        );
12857    }
12858
12859    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12860    /// with each line being an array of {text, highlight} objects.
12861    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12862        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12863            return;
12864        };
12865
12866        #[derive(Serialize)]
12867        struct Chunk<'a> {
12868            text: String,
12869            highlight: Option<&'a str>,
12870        }
12871
12872        let snapshot = buffer.read(cx).snapshot();
12873        let range = self
12874            .selected_text_range(false, cx)
12875            .and_then(|selection| {
12876                if selection.range.is_empty() {
12877                    None
12878                } else {
12879                    Some(selection.range)
12880                }
12881            })
12882            .unwrap_or_else(|| 0..snapshot.len());
12883
12884        let chunks = snapshot.chunks(range, true);
12885        let mut lines = Vec::new();
12886        let mut line: VecDeque<Chunk> = VecDeque::new();
12887
12888        let Some(style) = self.style.as_ref() else {
12889            return;
12890        };
12891
12892        for chunk in chunks {
12893            let highlight = chunk
12894                .syntax_highlight_id
12895                .and_then(|id| id.name(&style.syntax));
12896            let mut chunk_lines = chunk.text.split('\n').peekable();
12897            while let Some(text) = chunk_lines.next() {
12898                let mut merged_with_last_token = false;
12899                if let Some(last_token) = line.back_mut() {
12900                    if last_token.highlight == highlight {
12901                        last_token.text.push_str(text);
12902                        merged_with_last_token = true;
12903                    }
12904                }
12905
12906                if !merged_with_last_token {
12907                    line.push_back(Chunk {
12908                        text: text.into(),
12909                        highlight,
12910                    });
12911                }
12912
12913                if chunk_lines.peek().is_some() {
12914                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12915                        line.pop_front();
12916                    }
12917                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12918                        line.pop_back();
12919                    }
12920
12921                    lines.push(mem::take(&mut line));
12922                }
12923            }
12924        }
12925
12926        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12927            return;
12928        };
12929        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12930    }
12931
12932    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12933        self.request_autoscroll(Autoscroll::newest(), cx);
12934        let position = self.selections.newest_display(cx).start;
12935        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12936    }
12937
12938    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12939        &self.inlay_hint_cache
12940    }
12941
12942    pub fn replay_insert_event(
12943        &mut self,
12944        text: &str,
12945        relative_utf16_range: Option<Range<isize>>,
12946        cx: &mut ViewContext<Self>,
12947    ) {
12948        if !self.input_enabled {
12949            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12950            return;
12951        }
12952        if let Some(relative_utf16_range) = relative_utf16_range {
12953            let selections = self.selections.all::<OffsetUtf16>(cx);
12954            self.change_selections(None, cx, |s| {
12955                let new_ranges = selections.into_iter().map(|range| {
12956                    let start = OffsetUtf16(
12957                        range
12958                            .head()
12959                            .0
12960                            .saturating_add_signed(relative_utf16_range.start),
12961                    );
12962                    let end = OffsetUtf16(
12963                        range
12964                            .head()
12965                            .0
12966                            .saturating_add_signed(relative_utf16_range.end),
12967                    );
12968                    start..end
12969                });
12970                s.select_ranges(new_ranges);
12971            });
12972        }
12973
12974        self.handle_input(text, cx);
12975    }
12976
12977    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12978        let Some(provider) = self.semantics_provider.as_ref() else {
12979            return false;
12980        };
12981
12982        let mut supports = false;
12983        self.buffer().read(cx).for_each_buffer(|buffer| {
12984            supports |= provider.supports_inlay_hints(buffer, cx);
12985        });
12986        supports
12987    }
12988
12989    pub fn focus(&self, cx: &mut WindowContext) {
12990        cx.focus(&self.focus_handle)
12991    }
12992
12993    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12994        self.focus_handle.is_focused(cx)
12995    }
12996
12997    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12998        cx.emit(EditorEvent::Focused);
12999
13000        if let Some(descendant) = self
13001            .last_focused_descendant
13002            .take()
13003            .and_then(|descendant| descendant.upgrade())
13004        {
13005            cx.focus(&descendant);
13006        } else {
13007            if let Some(blame) = self.blame.as_ref() {
13008                blame.update(cx, GitBlame::focus)
13009            }
13010
13011            self.blink_manager.update(cx, BlinkManager::enable);
13012            self.show_cursor_names(cx);
13013            self.buffer.update(cx, |buffer, cx| {
13014                buffer.finalize_last_transaction(cx);
13015                if self.leader_peer_id.is_none() {
13016                    buffer.set_active_selections(
13017                        &self.selections.disjoint_anchors(),
13018                        self.selections.line_mode,
13019                        self.cursor_shape,
13020                        cx,
13021                    );
13022                }
13023            });
13024        }
13025    }
13026
13027    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13028        cx.emit(EditorEvent::FocusedIn)
13029    }
13030
13031    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13032        if event.blurred != self.focus_handle {
13033            self.last_focused_descendant = Some(event.blurred);
13034        }
13035    }
13036
13037    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13038        self.blink_manager.update(cx, BlinkManager::disable);
13039        self.buffer
13040            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13041
13042        if let Some(blame) = self.blame.as_ref() {
13043            blame.update(cx, GitBlame::blur)
13044        }
13045        if !self.hover_state.focused(cx) {
13046            hide_hover(self, cx);
13047        }
13048
13049        self.hide_context_menu(cx);
13050        cx.emit(EditorEvent::Blurred);
13051        cx.notify();
13052    }
13053
13054    pub fn register_action<A: Action>(
13055        &mut self,
13056        listener: impl Fn(&A, &mut WindowContext) + 'static,
13057    ) -> Subscription {
13058        let id = self.next_editor_action_id.post_inc();
13059        let listener = Arc::new(listener);
13060        self.editor_actions.borrow_mut().insert(
13061            id,
13062            Box::new(move |cx| {
13063                let cx = cx.window_context();
13064                let listener = listener.clone();
13065                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13066                    let action = action.downcast_ref().unwrap();
13067                    if phase == DispatchPhase::Bubble {
13068                        listener(action, cx)
13069                    }
13070                })
13071            }),
13072        );
13073
13074        let editor_actions = self.editor_actions.clone();
13075        Subscription::new(move || {
13076            editor_actions.borrow_mut().remove(&id);
13077        })
13078    }
13079
13080    pub fn file_header_size(&self) -> u32 {
13081        FILE_HEADER_HEIGHT
13082    }
13083
13084    pub fn revert(
13085        &mut self,
13086        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13087        cx: &mut ViewContext<Self>,
13088    ) {
13089        self.buffer().update(cx, |multi_buffer, cx| {
13090            for (buffer_id, changes) in revert_changes {
13091                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13092                    buffer.update(cx, |buffer, cx| {
13093                        buffer.edit(
13094                            changes.into_iter().map(|(range, text)| {
13095                                (range, text.to_string().map(Arc::<str>::from))
13096                            }),
13097                            None,
13098                            cx,
13099                        );
13100                    });
13101                }
13102            }
13103        });
13104        self.change_selections(None, cx, |selections| selections.refresh());
13105    }
13106
13107    pub fn to_pixel_point(
13108        &mut self,
13109        source: multi_buffer::Anchor,
13110        editor_snapshot: &EditorSnapshot,
13111        cx: &mut ViewContext<Self>,
13112    ) -> Option<gpui::Point<Pixels>> {
13113        let source_point = source.to_display_point(editor_snapshot);
13114        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13115    }
13116
13117    pub fn display_to_pixel_point(
13118        &self,
13119        source: DisplayPoint,
13120        editor_snapshot: &EditorSnapshot,
13121        cx: &WindowContext,
13122    ) -> Option<gpui::Point<Pixels>> {
13123        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13124        let text_layout_details = self.text_layout_details(cx);
13125        let scroll_top = text_layout_details
13126            .scroll_anchor
13127            .scroll_position(editor_snapshot)
13128            .y;
13129
13130        if source.row().as_f32() < scroll_top.floor() {
13131            return None;
13132        }
13133        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13134        let source_y = line_height * (source.row().as_f32() - scroll_top);
13135        Some(gpui::Point::new(source_x, source_y))
13136    }
13137
13138    pub fn has_active_completions_menu(&self) -> bool {
13139        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13140            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13141        })
13142    }
13143
13144    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13145        self.addons
13146            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13147    }
13148
13149    pub fn unregister_addon<T: Addon>(&mut self) {
13150        self.addons.remove(&std::any::TypeId::of::<T>());
13151    }
13152
13153    pub fn addon<T: Addon>(&self) -> Option<&T> {
13154        let type_id = std::any::TypeId::of::<T>();
13155        self.addons
13156            .get(&type_id)
13157            .and_then(|item| item.to_any().downcast_ref::<T>())
13158    }
13159
13160    pub fn add_change_set(
13161        &mut self,
13162        change_set: Model<BufferChangeSet>,
13163        cx: &mut ViewContext<Self>,
13164    ) {
13165        self.diff_map.add_change_set(change_set, cx);
13166    }
13167
13168    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13169        let text_layout_details = self.text_layout_details(cx);
13170        let style = &text_layout_details.editor_style;
13171        let font_id = cx.text_system().resolve_font(&style.text.font());
13172        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13173        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13174
13175        let em_width = cx
13176            .text_system()
13177            .typographic_bounds(font_id, font_size, 'm')
13178            .unwrap()
13179            .size
13180            .width;
13181
13182        gpui::Point::new(em_width, line_height)
13183    }
13184}
13185
13186fn get_unstaged_changes_for_buffers(
13187    project: &Model<Project>,
13188    buffers: impl IntoIterator<Item = Model<Buffer>>,
13189    cx: &mut ViewContext<Editor>,
13190) {
13191    let mut tasks = Vec::new();
13192    project.update(cx, |project, cx| {
13193        for buffer in buffers {
13194            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13195        }
13196    });
13197    cx.spawn(|this, mut cx| async move {
13198        let change_sets = futures::future::join_all(tasks).await;
13199        this.update(&mut cx, |this, cx| {
13200            for change_set in change_sets {
13201                if let Some(change_set) = change_set.log_err() {
13202                    this.diff_map.add_change_set(change_set, cx);
13203                }
13204            }
13205        })
13206        .ok();
13207    })
13208    .detach();
13209}
13210
13211fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13212    let tab_size = tab_size.get() as usize;
13213    let mut width = offset;
13214
13215    for ch in text.chars() {
13216        width += if ch == '\t' {
13217            tab_size - (width % tab_size)
13218        } else {
13219            1
13220        };
13221    }
13222
13223    width - offset
13224}
13225
13226#[cfg(test)]
13227mod tests {
13228    use super::*;
13229
13230    #[test]
13231    fn test_string_size_with_expanded_tabs() {
13232        let nz = |val| NonZeroU32::new(val).unwrap();
13233        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13234        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13235        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13236        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13237        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13238        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13239        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13240        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13241    }
13242}
13243
13244/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13245struct WordBreakingTokenizer<'a> {
13246    input: &'a str,
13247}
13248
13249impl<'a> WordBreakingTokenizer<'a> {
13250    fn new(input: &'a str) -> Self {
13251        Self { input }
13252    }
13253}
13254
13255fn is_char_ideographic(ch: char) -> bool {
13256    use unicode_script::Script::*;
13257    use unicode_script::UnicodeScript;
13258    matches!(ch.script(), Han | Tangut | Yi)
13259}
13260
13261fn is_grapheme_ideographic(text: &str) -> bool {
13262    text.chars().any(is_char_ideographic)
13263}
13264
13265fn is_grapheme_whitespace(text: &str) -> bool {
13266    text.chars().any(|x| x.is_whitespace())
13267}
13268
13269fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13270    text.chars().next().map_or(false, |ch| {
13271        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13272    })
13273}
13274
13275#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13276struct WordBreakToken<'a> {
13277    token: &'a str,
13278    grapheme_len: usize,
13279    is_whitespace: bool,
13280}
13281
13282impl<'a> Iterator for WordBreakingTokenizer<'a> {
13283    /// Yields a span, the count of graphemes in the token, and whether it was
13284    /// whitespace. Note that it also breaks at word boundaries.
13285    type Item = WordBreakToken<'a>;
13286
13287    fn next(&mut self) -> Option<Self::Item> {
13288        use unicode_segmentation::UnicodeSegmentation;
13289        if self.input.is_empty() {
13290            return None;
13291        }
13292
13293        let mut iter = self.input.graphemes(true).peekable();
13294        let mut offset = 0;
13295        let mut graphemes = 0;
13296        if let Some(first_grapheme) = iter.next() {
13297            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13298            offset += first_grapheme.len();
13299            graphemes += 1;
13300            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13301                if let Some(grapheme) = iter.peek().copied() {
13302                    if should_stay_with_preceding_ideograph(grapheme) {
13303                        offset += grapheme.len();
13304                        graphemes += 1;
13305                    }
13306                }
13307            } else {
13308                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13309                let mut next_word_bound = words.peek().copied();
13310                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13311                    next_word_bound = words.next();
13312                }
13313                while let Some(grapheme) = iter.peek().copied() {
13314                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13315                        break;
13316                    };
13317                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13318                        break;
13319                    };
13320                    offset += grapheme.len();
13321                    graphemes += 1;
13322                    iter.next();
13323                }
13324            }
13325            let token = &self.input[..offset];
13326            self.input = &self.input[offset..];
13327            if is_whitespace {
13328                Some(WordBreakToken {
13329                    token: " ",
13330                    grapheme_len: 1,
13331                    is_whitespace: true,
13332                })
13333            } else {
13334                Some(WordBreakToken {
13335                    token,
13336                    grapheme_len: graphemes,
13337                    is_whitespace: false,
13338                })
13339            }
13340        } else {
13341            None
13342        }
13343    }
13344}
13345
13346#[test]
13347fn test_word_breaking_tokenizer() {
13348    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13349        ("", &[]),
13350        ("  ", &[(" ", 1, true)]),
13351        ("Ʒ", &[("Ʒ", 1, false)]),
13352        ("Ǽ", &[("Ǽ", 1, false)]),
13353        ("", &[("", 1, false)]),
13354        ("⋑⋑", &[("⋑⋑", 2, false)]),
13355        (
13356            "原理,进而",
13357            &[
13358                ("", 1, false),
13359                ("理,", 2, false),
13360                ("", 1, false),
13361                ("", 1, false),
13362            ],
13363        ),
13364        (
13365            "hello world",
13366            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13367        ),
13368        (
13369            "hello, world",
13370            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13371        ),
13372        (
13373            "  hello world",
13374            &[
13375                (" ", 1, true),
13376                ("hello", 5, false),
13377                (" ", 1, true),
13378                ("world", 5, false),
13379            ],
13380        ),
13381        (
13382            "这是什么 \n 钢笔",
13383            &[
13384                ("", 1, false),
13385                ("", 1, false),
13386                ("", 1, false),
13387                ("", 1, false),
13388                (" ", 1, true),
13389                ("", 1, false),
13390                ("", 1, false),
13391            ],
13392        ),
13393        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13394    ];
13395
13396    for (input, result) in tests {
13397        assert_eq!(
13398            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13399            result
13400                .iter()
13401                .copied()
13402                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13403                    token,
13404                    grapheme_len,
13405                    is_whitespace,
13406                })
13407                .collect::<Vec<_>>()
13408        );
13409    }
13410}
13411
13412fn wrap_with_prefix(
13413    line_prefix: String,
13414    unwrapped_text: String,
13415    wrap_column: usize,
13416    tab_size: NonZeroU32,
13417) -> String {
13418    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13419    let mut wrapped_text = String::new();
13420    let mut current_line = line_prefix.clone();
13421
13422    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13423    let mut current_line_len = line_prefix_len;
13424    for WordBreakToken {
13425        token,
13426        grapheme_len,
13427        is_whitespace,
13428    } in tokenizer
13429    {
13430        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13431            wrapped_text.push_str(current_line.trim_end());
13432            wrapped_text.push('\n');
13433            current_line.truncate(line_prefix.len());
13434            current_line_len = line_prefix_len;
13435            if !is_whitespace {
13436                current_line.push_str(token);
13437                current_line_len += grapheme_len;
13438            }
13439        } else if !is_whitespace {
13440            current_line.push_str(token);
13441            current_line_len += grapheme_len;
13442        } else if current_line_len != line_prefix_len {
13443            current_line.push(' ');
13444            current_line_len += 1;
13445        }
13446    }
13447
13448    if !current_line.is_empty() {
13449        wrapped_text.push_str(&current_line);
13450    }
13451    wrapped_text
13452}
13453
13454#[test]
13455fn test_wrap_with_prefix() {
13456    assert_eq!(
13457        wrap_with_prefix(
13458            "# ".to_string(),
13459            "abcdefg".to_string(),
13460            4,
13461            NonZeroU32::new(4).unwrap()
13462        ),
13463        "# abcdefg"
13464    );
13465    assert_eq!(
13466        wrap_with_prefix(
13467            "".to_string(),
13468            "\thello world".to_string(),
13469            8,
13470            NonZeroU32::new(4).unwrap()
13471        ),
13472        "hello\nworld"
13473    );
13474    assert_eq!(
13475        wrap_with_prefix(
13476            "// ".to_string(),
13477            "xx \nyy zz aa bb cc".to_string(),
13478            12,
13479            NonZeroU32::new(4).unwrap()
13480        ),
13481        "// xx yy zz\n// aa bb cc"
13482    );
13483    assert_eq!(
13484        wrap_with_prefix(
13485            String::new(),
13486            "这是什么 \n 钢笔".to_string(),
13487            3,
13488            NonZeroU32::new(4).unwrap()
13489        ),
13490        "这是什\n么 钢\n"
13491    );
13492}
13493
13494fn hunks_for_selections(
13495    snapshot: &EditorSnapshot,
13496    selections: &[Selection<Point>],
13497) -> Vec<MultiBufferDiffHunk> {
13498    hunks_for_ranges(
13499        selections.iter().map(|selection| selection.range()),
13500        snapshot,
13501    )
13502}
13503
13504pub fn hunks_for_ranges(
13505    ranges: impl Iterator<Item = Range<Point>>,
13506    snapshot: &EditorSnapshot,
13507) -> Vec<MultiBufferDiffHunk> {
13508    let mut hunks = Vec::new();
13509    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13510        HashMap::default();
13511    for query_range in ranges {
13512        let query_rows =
13513            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13514        for hunk in snapshot.diff_map.diff_hunks_in_range(
13515            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13516            &snapshot.buffer_snapshot,
13517        ) {
13518            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13519            // when the caret is just above or just below the deleted hunk.
13520            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13521            let related_to_selection = if allow_adjacent {
13522                hunk.row_range.overlaps(&query_rows)
13523                    || hunk.row_range.start == query_rows.end
13524                    || hunk.row_range.end == query_rows.start
13525            } else {
13526                hunk.row_range.overlaps(&query_rows)
13527            };
13528            if related_to_selection {
13529                if !processed_buffer_rows
13530                    .entry(hunk.buffer_id)
13531                    .or_default()
13532                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13533                {
13534                    continue;
13535                }
13536                hunks.push(hunk);
13537            }
13538        }
13539    }
13540
13541    hunks
13542}
13543
13544pub trait CollaborationHub {
13545    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13546    fn user_participant_indices<'a>(
13547        &self,
13548        cx: &'a AppContext,
13549    ) -> &'a HashMap<u64, ParticipantIndex>;
13550    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13551}
13552
13553impl CollaborationHub for Model<Project> {
13554    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13555        self.read(cx).collaborators()
13556    }
13557
13558    fn user_participant_indices<'a>(
13559        &self,
13560        cx: &'a AppContext,
13561    ) -> &'a HashMap<u64, ParticipantIndex> {
13562        self.read(cx).user_store().read(cx).participant_indices()
13563    }
13564
13565    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13566        let this = self.read(cx);
13567        let user_ids = this.collaborators().values().map(|c| c.user_id);
13568        this.user_store().read_with(cx, |user_store, cx| {
13569            user_store.participant_names(user_ids, cx)
13570        })
13571    }
13572}
13573
13574pub trait SemanticsProvider {
13575    fn hover(
13576        &self,
13577        buffer: &Model<Buffer>,
13578        position: text::Anchor,
13579        cx: &mut AppContext,
13580    ) -> Option<Task<Vec<project::Hover>>>;
13581
13582    fn inlay_hints(
13583        &self,
13584        buffer_handle: Model<Buffer>,
13585        range: Range<text::Anchor>,
13586        cx: &mut AppContext,
13587    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13588
13589    fn resolve_inlay_hint(
13590        &self,
13591        hint: InlayHint,
13592        buffer_handle: Model<Buffer>,
13593        server_id: LanguageServerId,
13594        cx: &mut AppContext,
13595    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13596
13597    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13598
13599    fn document_highlights(
13600        &self,
13601        buffer: &Model<Buffer>,
13602        position: text::Anchor,
13603        cx: &mut AppContext,
13604    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13605
13606    fn definitions(
13607        &self,
13608        buffer: &Model<Buffer>,
13609        position: text::Anchor,
13610        kind: GotoDefinitionKind,
13611        cx: &mut AppContext,
13612    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13613
13614    fn range_for_rename(
13615        &self,
13616        buffer: &Model<Buffer>,
13617        position: text::Anchor,
13618        cx: &mut AppContext,
13619    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13620
13621    fn perform_rename(
13622        &self,
13623        buffer: &Model<Buffer>,
13624        position: text::Anchor,
13625        new_name: String,
13626        cx: &mut AppContext,
13627    ) -> Option<Task<Result<ProjectTransaction>>>;
13628}
13629
13630pub trait CompletionProvider {
13631    fn completions(
13632        &self,
13633        buffer: &Model<Buffer>,
13634        buffer_position: text::Anchor,
13635        trigger: CompletionContext,
13636        cx: &mut ViewContext<Editor>,
13637    ) -> Task<Result<Vec<Completion>>>;
13638
13639    fn resolve_completions(
13640        &self,
13641        buffer: Model<Buffer>,
13642        completion_indices: Vec<usize>,
13643        completions: Rc<RefCell<Box<[Completion]>>>,
13644        cx: &mut ViewContext<Editor>,
13645    ) -> Task<Result<bool>>;
13646
13647    fn apply_additional_edits_for_completion(
13648        &self,
13649        _buffer: Model<Buffer>,
13650        _completions: Rc<RefCell<Box<[Completion]>>>,
13651        _completion_index: usize,
13652        _push_to_history: bool,
13653        _cx: &mut ViewContext<Editor>,
13654    ) -> Task<Result<Option<language::Transaction>>> {
13655        Task::ready(Ok(None))
13656    }
13657
13658    fn is_completion_trigger(
13659        &self,
13660        buffer: &Model<Buffer>,
13661        position: language::Anchor,
13662        text: &str,
13663        trigger_in_words: bool,
13664        cx: &mut ViewContext<Editor>,
13665    ) -> bool;
13666
13667    fn sort_completions(&self) -> bool {
13668        true
13669    }
13670}
13671
13672pub trait CodeActionProvider {
13673    fn id(&self) -> Arc<str>;
13674
13675    fn code_actions(
13676        &self,
13677        buffer: &Model<Buffer>,
13678        range: Range<text::Anchor>,
13679        cx: &mut WindowContext,
13680    ) -> Task<Result<Vec<CodeAction>>>;
13681
13682    fn apply_code_action(
13683        &self,
13684        buffer_handle: Model<Buffer>,
13685        action: CodeAction,
13686        excerpt_id: ExcerptId,
13687        push_to_history: bool,
13688        cx: &mut WindowContext,
13689    ) -> Task<Result<ProjectTransaction>>;
13690}
13691
13692impl CodeActionProvider for Model<Project> {
13693    fn id(&self) -> Arc<str> {
13694        "project".into()
13695    }
13696
13697    fn code_actions(
13698        &self,
13699        buffer: &Model<Buffer>,
13700        range: Range<text::Anchor>,
13701        cx: &mut WindowContext,
13702    ) -> Task<Result<Vec<CodeAction>>> {
13703        self.update(cx, |project, cx| {
13704            project.code_actions(buffer, range, None, cx)
13705        })
13706    }
13707
13708    fn apply_code_action(
13709        &self,
13710        buffer_handle: Model<Buffer>,
13711        action: CodeAction,
13712        _excerpt_id: ExcerptId,
13713        push_to_history: bool,
13714        cx: &mut WindowContext,
13715    ) -> Task<Result<ProjectTransaction>> {
13716        self.update(cx, |project, cx| {
13717            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13718        })
13719    }
13720}
13721
13722fn snippet_completions(
13723    project: &Project,
13724    buffer: &Model<Buffer>,
13725    buffer_position: text::Anchor,
13726    cx: &mut AppContext,
13727) -> Task<Result<Vec<Completion>>> {
13728    let language = buffer.read(cx).language_at(buffer_position);
13729    let language_name = language.as_ref().map(|language| language.lsp_id());
13730    let snippet_store = project.snippets().read(cx);
13731    let snippets = snippet_store.snippets_for(language_name, cx);
13732
13733    if snippets.is_empty() {
13734        return Task::ready(Ok(vec![]));
13735    }
13736    let snapshot = buffer.read(cx).text_snapshot();
13737    let chars: String = snapshot
13738        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13739        .collect();
13740
13741    let scope = language.map(|language| language.default_scope());
13742    let executor = cx.background_executor().clone();
13743
13744    cx.background_executor().spawn(async move {
13745        let classifier = CharClassifier::new(scope).for_completion(true);
13746        let mut last_word = chars
13747            .chars()
13748            .take_while(|c| classifier.is_word(*c))
13749            .collect::<String>();
13750        last_word = last_word.chars().rev().collect();
13751
13752        if last_word.is_empty() {
13753            return Ok(vec![]);
13754        }
13755
13756        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13757        let to_lsp = |point: &text::Anchor| {
13758            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13759            point_to_lsp(end)
13760        };
13761        let lsp_end = to_lsp(&buffer_position);
13762
13763        let candidates = snippets
13764            .iter()
13765            .enumerate()
13766            .flat_map(|(ix, snippet)| {
13767                snippet
13768                    .prefix
13769                    .iter()
13770                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13771            })
13772            .collect::<Vec<StringMatchCandidate>>();
13773
13774        let mut matches = fuzzy::match_strings(
13775            &candidates,
13776            &last_word,
13777            last_word.chars().any(|c| c.is_uppercase()),
13778            100,
13779            &Default::default(),
13780            executor,
13781        )
13782        .await;
13783
13784        // Remove all candidates where the query's start does not match the start of any word in the candidate
13785        if let Some(query_start) = last_word.chars().next() {
13786            matches.retain(|string_match| {
13787                split_words(&string_match.string).any(|word| {
13788                    // Check that the first codepoint of the word as lowercase matches the first
13789                    // codepoint of the query as lowercase
13790                    word.chars()
13791                        .flat_map(|codepoint| codepoint.to_lowercase())
13792                        .zip(query_start.to_lowercase())
13793                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13794                })
13795            });
13796        }
13797
13798        let matched_strings = matches
13799            .into_iter()
13800            .map(|m| m.string)
13801            .collect::<HashSet<_>>();
13802
13803        let result: Vec<Completion> = snippets
13804            .into_iter()
13805            .filter_map(|snippet| {
13806                let matching_prefix = snippet
13807                    .prefix
13808                    .iter()
13809                    .find(|prefix| matched_strings.contains(*prefix))?;
13810                let start = as_offset - last_word.len();
13811                let start = snapshot.anchor_before(start);
13812                let range = start..buffer_position;
13813                let lsp_start = to_lsp(&start);
13814                let lsp_range = lsp::Range {
13815                    start: lsp_start,
13816                    end: lsp_end,
13817                };
13818                Some(Completion {
13819                    old_range: range,
13820                    new_text: snippet.body.clone(),
13821                    resolved: false,
13822                    label: CodeLabel {
13823                        text: matching_prefix.clone(),
13824                        runs: vec![],
13825                        filter_range: 0..matching_prefix.len(),
13826                    },
13827                    server_id: LanguageServerId(usize::MAX),
13828                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13829                    lsp_completion: lsp::CompletionItem {
13830                        label: snippet.prefix.first().unwrap().clone(),
13831                        kind: Some(CompletionItemKind::SNIPPET),
13832                        label_details: snippet.description.as_ref().map(|description| {
13833                            lsp::CompletionItemLabelDetails {
13834                                detail: Some(description.clone()),
13835                                description: None,
13836                            }
13837                        }),
13838                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13839                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13840                            lsp::InsertReplaceEdit {
13841                                new_text: snippet.body.clone(),
13842                                insert: lsp_range,
13843                                replace: lsp_range,
13844                            },
13845                        )),
13846                        filter_text: Some(snippet.body.clone()),
13847                        sort_text: Some(char::MAX.to_string()),
13848                        ..Default::default()
13849                    },
13850                    confirm: None,
13851                })
13852            })
13853            .collect();
13854
13855        Ok(result)
13856    })
13857}
13858
13859impl CompletionProvider for Model<Project> {
13860    fn completions(
13861        &self,
13862        buffer: &Model<Buffer>,
13863        buffer_position: text::Anchor,
13864        options: CompletionContext,
13865        cx: &mut ViewContext<Editor>,
13866    ) -> Task<Result<Vec<Completion>>> {
13867        self.update(cx, |project, cx| {
13868            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13869            let project_completions = project.completions(buffer, buffer_position, options, cx);
13870            cx.background_executor().spawn(async move {
13871                let mut completions = project_completions.await?;
13872                let snippets_completions = snippets.await?;
13873                completions.extend(snippets_completions);
13874                Ok(completions)
13875            })
13876        })
13877    }
13878
13879    fn resolve_completions(
13880        &self,
13881        buffer: Model<Buffer>,
13882        completion_indices: Vec<usize>,
13883        completions: Rc<RefCell<Box<[Completion]>>>,
13884        cx: &mut ViewContext<Editor>,
13885    ) -> Task<Result<bool>> {
13886        self.update(cx, |project, cx| {
13887            project.lsp_store().update(cx, |lsp_store, cx| {
13888                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13889            })
13890        })
13891    }
13892
13893    fn apply_additional_edits_for_completion(
13894        &self,
13895        buffer: Model<Buffer>,
13896        completions: Rc<RefCell<Box<[Completion]>>>,
13897        completion_index: usize,
13898        push_to_history: bool,
13899        cx: &mut ViewContext<Editor>,
13900    ) -> Task<Result<Option<language::Transaction>>> {
13901        self.update(cx, |project, cx| {
13902            project.lsp_store().update(cx, |lsp_store, cx| {
13903                lsp_store.apply_additional_edits_for_completion(
13904                    buffer,
13905                    completions,
13906                    completion_index,
13907                    push_to_history,
13908                    cx,
13909                )
13910            })
13911        })
13912    }
13913
13914    fn is_completion_trigger(
13915        &self,
13916        buffer: &Model<Buffer>,
13917        position: language::Anchor,
13918        text: &str,
13919        trigger_in_words: bool,
13920        cx: &mut ViewContext<Editor>,
13921    ) -> bool {
13922        let mut chars = text.chars();
13923        let char = if let Some(char) = chars.next() {
13924            char
13925        } else {
13926            return false;
13927        };
13928        if chars.next().is_some() {
13929            return false;
13930        }
13931
13932        let buffer = buffer.read(cx);
13933        let snapshot = buffer.snapshot();
13934        if !snapshot.settings_at(position, cx).show_completions_on_input {
13935            return false;
13936        }
13937        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13938        if trigger_in_words && classifier.is_word(char) {
13939            return true;
13940        }
13941
13942        buffer.completion_triggers().contains(text)
13943    }
13944}
13945
13946impl SemanticsProvider for Model<Project> {
13947    fn hover(
13948        &self,
13949        buffer: &Model<Buffer>,
13950        position: text::Anchor,
13951        cx: &mut AppContext,
13952    ) -> Option<Task<Vec<project::Hover>>> {
13953        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13954    }
13955
13956    fn document_highlights(
13957        &self,
13958        buffer: &Model<Buffer>,
13959        position: text::Anchor,
13960        cx: &mut AppContext,
13961    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13962        Some(self.update(cx, |project, cx| {
13963            project.document_highlights(buffer, position, cx)
13964        }))
13965    }
13966
13967    fn definitions(
13968        &self,
13969        buffer: &Model<Buffer>,
13970        position: text::Anchor,
13971        kind: GotoDefinitionKind,
13972        cx: &mut AppContext,
13973    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13974        Some(self.update(cx, |project, cx| match kind {
13975            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13976            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13977            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13978            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13979        }))
13980    }
13981
13982    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13983        // TODO: make this work for remote projects
13984        self.read(cx)
13985            .language_servers_for_local_buffer(buffer.read(cx), cx)
13986            .any(
13987                |(_, server)| match server.capabilities().inlay_hint_provider {
13988                    Some(lsp::OneOf::Left(enabled)) => enabled,
13989                    Some(lsp::OneOf::Right(_)) => true,
13990                    None => false,
13991                },
13992            )
13993    }
13994
13995    fn inlay_hints(
13996        &self,
13997        buffer_handle: Model<Buffer>,
13998        range: Range<text::Anchor>,
13999        cx: &mut AppContext,
14000    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14001        Some(self.update(cx, |project, cx| {
14002            project.inlay_hints(buffer_handle, range, cx)
14003        }))
14004    }
14005
14006    fn resolve_inlay_hint(
14007        &self,
14008        hint: InlayHint,
14009        buffer_handle: Model<Buffer>,
14010        server_id: LanguageServerId,
14011        cx: &mut AppContext,
14012    ) -> Option<Task<anyhow::Result<InlayHint>>> {
14013        Some(self.update(cx, |project, cx| {
14014            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14015        }))
14016    }
14017
14018    fn range_for_rename(
14019        &self,
14020        buffer: &Model<Buffer>,
14021        position: text::Anchor,
14022        cx: &mut AppContext,
14023    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14024        Some(self.update(cx, |project, cx| {
14025            let buffer = buffer.clone();
14026            let task = project.prepare_rename(buffer.clone(), position, cx);
14027            cx.spawn(|_, mut cx| async move {
14028                Ok(match task.await? {
14029                    PrepareRenameResponse::Success(range) => Some(range),
14030                    PrepareRenameResponse::InvalidPosition => None,
14031                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14032                        // Fallback on using TreeSitter info to determine identifier range
14033                        buffer.update(&mut cx, |buffer, _| {
14034                            let snapshot = buffer.snapshot();
14035                            let (range, kind) = snapshot.surrounding_word(position);
14036                            if kind != Some(CharKind::Word) {
14037                                return None;
14038                            }
14039                            Some(
14040                                snapshot.anchor_before(range.start)
14041                                    ..snapshot.anchor_after(range.end),
14042                            )
14043                        })?
14044                    }
14045                })
14046            })
14047        }))
14048    }
14049
14050    fn perform_rename(
14051        &self,
14052        buffer: &Model<Buffer>,
14053        position: text::Anchor,
14054        new_name: String,
14055        cx: &mut AppContext,
14056    ) -> Option<Task<Result<ProjectTransaction>>> {
14057        Some(self.update(cx, |project, cx| {
14058            project.perform_rename(buffer.clone(), position, new_name, cx)
14059        }))
14060    }
14061}
14062
14063fn inlay_hint_settings(
14064    location: Anchor,
14065    snapshot: &MultiBufferSnapshot,
14066    cx: &mut ViewContext<Editor>,
14067) -> InlayHintSettings {
14068    let file = snapshot.file_at(location);
14069    let language = snapshot.language_at(location).map(|l| l.name());
14070    language_settings(language, file, cx).inlay_hints
14071}
14072
14073fn consume_contiguous_rows(
14074    contiguous_row_selections: &mut Vec<Selection<Point>>,
14075    selection: &Selection<Point>,
14076    display_map: &DisplaySnapshot,
14077    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14078) -> (MultiBufferRow, MultiBufferRow) {
14079    contiguous_row_selections.push(selection.clone());
14080    let start_row = MultiBufferRow(selection.start.row);
14081    let mut end_row = ending_row(selection, display_map);
14082
14083    while let Some(next_selection) = selections.peek() {
14084        if next_selection.start.row <= end_row.0 {
14085            end_row = ending_row(next_selection, display_map);
14086            contiguous_row_selections.push(selections.next().unwrap().clone());
14087        } else {
14088            break;
14089        }
14090    }
14091    (start_row, end_row)
14092}
14093
14094fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14095    if next_selection.end.column > 0 || next_selection.is_empty() {
14096        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14097    } else {
14098        MultiBufferRow(next_selection.end.row)
14099    }
14100}
14101
14102impl EditorSnapshot {
14103    pub fn remote_selections_in_range<'a>(
14104        &'a self,
14105        range: &'a Range<Anchor>,
14106        collaboration_hub: &dyn CollaborationHub,
14107        cx: &'a AppContext,
14108    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14109        let participant_names = collaboration_hub.user_names(cx);
14110        let participant_indices = collaboration_hub.user_participant_indices(cx);
14111        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14112        let collaborators_by_replica_id = collaborators_by_peer_id
14113            .iter()
14114            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14115            .collect::<HashMap<_, _>>();
14116        self.buffer_snapshot
14117            .selections_in_range(range, false)
14118            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14119                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14120                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14121                let user_name = participant_names.get(&collaborator.user_id).cloned();
14122                Some(RemoteSelection {
14123                    replica_id,
14124                    selection,
14125                    cursor_shape,
14126                    line_mode,
14127                    participant_index,
14128                    peer_id: collaborator.peer_id,
14129                    user_name,
14130                })
14131            })
14132    }
14133
14134    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14135        self.display_snapshot.buffer_snapshot.language_at(position)
14136    }
14137
14138    pub fn is_focused(&self) -> bool {
14139        self.is_focused
14140    }
14141
14142    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14143        self.placeholder_text.as_ref()
14144    }
14145
14146    pub fn scroll_position(&self) -> gpui::Point<f32> {
14147        self.scroll_anchor.scroll_position(&self.display_snapshot)
14148    }
14149
14150    fn gutter_dimensions(
14151        &self,
14152        font_id: FontId,
14153        font_size: Pixels,
14154        em_width: Pixels,
14155        em_advance: Pixels,
14156        max_line_number_width: Pixels,
14157        cx: &AppContext,
14158    ) -> GutterDimensions {
14159        if !self.show_gutter {
14160            return GutterDimensions::default();
14161        }
14162        let descent = cx.text_system().descent(font_id, font_size);
14163
14164        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14165            matches!(
14166                ProjectSettings::get_global(cx).git.git_gutter,
14167                Some(GitGutterSetting::TrackedFiles)
14168            )
14169        });
14170        let gutter_settings = EditorSettings::get_global(cx).gutter;
14171        let show_line_numbers = self
14172            .show_line_numbers
14173            .unwrap_or(gutter_settings.line_numbers);
14174        let line_gutter_width = if show_line_numbers {
14175            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14176            let min_width_for_number_on_gutter = em_advance * 4.0;
14177            max_line_number_width.max(min_width_for_number_on_gutter)
14178        } else {
14179            0.0.into()
14180        };
14181
14182        let show_code_actions = self
14183            .show_code_actions
14184            .unwrap_or(gutter_settings.code_actions);
14185
14186        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14187
14188        let git_blame_entries_width =
14189            self.git_blame_gutter_max_author_length
14190                .map(|max_author_length| {
14191                    // Length of the author name, but also space for the commit hash,
14192                    // the spacing and the timestamp.
14193                    let max_char_count = max_author_length
14194                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14195                        + 7 // length of commit sha
14196                        + 14 // length of max relative timestamp ("60 minutes ago")
14197                        + 4; // gaps and margins
14198
14199                    em_advance * max_char_count
14200                });
14201
14202        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14203        left_padding += if show_code_actions || show_runnables {
14204            em_width * 3.0
14205        } else if show_git_gutter && show_line_numbers {
14206            em_width * 2.0
14207        } else if show_git_gutter || show_line_numbers {
14208            em_width
14209        } else {
14210            px(0.)
14211        };
14212
14213        let right_padding = if gutter_settings.folds && show_line_numbers {
14214            em_width * 4.0
14215        } else if gutter_settings.folds {
14216            em_width * 3.0
14217        } else if show_line_numbers {
14218            em_width
14219        } else {
14220            px(0.)
14221        };
14222
14223        GutterDimensions {
14224            left_padding,
14225            right_padding,
14226            width: line_gutter_width + left_padding + right_padding,
14227            margin: -descent,
14228            git_blame_entries_width,
14229        }
14230    }
14231
14232    pub fn render_crease_toggle(
14233        &self,
14234        buffer_row: MultiBufferRow,
14235        row_contains_cursor: bool,
14236        editor: View<Editor>,
14237        cx: &mut WindowContext,
14238    ) -> Option<AnyElement> {
14239        let folded = self.is_line_folded(buffer_row);
14240        let mut is_foldable = false;
14241
14242        if let Some(crease) = self
14243            .crease_snapshot
14244            .query_row(buffer_row, &self.buffer_snapshot)
14245        {
14246            is_foldable = true;
14247            match crease {
14248                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14249                    if let Some(render_toggle) = render_toggle {
14250                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14251                            if folded {
14252                                editor.update(cx, |editor, cx| {
14253                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14254                                });
14255                            } else {
14256                                editor.update(cx, |editor, cx| {
14257                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14258                                });
14259                            }
14260                        });
14261                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14262                    }
14263                }
14264            }
14265        }
14266
14267        is_foldable |= self.starts_indent(buffer_row);
14268
14269        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14270            Some(
14271                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14272                    .toggle_state(folded)
14273                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14274                        if folded {
14275                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14276                        } else {
14277                            this.fold_at(&FoldAt { buffer_row }, cx);
14278                        }
14279                    }))
14280                    .into_any_element(),
14281            )
14282        } else {
14283            None
14284        }
14285    }
14286
14287    pub fn render_crease_trailer(
14288        &self,
14289        buffer_row: MultiBufferRow,
14290        cx: &mut WindowContext,
14291    ) -> Option<AnyElement> {
14292        let folded = self.is_line_folded(buffer_row);
14293        if let Crease::Inline { render_trailer, .. } = self
14294            .crease_snapshot
14295            .query_row(buffer_row, &self.buffer_snapshot)?
14296        {
14297            let render_trailer = render_trailer.as_ref()?;
14298            Some(render_trailer(buffer_row, folded, cx))
14299        } else {
14300            None
14301        }
14302    }
14303}
14304
14305impl Deref for EditorSnapshot {
14306    type Target = DisplaySnapshot;
14307
14308    fn deref(&self) -> &Self::Target {
14309        &self.display_snapshot
14310    }
14311}
14312
14313#[derive(Clone, Debug, PartialEq, Eq)]
14314pub enum EditorEvent {
14315    InputIgnored {
14316        text: Arc<str>,
14317    },
14318    InputHandled {
14319        utf16_range_to_replace: Option<Range<isize>>,
14320        text: Arc<str>,
14321    },
14322    ExcerptsAdded {
14323        buffer: Model<Buffer>,
14324        predecessor: ExcerptId,
14325        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14326    },
14327    ExcerptsRemoved {
14328        ids: Vec<ExcerptId>,
14329    },
14330    BufferFoldToggled {
14331        ids: Vec<ExcerptId>,
14332        folded: bool,
14333    },
14334    ExcerptsEdited {
14335        ids: Vec<ExcerptId>,
14336    },
14337    ExcerptsExpanded {
14338        ids: Vec<ExcerptId>,
14339    },
14340    BufferEdited,
14341    Edited {
14342        transaction_id: clock::Lamport,
14343    },
14344    Reparsed(BufferId),
14345    Focused,
14346    FocusedIn,
14347    Blurred,
14348    DirtyChanged,
14349    Saved,
14350    TitleChanged,
14351    DiffBaseChanged,
14352    SelectionsChanged {
14353        local: bool,
14354    },
14355    ScrollPositionChanged {
14356        local: bool,
14357        autoscroll: bool,
14358    },
14359    Closed,
14360    TransactionUndone {
14361        transaction_id: clock::Lamport,
14362    },
14363    TransactionBegun {
14364        transaction_id: clock::Lamport,
14365    },
14366    Reloaded,
14367    CursorShapeChanged,
14368}
14369
14370impl EventEmitter<EditorEvent> for Editor {}
14371
14372impl FocusableView for Editor {
14373    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14374        self.focus_handle.clone()
14375    }
14376}
14377
14378impl Render for Editor {
14379    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14380        let settings = ThemeSettings::get_global(cx);
14381
14382        let mut text_style = match self.mode {
14383            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14384                color: cx.theme().colors().editor_foreground,
14385                font_family: settings.ui_font.family.clone(),
14386                font_features: settings.ui_font.features.clone(),
14387                font_fallbacks: settings.ui_font.fallbacks.clone(),
14388                font_size: rems(0.875).into(),
14389                font_weight: settings.ui_font.weight,
14390                line_height: relative(settings.buffer_line_height.value()),
14391                ..Default::default()
14392            },
14393            EditorMode::Full => TextStyle {
14394                color: cx.theme().colors().editor_foreground,
14395                font_family: settings.buffer_font.family.clone(),
14396                font_features: settings.buffer_font.features.clone(),
14397                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14398                font_size: settings.buffer_font_size().into(),
14399                font_weight: settings.buffer_font.weight,
14400                line_height: relative(settings.buffer_line_height.value()),
14401                ..Default::default()
14402            },
14403        };
14404        if let Some(text_style_refinement) = &self.text_style_refinement {
14405            text_style.refine(text_style_refinement)
14406        }
14407
14408        let background = match self.mode {
14409            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14410            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14411            EditorMode::Full => cx.theme().colors().editor_background,
14412        };
14413
14414        EditorElement::new(
14415            cx.view(),
14416            EditorStyle {
14417                background,
14418                local_player: cx.theme().players().local(),
14419                text: text_style,
14420                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14421                syntax: cx.theme().syntax().clone(),
14422                status: cx.theme().status().clone(),
14423                inlay_hints_style: make_inlay_hints_style(cx),
14424                inline_completion_styles: make_suggestion_styles(cx),
14425                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14426            },
14427        )
14428    }
14429}
14430
14431impl ViewInputHandler for Editor {
14432    fn text_for_range(
14433        &mut self,
14434        range_utf16: Range<usize>,
14435        adjusted_range: &mut Option<Range<usize>>,
14436        cx: &mut ViewContext<Self>,
14437    ) -> Option<String> {
14438        let snapshot = self.buffer.read(cx).read(cx);
14439        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14440        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14441        if (start.0..end.0) != range_utf16 {
14442            adjusted_range.replace(start.0..end.0);
14443        }
14444        Some(snapshot.text_for_range(start..end).collect())
14445    }
14446
14447    fn selected_text_range(
14448        &mut self,
14449        ignore_disabled_input: bool,
14450        cx: &mut ViewContext<Self>,
14451    ) -> Option<UTF16Selection> {
14452        // Prevent the IME menu from appearing when holding down an alphabetic key
14453        // while input is disabled.
14454        if !ignore_disabled_input && !self.input_enabled {
14455            return None;
14456        }
14457
14458        let selection = self.selections.newest::<OffsetUtf16>(cx);
14459        let range = selection.range();
14460
14461        Some(UTF16Selection {
14462            range: range.start.0..range.end.0,
14463            reversed: selection.reversed,
14464        })
14465    }
14466
14467    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14468        let snapshot = self.buffer.read(cx).read(cx);
14469        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14470        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14471    }
14472
14473    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14474        self.clear_highlights::<InputComposition>(cx);
14475        self.ime_transaction.take();
14476    }
14477
14478    fn replace_text_in_range(
14479        &mut self,
14480        range_utf16: Option<Range<usize>>,
14481        text: &str,
14482        cx: &mut ViewContext<Self>,
14483    ) {
14484        if !self.input_enabled {
14485            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14486            return;
14487        }
14488
14489        self.transact(cx, |this, cx| {
14490            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14491                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14492                Some(this.selection_replacement_ranges(range_utf16, cx))
14493            } else {
14494                this.marked_text_ranges(cx)
14495            };
14496
14497            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14498                let newest_selection_id = this.selections.newest_anchor().id;
14499                this.selections
14500                    .all::<OffsetUtf16>(cx)
14501                    .iter()
14502                    .zip(ranges_to_replace.iter())
14503                    .find_map(|(selection, range)| {
14504                        if selection.id == newest_selection_id {
14505                            Some(
14506                                (range.start.0 as isize - selection.head().0 as isize)
14507                                    ..(range.end.0 as isize - selection.head().0 as isize),
14508                            )
14509                        } else {
14510                            None
14511                        }
14512                    })
14513            });
14514
14515            cx.emit(EditorEvent::InputHandled {
14516                utf16_range_to_replace: range_to_replace,
14517                text: text.into(),
14518            });
14519
14520            if let Some(new_selected_ranges) = new_selected_ranges {
14521                this.change_selections(None, cx, |selections| {
14522                    selections.select_ranges(new_selected_ranges)
14523                });
14524                this.backspace(&Default::default(), cx);
14525            }
14526
14527            this.handle_input(text, cx);
14528        });
14529
14530        if let Some(transaction) = self.ime_transaction {
14531            self.buffer.update(cx, |buffer, cx| {
14532                buffer.group_until_transaction(transaction, cx);
14533            });
14534        }
14535
14536        self.unmark_text(cx);
14537    }
14538
14539    fn replace_and_mark_text_in_range(
14540        &mut self,
14541        range_utf16: Option<Range<usize>>,
14542        text: &str,
14543        new_selected_range_utf16: Option<Range<usize>>,
14544        cx: &mut ViewContext<Self>,
14545    ) {
14546        if !self.input_enabled {
14547            return;
14548        }
14549
14550        let transaction = self.transact(cx, |this, cx| {
14551            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14552                let snapshot = this.buffer.read(cx).read(cx);
14553                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14554                    for marked_range in &mut marked_ranges {
14555                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14556                        marked_range.start.0 += relative_range_utf16.start;
14557                        marked_range.start =
14558                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14559                        marked_range.end =
14560                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14561                    }
14562                }
14563                Some(marked_ranges)
14564            } else if let Some(range_utf16) = range_utf16 {
14565                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14566                Some(this.selection_replacement_ranges(range_utf16, cx))
14567            } else {
14568                None
14569            };
14570
14571            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14572                let newest_selection_id = this.selections.newest_anchor().id;
14573                this.selections
14574                    .all::<OffsetUtf16>(cx)
14575                    .iter()
14576                    .zip(ranges_to_replace.iter())
14577                    .find_map(|(selection, range)| {
14578                        if selection.id == newest_selection_id {
14579                            Some(
14580                                (range.start.0 as isize - selection.head().0 as isize)
14581                                    ..(range.end.0 as isize - selection.head().0 as isize),
14582                            )
14583                        } else {
14584                            None
14585                        }
14586                    })
14587            });
14588
14589            cx.emit(EditorEvent::InputHandled {
14590                utf16_range_to_replace: range_to_replace,
14591                text: text.into(),
14592            });
14593
14594            if let Some(ranges) = ranges_to_replace {
14595                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14596            }
14597
14598            let marked_ranges = {
14599                let snapshot = this.buffer.read(cx).read(cx);
14600                this.selections
14601                    .disjoint_anchors()
14602                    .iter()
14603                    .map(|selection| {
14604                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14605                    })
14606                    .collect::<Vec<_>>()
14607            };
14608
14609            if text.is_empty() {
14610                this.unmark_text(cx);
14611            } else {
14612                this.highlight_text::<InputComposition>(
14613                    marked_ranges.clone(),
14614                    HighlightStyle {
14615                        underline: Some(UnderlineStyle {
14616                            thickness: px(1.),
14617                            color: None,
14618                            wavy: false,
14619                        }),
14620                        ..Default::default()
14621                    },
14622                    cx,
14623                );
14624            }
14625
14626            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14627            let use_autoclose = this.use_autoclose;
14628            let use_auto_surround = this.use_auto_surround;
14629            this.set_use_autoclose(false);
14630            this.set_use_auto_surround(false);
14631            this.handle_input(text, cx);
14632            this.set_use_autoclose(use_autoclose);
14633            this.set_use_auto_surround(use_auto_surround);
14634
14635            if let Some(new_selected_range) = new_selected_range_utf16 {
14636                let snapshot = this.buffer.read(cx).read(cx);
14637                let new_selected_ranges = marked_ranges
14638                    .into_iter()
14639                    .map(|marked_range| {
14640                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14641                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14642                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14643                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14644                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14645                    })
14646                    .collect::<Vec<_>>();
14647
14648                drop(snapshot);
14649                this.change_selections(None, cx, |selections| {
14650                    selections.select_ranges(new_selected_ranges)
14651                });
14652            }
14653        });
14654
14655        self.ime_transaction = self.ime_transaction.or(transaction);
14656        if let Some(transaction) = self.ime_transaction {
14657            self.buffer.update(cx, |buffer, cx| {
14658                buffer.group_until_transaction(transaction, cx);
14659            });
14660        }
14661
14662        if self.text_highlights::<InputComposition>(cx).is_none() {
14663            self.ime_transaction.take();
14664        }
14665    }
14666
14667    fn bounds_for_range(
14668        &mut self,
14669        range_utf16: Range<usize>,
14670        element_bounds: gpui::Bounds<Pixels>,
14671        cx: &mut ViewContext<Self>,
14672    ) -> Option<gpui::Bounds<Pixels>> {
14673        let text_layout_details = self.text_layout_details(cx);
14674        let gpui::Point {
14675            x: em_width,
14676            y: line_height,
14677        } = self.character_size(cx);
14678
14679        let snapshot = self.snapshot(cx);
14680        let scroll_position = snapshot.scroll_position();
14681        let scroll_left = scroll_position.x * em_width;
14682
14683        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14684        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14685            + self.gutter_dimensions.width
14686            + self.gutter_dimensions.margin;
14687        let y = line_height * (start.row().as_f32() - scroll_position.y);
14688
14689        Some(Bounds {
14690            origin: element_bounds.origin + point(x, y),
14691            size: size(em_width, line_height),
14692        })
14693    }
14694}
14695
14696trait SelectionExt {
14697    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14698    fn spanned_rows(
14699        &self,
14700        include_end_if_at_line_start: bool,
14701        map: &DisplaySnapshot,
14702    ) -> Range<MultiBufferRow>;
14703}
14704
14705impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14706    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14707        let start = self
14708            .start
14709            .to_point(&map.buffer_snapshot)
14710            .to_display_point(map);
14711        let end = self
14712            .end
14713            .to_point(&map.buffer_snapshot)
14714            .to_display_point(map);
14715        if self.reversed {
14716            end..start
14717        } else {
14718            start..end
14719        }
14720    }
14721
14722    fn spanned_rows(
14723        &self,
14724        include_end_if_at_line_start: bool,
14725        map: &DisplaySnapshot,
14726    ) -> Range<MultiBufferRow> {
14727        let start = self.start.to_point(&map.buffer_snapshot);
14728        let mut end = self.end.to_point(&map.buffer_snapshot);
14729        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14730            end.row -= 1;
14731        }
14732
14733        let buffer_start = map.prev_line_boundary(start).0;
14734        let buffer_end = map.next_line_boundary(end).0;
14735        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14736    }
14737}
14738
14739impl<T: InvalidationRegion> InvalidationStack<T> {
14740    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14741    where
14742        S: Clone + ToOffset,
14743    {
14744        while let Some(region) = self.last() {
14745            let all_selections_inside_invalidation_ranges =
14746                if selections.len() == region.ranges().len() {
14747                    selections
14748                        .iter()
14749                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14750                        .all(|(selection, invalidation_range)| {
14751                            let head = selection.head().to_offset(buffer);
14752                            invalidation_range.start <= head && invalidation_range.end >= head
14753                        })
14754                } else {
14755                    false
14756                };
14757
14758            if all_selections_inside_invalidation_ranges {
14759                break;
14760            } else {
14761                self.pop();
14762            }
14763        }
14764    }
14765}
14766
14767impl<T> Default for InvalidationStack<T> {
14768    fn default() -> Self {
14769        Self(Default::default())
14770    }
14771}
14772
14773impl<T> Deref for InvalidationStack<T> {
14774    type Target = Vec<T>;
14775
14776    fn deref(&self) -> &Self::Target {
14777        &self.0
14778    }
14779}
14780
14781impl<T> DerefMut for InvalidationStack<T> {
14782    fn deref_mut(&mut self) -> &mut Self::Target {
14783        &mut self.0
14784    }
14785}
14786
14787impl InvalidationRegion for SnippetState {
14788    fn ranges(&self) -> &[Range<Anchor>] {
14789        &self.ranges[self.active_index]
14790    }
14791}
14792
14793pub fn diagnostic_block_renderer(
14794    diagnostic: Diagnostic,
14795    max_message_rows: Option<u8>,
14796    allow_closing: bool,
14797    _is_valid: bool,
14798) -> RenderBlock {
14799    let (text_without_backticks, code_ranges) =
14800        highlight_diagnostic_message(&diagnostic, max_message_rows);
14801
14802    Arc::new(move |cx: &mut BlockContext| {
14803        let group_id: SharedString = cx.block_id.to_string().into();
14804
14805        let mut text_style = cx.text_style().clone();
14806        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14807        let theme_settings = ThemeSettings::get_global(cx);
14808        text_style.font_family = theme_settings.buffer_font.family.clone();
14809        text_style.font_style = theme_settings.buffer_font.style;
14810        text_style.font_features = theme_settings.buffer_font.features.clone();
14811        text_style.font_weight = theme_settings.buffer_font.weight;
14812
14813        let multi_line_diagnostic = diagnostic.message.contains('\n');
14814
14815        let buttons = |diagnostic: &Diagnostic| {
14816            if multi_line_diagnostic {
14817                v_flex()
14818            } else {
14819                h_flex()
14820            }
14821            .when(allow_closing, |div| {
14822                div.children(diagnostic.is_primary.then(|| {
14823                    IconButton::new("close-block", IconName::XCircle)
14824                        .icon_color(Color::Muted)
14825                        .size(ButtonSize::Compact)
14826                        .style(ButtonStyle::Transparent)
14827                        .visible_on_hover(group_id.clone())
14828                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14829                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14830                }))
14831            })
14832            .child(
14833                IconButton::new("copy-block", IconName::Copy)
14834                    .icon_color(Color::Muted)
14835                    .size(ButtonSize::Compact)
14836                    .style(ButtonStyle::Transparent)
14837                    .visible_on_hover(group_id.clone())
14838                    .on_click({
14839                        let message = diagnostic.message.clone();
14840                        move |_click, cx| {
14841                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14842                        }
14843                    })
14844                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14845            )
14846        };
14847
14848        let icon_size = buttons(&diagnostic)
14849            .into_any_element()
14850            .layout_as_root(AvailableSpace::min_size(), cx);
14851
14852        h_flex()
14853            .id(cx.block_id)
14854            .group(group_id.clone())
14855            .relative()
14856            .size_full()
14857            .block_mouse_down()
14858            .pl(cx.gutter_dimensions.width)
14859            .w(cx.max_width - cx.gutter_dimensions.full_width())
14860            .child(
14861                div()
14862                    .flex()
14863                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14864                    .flex_shrink(),
14865            )
14866            .child(buttons(&diagnostic))
14867            .child(div().flex().flex_shrink_0().child(
14868                StyledText::new(text_without_backticks.clone()).with_highlights(
14869                    &text_style,
14870                    code_ranges.iter().map(|range| {
14871                        (
14872                            range.clone(),
14873                            HighlightStyle {
14874                                font_weight: Some(FontWeight::BOLD),
14875                                ..Default::default()
14876                            },
14877                        )
14878                    }),
14879                ),
14880            ))
14881            .into_any_element()
14882    })
14883}
14884
14885fn inline_completion_edit_text(
14886    editor_snapshot: &EditorSnapshot,
14887    edits: &Vec<(Range<Anchor>, String)>,
14888    include_deletions: bool,
14889    cx: &WindowContext,
14890) -> InlineCompletionText {
14891    let edit_start = edits
14892        .first()
14893        .unwrap()
14894        .0
14895        .start
14896        .to_display_point(editor_snapshot);
14897
14898    let mut text = String::new();
14899    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14900    let mut highlights = Vec::new();
14901    for (old_range, new_text) in edits {
14902        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14903        text.extend(
14904            editor_snapshot
14905                .buffer_snapshot
14906                .chunks(offset..old_offset_range.start, false)
14907                .map(|chunk| chunk.text),
14908        );
14909        offset = old_offset_range.end;
14910
14911        let start = text.len();
14912        let color = if include_deletions && new_text.is_empty() {
14913            text.extend(
14914                editor_snapshot
14915                    .buffer_snapshot
14916                    .chunks(old_offset_range.start..offset, false)
14917                    .map(|chunk| chunk.text),
14918            );
14919            cx.theme().status().deleted_background
14920        } else {
14921            text.push_str(new_text);
14922            cx.theme().status().created_background
14923        };
14924        let end = text.len();
14925
14926        highlights.push((
14927            start..end,
14928            HighlightStyle {
14929                background_color: Some(color),
14930                ..Default::default()
14931            },
14932        ));
14933    }
14934
14935    let edit_end = edits
14936        .last()
14937        .unwrap()
14938        .0
14939        .end
14940        .to_display_point(editor_snapshot);
14941    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14942        .to_offset(editor_snapshot, Bias::Right);
14943    text.extend(
14944        editor_snapshot
14945            .buffer_snapshot
14946            .chunks(offset..end_of_line, false)
14947            .map(|chunk| chunk.text),
14948    );
14949
14950    InlineCompletionText::Edit {
14951        text: text.into(),
14952        highlights,
14953    }
14954}
14955
14956pub fn highlight_diagnostic_message(
14957    diagnostic: &Diagnostic,
14958    mut max_message_rows: Option<u8>,
14959) -> (SharedString, Vec<Range<usize>>) {
14960    let mut text_without_backticks = String::new();
14961    let mut code_ranges = Vec::new();
14962
14963    if let Some(source) = &diagnostic.source {
14964        text_without_backticks.push_str(source);
14965        code_ranges.push(0..source.len());
14966        text_without_backticks.push_str(": ");
14967    }
14968
14969    let mut prev_offset = 0;
14970    let mut in_code_block = false;
14971    let has_row_limit = max_message_rows.is_some();
14972    let mut newline_indices = diagnostic
14973        .message
14974        .match_indices('\n')
14975        .filter(|_| has_row_limit)
14976        .map(|(ix, _)| ix)
14977        .fuse()
14978        .peekable();
14979
14980    for (quote_ix, _) in diagnostic
14981        .message
14982        .match_indices('`')
14983        .chain([(diagnostic.message.len(), "")])
14984    {
14985        let mut first_newline_ix = None;
14986        let mut last_newline_ix = None;
14987        while let Some(newline_ix) = newline_indices.peek() {
14988            if *newline_ix < quote_ix {
14989                if first_newline_ix.is_none() {
14990                    first_newline_ix = Some(*newline_ix);
14991                }
14992                last_newline_ix = Some(*newline_ix);
14993
14994                if let Some(rows_left) = &mut max_message_rows {
14995                    if *rows_left == 0 {
14996                        break;
14997                    } else {
14998                        *rows_left -= 1;
14999                    }
15000                }
15001                let _ = newline_indices.next();
15002            } else {
15003                break;
15004            }
15005        }
15006        let prev_len = text_without_backticks.len();
15007        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15008        text_without_backticks.push_str(new_text);
15009        if in_code_block {
15010            code_ranges.push(prev_len..text_without_backticks.len());
15011        }
15012        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15013        in_code_block = !in_code_block;
15014        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15015            text_without_backticks.push_str("...");
15016            break;
15017        }
15018    }
15019
15020    (text_without_backticks.into(), code_ranges)
15021}
15022
15023fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15024    match severity {
15025        DiagnosticSeverity::ERROR => colors.error,
15026        DiagnosticSeverity::WARNING => colors.warning,
15027        DiagnosticSeverity::INFORMATION => colors.info,
15028        DiagnosticSeverity::HINT => colors.info,
15029        _ => colors.ignored,
15030    }
15031}
15032
15033pub fn styled_runs_for_code_label<'a>(
15034    label: &'a CodeLabel,
15035    syntax_theme: &'a theme::SyntaxTheme,
15036) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15037    let fade_out = HighlightStyle {
15038        fade_out: Some(0.35),
15039        ..Default::default()
15040    };
15041
15042    let mut prev_end = label.filter_range.end;
15043    label
15044        .runs
15045        .iter()
15046        .enumerate()
15047        .flat_map(move |(ix, (range, highlight_id))| {
15048            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15049                style
15050            } else {
15051                return Default::default();
15052            };
15053            let mut muted_style = style;
15054            muted_style.highlight(fade_out);
15055
15056            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15057            if range.start >= label.filter_range.end {
15058                if range.start > prev_end {
15059                    runs.push((prev_end..range.start, fade_out));
15060                }
15061                runs.push((range.clone(), muted_style));
15062            } else if range.end <= label.filter_range.end {
15063                runs.push((range.clone(), style));
15064            } else {
15065                runs.push((range.start..label.filter_range.end, style));
15066                runs.push((label.filter_range.end..range.end, muted_style));
15067            }
15068            prev_end = cmp::max(prev_end, range.end);
15069
15070            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15071                runs.push((prev_end..label.text.len(), fade_out));
15072            }
15073
15074            runs
15075        })
15076}
15077
15078pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15079    let mut prev_index = 0;
15080    let mut prev_codepoint: Option<char> = None;
15081    text.char_indices()
15082        .chain([(text.len(), '\0')])
15083        .filter_map(move |(index, codepoint)| {
15084            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15085            let is_boundary = index == text.len()
15086                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15087                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15088            if is_boundary {
15089                let chunk = &text[prev_index..index];
15090                prev_index = index;
15091                Some(chunk)
15092            } else {
15093                None
15094            }
15095        })
15096}
15097
15098pub trait RangeToAnchorExt: Sized {
15099    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15100
15101    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15102        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15103        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15104    }
15105}
15106
15107impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15108    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15109        let start_offset = self.start.to_offset(snapshot);
15110        let end_offset = self.end.to_offset(snapshot);
15111        if start_offset == end_offset {
15112            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15113        } else {
15114            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15115        }
15116    }
15117}
15118
15119pub trait RowExt {
15120    fn as_f32(&self) -> f32;
15121
15122    fn next_row(&self) -> Self;
15123
15124    fn previous_row(&self) -> Self;
15125
15126    fn minus(&self, other: Self) -> u32;
15127}
15128
15129impl RowExt for DisplayRow {
15130    fn as_f32(&self) -> f32 {
15131        self.0 as f32
15132    }
15133
15134    fn next_row(&self) -> Self {
15135        Self(self.0 + 1)
15136    }
15137
15138    fn previous_row(&self) -> Self {
15139        Self(self.0.saturating_sub(1))
15140    }
15141
15142    fn minus(&self, other: Self) -> u32 {
15143        self.0 - other.0
15144    }
15145}
15146
15147impl RowExt for MultiBufferRow {
15148    fn as_f32(&self) -> f32 {
15149        self.0 as f32
15150    }
15151
15152    fn next_row(&self) -> Self {
15153        Self(self.0 + 1)
15154    }
15155
15156    fn previous_row(&self) -> Self {
15157        Self(self.0.saturating_sub(1))
15158    }
15159
15160    fn minus(&self, other: Self) -> u32 {
15161        self.0 - other.0
15162    }
15163}
15164
15165trait RowRangeExt {
15166    type Row;
15167
15168    fn len(&self) -> usize;
15169
15170    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15171}
15172
15173impl RowRangeExt for Range<MultiBufferRow> {
15174    type Row = MultiBufferRow;
15175
15176    fn len(&self) -> usize {
15177        (self.end.0 - self.start.0) as usize
15178    }
15179
15180    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15181        (self.start.0..self.end.0).map(MultiBufferRow)
15182    }
15183}
15184
15185impl RowRangeExt for Range<DisplayRow> {
15186    type Row = DisplayRow;
15187
15188    fn len(&self) -> usize {
15189        (self.end.0 - self.start.0) as usize
15190    }
15191
15192    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15193        (self.start.0..self.end.0).map(DisplayRow)
15194    }
15195}
15196
15197fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15198    if hunk.diff_base_byte_range.is_empty() {
15199        DiffHunkStatus::Added
15200    } else if hunk.row_range.is_empty() {
15201        DiffHunkStatus::Removed
15202    } else {
15203        DiffHunkStatus::Modified
15204    }
15205}
15206
15207/// If select range has more than one line, we
15208/// just point the cursor to range.start.
15209fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15210    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15211        range
15212    } else {
15213        range.start..range.start
15214    }
15215}
15216
15217pub struct KillRing(ClipboardItem);
15218impl Global for KillRing {}
15219
15220const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);