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::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462enum InlineCompletionMenuHint {
  463    Loading,
  464    Loaded { text: InlineCompletionText },
  465    None,
  466}
  467
  468impl InlineCompletionMenuHint {
  469    pub fn label(&self) -> &'static str {
  470        match self {
  471            InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
  472                "Edit Prediction"
  473            }
  474            InlineCompletionMenuHint::None => "No Prediction",
  475        }
  476    }
  477}
  478
  479#[derive(Clone, Debug)]
  480enum InlineCompletionText {
  481    Move(SharedString),
  482    Edit {
  483        text: SharedString,
  484        highlights: Vec<(Range<usize>, HighlightStyle)>,
  485    },
  486}
  487
  488enum InlineCompletion {
  489    Edit(Vec<(Range<Anchor>, String)>),
  490    Move(Anchor),
  491}
  492
  493struct InlineCompletionState {
  494    inlay_ids: Vec<InlayId>,
  495    completion: InlineCompletion,
  496    invalidation_range: Range<Anchor>,
  497}
  498
  499enum InlineCompletionHighlight {}
  500
  501#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  502struct EditorActionId(usize);
  503
  504impl EditorActionId {
  505    pub fn post_inc(&mut self) -> Self {
  506        let answer = self.0;
  507
  508        *self = Self(answer + 1);
  509
  510        Self(answer)
  511    }
  512}
  513
  514// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  515// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  516
  517type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  518type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  519
  520#[derive(Default)]
  521struct ScrollbarMarkerState {
  522    scrollbar_size: Size<Pixels>,
  523    dirty: bool,
  524    markers: Arc<[PaintQuad]>,
  525    pending_refresh: Option<Task<Result<()>>>,
  526}
  527
  528impl ScrollbarMarkerState {
  529    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  530        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  531    }
  532}
  533
  534#[derive(Clone, Debug)]
  535struct RunnableTasks {
  536    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  537    offset: MultiBufferOffset,
  538    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  539    column: u32,
  540    // Values of all named captures, including those starting with '_'
  541    extra_variables: HashMap<String, String>,
  542    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  543    context_range: Range<BufferOffset>,
  544}
  545
  546impl RunnableTasks {
  547    fn resolve<'a>(
  548        &'a self,
  549        cx: &'a task::TaskContext,
  550    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  551        self.templates.iter().filter_map(|(kind, template)| {
  552            template
  553                .resolve_task(&kind.to_id_base(), cx)
  554                .map(|task| (kind.clone(), task))
  555        })
  556    }
  557}
  558
  559#[derive(Clone)]
  560struct ResolvedTasks {
  561    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  562    position: Anchor,
  563}
  564#[derive(Copy, Clone, Debug)]
  565struct MultiBufferOffset(usize);
  566#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  567struct BufferOffset(usize);
  568
  569// Addons allow storing per-editor state in other crates (e.g. Vim)
  570pub trait Addon: 'static {
  571    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  572
  573    fn to_any(&self) -> &dyn std::any::Any;
  574}
  575
  576#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  577pub enum IsVimMode {
  578    Yes,
  579    No,
  580}
  581
  582/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  583///
  584/// See the [module level documentation](self) for more information.
  585pub struct Editor {
  586    focus_handle: FocusHandle,
  587    last_focused_descendant: Option<WeakFocusHandle>,
  588    /// The text buffer being edited
  589    buffer: Model<MultiBuffer>,
  590    /// Map of how text in the buffer should be displayed.
  591    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  592    pub display_map: Model<DisplayMap>,
  593    pub selections: SelectionsCollection,
  594    pub scroll_manager: ScrollManager,
  595    /// When inline assist editors are linked, they all render cursors because
  596    /// typing enters text into each of them, even the ones that aren't focused.
  597    pub(crate) show_cursor_when_unfocused: bool,
  598    columnar_selection_tail: Option<Anchor>,
  599    add_selections_state: Option<AddSelectionsState>,
  600    select_next_state: Option<SelectNextState>,
  601    select_prev_state: Option<SelectNextState>,
  602    selection_history: SelectionHistory,
  603    autoclose_regions: Vec<AutocloseRegion>,
  604    snippet_stack: InvalidationStack<SnippetState>,
  605    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  606    ime_transaction: Option<TransactionId>,
  607    active_diagnostics: Option<ActiveDiagnosticGroup>,
  608    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  609
  610    project: Option<Model<Project>>,
  611    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  612    completion_provider: Option<Box<dyn CompletionProvider>>,
  613    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  614    blink_manager: Model<BlinkManager>,
  615    show_cursor_names: bool,
  616    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  617    pub show_local_selections: bool,
  618    mode: EditorMode,
  619    show_breadcrumbs: bool,
  620    show_gutter: bool,
  621    show_scrollbars: bool,
  622    show_line_numbers: Option<bool>,
  623    use_relative_line_numbers: Option<bool>,
  624    show_git_diff_gutter: Option<bool>,
  625    show_code_actions: Option<bool>,
  626    show_runnables: Option<bool>,
  627    show_wrap_guides: Option<bool>,
  628    show_indent_guides: Option<bool>,
  629    placeholder_text: Option<Arc<str>>,
  630    highlight_order: usize,
  631    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  632    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  633    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  634    scrollbar_marker_state: ScrollbarMarkerState,
  635    active_indent_guides_state: ActiveIndentGuidesState,
  636    nav_history: Option<ItemNavHistory>,
  637    context_menu: RefCell<Option<CodeContextMenu>>,
  638    mouse_context_menu: Option<MouseContextMenu>,
  639    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  640    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  641    signature_help_state: SignatureHelpState,
  642    auto_signature_help: Option<bool>,
  643    find_all_references_task_sources: Vec<Anchor>,
  644    next_completion_id: CompletionId,
  645    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  646    code_actions_task: Option<Task<Result<()>>>,
  647    document_highlights_task: Option<Task<()>>,
  648    linked_editing_range_task: Option<Task<Option<()>>>,
  649    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  650    pending_rename: Option<RenameState>,
  651    searchable: bool,
  652    cursor_shape: CursorShape,
  653    current_line_highlight: Option<CurrentLineHighlight>,
  654    collapse_matches: bool,
  655    autoindent_mode: Option<AutoindentMode>,
  656    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  657    input_enabled: bool,
  658    use_modal_editing: bool,
  659    read_only: bool,
  660    leader_peer_id: Option<PeerId>,
  661    remote_id: Option<ViewId>,
  662    hover_state: HoverState,
  663    gutter_hovered: bool,
  664    hovered_link_state: Option<HoveredLinkState>,
  665    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  666    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  667    active_inline_completion: Option<InlineCompletionState>,
  668    // enable_inline_completions is a switch that Vim can use to disable
  669    // inline completions based on its mode.
  670    enable_inline_completions: bool,
  671    show_inline_completions_override: Option<bool>,
  672    inlay_hint_cache: InlayHintCache,
  673    diff_map: DiffMap,
  674    next_inlay_id: usize,
  675    _subscriptions: Vec<Subscription>,
  676    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  677    gutter_dimensions: GutterDimensions,
  678    style: Option<EditorStyle>,
  679    text_style_refinement: Option<TextStyleRefinement>,
  680    next_editor_action_id: EditorActionId,
  681    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  682    use_autoclose: bool,
  683    use_auto_surround: bool,
  684    auto_replace_emoji_shortcode: bool,
  685    show_git_blame_gutter: bool,
  686    show_git_blame_inline: bool,
  687    show_git_blame_inline_delay_task: Option<Task<()>>,
  688    git_blame_inline_enabled: bool,
  689    serialize_dirty_buffers: bool,
  690    show_selection_menu: Option<bool>,
  691    blame: Option<Model<GitBlame>>,
  692    blame_subscription: Option<Subscription>,
  693    custom_context_menu: Option<
  694        Box<
  695            dyn 'static
  696                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  697        >,
  698    >,
  699    last_bounds: Option<Bounds<Pixels>>,
  700    expect_bounds_change: Option<Bounds<Pixels>>,
  701    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  702    tasks_update_task: Option<Task<()>>,
  703    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  704    breadcrumb_header: Option<String>,
  705    focused_block: Option<FocusedBlock>,
  706    next_scroll_position: NextScrollCursorCenterTopBottom,
  707    addons: HashMap<TypeId, Box<dyn Addon>>,
  708    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  709    toggle_fold_multiple_buffers: Task<()>,
  710    _scroll_cursor_center_top_bottom_task: Task<()>,
  711}
  712
  713#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  714enum NextScrollCursorCenterTopBottom {
  715    #[default]
  716    Center,
  717    Top,
  718    Bottom,
  719}
  720
  721impl NextScrollCursorCenterTopBottom {
  722    fn next(&self) -> Self {
  723        match self {
  724            Self::Center => Self::Top,
  725            Self::Top => Self::Bottom,
  726            Self::Bottom => Self::Center,
  727        }
  728    }
  729}
  730
  731#[derive(Clone)]
  732pub struct EditorSnapshot {
  733    pub mode: EditorMode,
  734    show_gutter: bool,
  735    show_line_numbers: Option<bool>,
  736    show_git_diff_gutter: Option<bool>,
  737    show_code_actions: Option<bool>,
  738    show_runnables: Option<bool>,
  739    git_blame_gutter_max_author_length: Option<usize>,
  740    pub display_snapshot: DisplaySnapshot,
  741    pub placeholder_text: Option<Arc<str>>,
  742    diff_map: DiffMapSnapshot,
  743    is_focused: bool,
  744    scroll_anchor: ScrollAnchor,
  745    ongoing_scroll: OngoingScroll,
  746    current_line_highlight: CurrentLineHighlight,
  747    gutter_hovered: bool,
  748}
  749
  750const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  751
  752#[derive(Default, Debug, Clone, Copy)]
  753pub struct GutterDimensions {
  754    pub left_padding: Pixels,
  755    pub right_padding: Pixels,
  756    pub width: Pixels,
  757    pub margin: Pixels,
  758    pub git_blame_entries_width: Option<Pixels>,
  759}
  760
  761impl GutterDimensions {
  762    /// The full width of the space taken up by the gutter.
  763    pub fn full_width(&self) -> Pixels {
  764        self.margin + self.width
  765    }
  766
  767    /// The width of the space reserved for the fold indicators,
  768    /// use alongside 'justify_end' and `gutter_width` to
  769    /// right align content with the line numbers
  770    pub fn fold_area_width(&self) -> Pixels {
  771        self.margin + self.right_padding
  772    }
  773}
  774
  775#[derive(Debug)]
  776pub struct RemoteSelection {
  777    pub replica_id: ReplicaId,
  778    pub selection: Selection<Anchor>,
  779    pub cursor_shape: CursorShape,
  780    pub peer_id: PeerId,
  781    pub line_mode: bool,
  782    pub participant_index: Option<ParticipantIndex>,
  783    pub user_name: Option<SharedString>,
  784}
  785
  786#[derive(Clone, Debug)]
  787struct SelectionHistoryEntry {
  788    selections: Arc<[Selection<Anchor>]>,
  789    select_next_state: Option<SelectNextState>,
  790    select_prev_state: Option<SelectNextState>,
  791    add_selections_state: Option<AddSelectionsState>,
  792}
  793
  794enum SelectionHistoryMode {
  795    Normal,
  796    Undoing,
  797    Redoing,
  798}
  799
  800#[derive(Clone, PartialEq, Eq, Hash)]
  801struct HoveredCursor {
  802    replica_id: u16,
  803    selection_id: usize,
  804}
  805
  806impl Default for SelectionHistoryMode {
  807    fn default() -> Self {
  808        Self::Normal
  809    }
  810}
  811
  812#[derive(Default)]
  813struct SelectionHistory {
  814    #[allow(clippy::type_complexity)]
  815    selections_by_transaction:
  816        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  817    mode: SelectionHistoryMode,
  818    undo_stack: VecDeque<SelectionHistoryEntry>,
  819    redo_stack: VecDeque<SelectionHistoryEntry>,
  820}
  821
  822impl SelectionHistory {
  823    fn insert_transaction(
  824        &mut self,
  825        transaction_id: TransactionId,
  826        selections: Arc<[Selection<Anchor>]>,
  827    ) {
  828        self.selections_by_transaction
  829            .insert(transaction_id, (selections, None));
  830    }
  831
  832    #[allow(clippy::type_complexity)]
  833    fn transaction(
  834        &self,
  835        transaction_id: TransactionId,
  836    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  837        self.selections_by_transaction.get(&transaction_id)
  838    }
  839
  840    #[allow(clippy::type_complexity)]
  841    fn transaction_mut(
  842        &mut self,
  843        transaction_id: TransactionId,
  844    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  845        self.selections_by_transaction.get_mut(&transaction_id)
  846    }
  847
  848    fn push(&mut self, entry: SelectionHistoryEntry) {
  849        if !entry.selections.is_empty() {
  850            match self.mode {
  851                SelectionHistoryMode::Normal => {
  852                    self.push_undo(entry);
  853                    self.redo_stack.clear();
  854                }
  855                SelectionHistoryMode::Undoing => self.push_redo(entry),
  856                SelectionHistoryMode::Redoing => self.push_undo(entry),
  857            }
  858        }
  859    }
  860
  861    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  862        if self
  863            .undo_stack
  864            .back()
  865            .map_or(true, |e| e.selections != entry.selections)
  866        {
  867            self.undo_stack.push_back(entry);
  868            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  869                self.undo_stack.pop_front();
  870            }
  871        }
  872    }
  873
  874    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  875        if self
  876            .redo_stack
  877            .back()
  878            .map_or(true, |e| e.selections != entry.selections)
  879        {
  880            self.redo_stack.push_back(entry);
  881            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  882                self.redo_stack.pop_front();
  883            }
  884        }
  885    }
  886}
  887
  888struct RowHighlight {
  889    index: usize,
  890    range: Range<Anchor>,
  891    color: Hsla,
  892    should_autoscroll: bool,
  893}
  894
  895#[derive(Clone, Debug)]
  896struct AddSelectionsState {
  897    above: bool,
  898    stack: Vec<usize>,
  899}
  900
  901#[derive(Clone)]
  902struct SelectNextState {
  903    query: AhoCorasick,
  904    wordwise: bool,
  905    done: bool,
  906}
  907
  908impl std::fmt::Debug for SelectNextState {
  909    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  910        f.debug_struct(std::any::type_name::<Self>())
  911            .field("wordwise", &self.wordwise)
  912            .field("done", &self.done)
  913            .finish()
  914    }
  915}
  916
  917#[derive(Debug)]
  918struct AutocloseRegion {
  919    selection_id: usize,
  920    range: Range<Anchor>,
  921    pair: BracketPair,
  922}
  923
  924#[derive(Debug)]
  925struct SnippetState {
  926    ranges: Vec<Vec<Range<Anchor>>>,
  927    active_index: usize,
  928    choices: Vec<Option<Vec<String>>>,
  929}
  930
  931#[doc(hidden)]
  932pub struct RenameState {
  933    pub range: Range<Anchor>,
  934    pub old_name: Arc<str>,
  935    pub editor: View<Editor>,
  936    block_id: CustomBlockId,
  937}
  938
  939struct InvalidationStack<T>(Vec<T>);
  940
  941struct RegisteredInlineCompletionProvider {
  942    provider: Arc<dyn InlineCompletionProviderHandle>,
  943    _subscription: Subscription,
  944}
  945
  946#[derive(Debug)]
  947struct ActiveDiagnosticGroup {
  948    primary_range: Range<Anchor>,
  949    primary_message: String,
  950    group_id: usize,
  951    blocks: HashMap<CustomBlockId, Diagnostic>,
  952    is_valid: bool,
  953}
  954
  955#[derive(Serialize, Deserialize, Clone, Debug)]
  956pub struct ClipboardSelection {
  957    pub len: usize,
  958    pub is_entire_line: bool,
  959    pub first_line_indent: u32,
  960}
  961
  962#[derive(Debug)]
  963pub(crate) struct NavigationData {
  964    cursor_anchor: Anchor,
  965    cursor_position: Point,
  966    scroll_anchor: ScrollAnchor,
  967    scroll_top_row: u32,
  968}
  969
  970#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  971pub enum GotoDefinitionKind {
  972    Symbol,
  973    Declaration,
  974    Type,
  975    Implementation,
  976}
  977
  978#[derive(Debug, Clone)]
  979enum InlayHintRefreshReason {
  980    Toggle(bool),
  981    SettingsChange(InlayHintSettings),
  982    NewLinesShown,
  983    BufferEdited(HashSet<Arc<Language>>),
  984    RefreshRequested,
  985    ExcerptsRemoved(Vec<ExcerptId>),
  986}
  987
  988impl InlayHintRefreshReason {
  989    fn description(&self) -> &'static str {
  990        match self {
  991            Self::Toggle(_) => "toggle",
  992            Self::SettingsChange(_) => "settings change",
  993            Self::NewLinesShown => "new lines shown",
  994            Self::BufferEdited(_) => "buffer edited",
  995            Self::RefreshRequested => "refresh requested",
  996            Self::ExcerptsRemoved(_) => "excerpts removed",
  997        }
  998    }
  999}
 1000
 1001pub enum FormatTarget {
 1002    Buffers,
 1003    Ranges(Vec<Range<MultiBufferPoint>>),
 1004}
 1005
 1006pub(crate) struct FocusedBlock {
 1007    id: BlockId,
 1008    focus_handle: WeakFocusHandle,
 1009}
 1010
 1011#[derive(Clone)]
 1012enum JumpData {
 1013    MultiBufferRow {
 1014        row: MultiBufferRow,
 1015        line_offset_from_top: u32,
 1016    },
 1017    MultiBufferPoint {
 1018        excerpt_id: ExcerptId,
 1019        position: Point,
 1020        anchor: text::Anchor,
 1021        line_offset_from_top: u32,
 1022    },
 1023}
 1024
 1025impl Editor {
 1026    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1027        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1028        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1029        Self::new(
 1030            EditorMode::SingleLine { auto_width: false },
 1031            buffer,
 1032            None,
 1033            false,
 1034            cx,
 1035        )
 1036    }
 1037
 1038    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1039        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1040        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1041        Self::new(EditorMode::Full, buffer, None, false, cx)
 1042    }
 1043
 1044    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1045        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1046        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1047        Self::new(
 1048            EditorMode::SingleLine { auto_width: true },
 1049            buffer,
 1050            None,
 1051            false,
 1052            cx,
 1053        )
 1054    }
 1055
 1056    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1057        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1058        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1059        Self::new(
 1060            EditorMode::AutoHeight { max_lines },
 1061            buffer,
 1062            None,
 1063            false,
 1064            cx,
 1065        )
 1066    }
 1067
 1068    pub fn for_buffer(
 1069        buffer: Model<Buffer>,
 1070        project: Option<Model<Project>>,
 1071        cx: &mut ViewContext<Self>,
 1072    ) -> Self {
 1073        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(EditorMode::Full, buffer, project, false, cx)
 1075    }
 1076
 1077    pub fn for_multibuffer(
 1078        buffer: Model<MultiBuffer>,
 1079        project: Option<Model<Project>>,
 1080        show_excerpt_controls: bool,
 1081        cx: &mut ViewContext<Self>,
 1082    ) -> Self {
 1083        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1084    }
 1085
 1086    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1087        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1088        let mut clone = Self::new(
 1089            self.mode,
 1090            self.buffer.clone(),
 1091            self.project.clone(),
 1092            show_excerpt_controls,
 1093            cx,
 1094        );
 1095        self.display_map.update(cx, |display_map, cx| {
 1096            let snapshot = display_map.snapshot(cx);
 1097            clone.display_map.update(cx, |display_map, cx| {
 1098                display_map.set_state(&snapshot, cx);
 1099            });
 1100        });
 1101        clone.selections.clone_state(&self.selections);
 1102        clone.scroll_manager.clone_state(&self.scroll_manager);
 1103        clone.searchable = self.searchable;
 1104        clone
 1105    }
 1106
 1107    pub fn new(
 1108        mode: EditorMode,
 1109        buffer: Model<MultiBuffer>,
 1110        project: Option<Model<Project>>,
 1111        show_excerpt_controls: bool,
 1112        cx: &mut ViewContext<Self>,
 1113    ) -> Self {
 1114        let style = cx.text_style();
 1115        let font_size = style.font_size.to_pixels(cx.rem_size());
 1116        let editor = cx.view().downgrade();
 1117        let fold_placeholder = FoldPlaceholder {
 1118            constrain_width: true,
 1119            render: Arc::new(move |fold_id, fold_range, cx| {
 1120                let editor = editor.clone();
 1121                div()
 1122                    .id(fold_id)
 1123                    .bg(cx.theme().colors().ghost_element_background)
 1124                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1125                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1126                    .rounded_sm()
 1127                    .size_full()
 1128                    .cursor_pointer()
 1129                    .child("")
 1130                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1131                    .on_click(move |_, cx| {
 1132                        editor
 1133                            .update(cx, |editor, cx| {
 1134                                editor.unfold_ranges(
 1135                                    &[fold_range.start..fold_range.end],
 1136                                    true,
 1137                                    false,
 1138                                    cx,
 1139                                );
 1140                                cx.stop_propagation();
 1141                            })
 1142                            .ok();
 1143                    })
 1144                    .into_any()
 1145            }),
 1146            merge_adjacent: true,
 1147            ..Default::default()
 1148        };
 1149        let display_map = cx.new_model(|cx| {
 1150            DisplayMap::new(
 1151                buffer.clone(),
 1152                style.font(),
 1153                font_size,
 1154                None,
 1155                show_excerpt_controls,
 1156                FILE_HEADER_HEIGHT,
 1157                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1158                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1159                fold_placeholder,
 1160                cx,
 1161            )
 1162        });
 1163
 1164        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1165
 1166        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1167
 1168        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1169            .then(|| language_settings::SoftWrap::None);
 1170
 1171        let mut project_subscriptions = Vec::new();
 1172        if mode == EditorMode::Full {
 1173            if let Some(project) = project.as_ref() {
 1174                if buffer.read(cx).is_singleton() {
 1175                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1176                        cx.emit(EditorEvent::TitleChanged);
 1177                    }));
 1178                }
 1179                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1180                    if let project::Event::RefreshInlayHints = event {
 1181                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1182                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1183                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1184                            let focus_handle = editor.focus_handle(cx);
 1185                            if focus_handle.is_focused(cx) {
 1186                                let snapshot = buffer.read(cx).snapshot();
 1187                                for (range, snippet) in snippet_edits {
 1188                                    let editor_range =
 1189                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1190                                    editor
 1191                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1192                                        .ok();
 1193                                }
 1194                            }
 1195                        }
 1196                    }
 1197                }));
 1198                if let Some(task_inventory) = project
 1199                    .read(cx)
 1200                    .task_store()
 1201                    .read(cx)
 1202                    .task_inventory()
 1203                    .cloned()
 1204                {
 1205                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1206                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1207                    }));
 1208                }
 1209            }
 1210        }
 1211
 1212        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1213
 1214        let inlay_hint_settings =
 1215            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1216        let focus_handle = cx.focus_handle();
 1217        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1218        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1219            .detach();
 1220        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1221            .detach();
 1222        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1223
 1224        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1225            Some(false)
 1226        } else {
 1227            None
 1228        };
 1229
 1230        let mut code_action_providers = Vec::new();
 1231        if let Some(project) = project.clone() {
 1232            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1233            code_action_providers.push(Rc::new(project) as Rc<_>);
 1234        }
 1235
 1236        let mut this = Self {
 1237            focus_handle,
 1238            show_cursor_when_unfocused: false,
 1239            last_focused_descendant: None,
 1240            buffer: buffer.clone(),
 1241            display_map: display_map.clone(),
 1242            selections,
 1243            scroll_manager: ScrollManager::new(cx),
 1244            columnar_selection_tail: None,
 1245            add_selections_state: None,
 1246            select_next_state: None,
 1247            select_prev_state: None,
 1248            selection_history: Default::default(),
 1249            autoclose_regions: Default::default(),
 1250            snippet_stack: Default::default(),
 1251            select_larger_syntax_node_stack: Vec::new(),
 1252            ime_transaction: Default::default(),
 1253            active_diagnostics: None,
 1254            soft_wrap_mode_override,
 1255            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1256            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1257            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1258            project,
 1259            blink_manager: blink_manager.clone(),
 1260            show_local_selections: true,
 1261            show_scrollbars: true,
 1262            mode,
 1263            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1264            show_gutter: mode == EditorMode::Full,
 1265            show_line_numbers: None,
 1266            use_relative_line_numbers: None,
 1267            show_git_diff_gutter: None,
 1268            show_code_actions: None,
 1269            show_runnables: None,
 1270            show_wrap_guides: None,
 1271            show_indent_guides,
 1272            placeholder_text: None,
 1273            highlight_order: 0,
 1274            highlighted_rows: HashMap::default(),
 1275            background_highlights: Default::default(),
 1276            gutter_highlights: TreeMap::default(),
 1277            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1278            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1279            nav_history: None,
 1280            context_menu: RefCell::new(None),
 1281            mouse_context_menu: None,
 1282            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1283            completion_tasks: Default::default(),
 1284            signature_help_state: SignatureHelpState::default(),
 1285            auto_signature_help: None,
 1286            find_all_references_task_sources: Vec::new(),
 1287            next_completion_id: 0,
 1288            next_inlay_id: 0,
 1289            code_action_providers,
 1290            available_code_actions: Default::default(),
 1291            code_actions_task: Default::default(),
 1292            document_highlights_task: Default::default(),
 1293            linked_editing_range_task: Default::default(),
 1294            pending_rename: Default::default(),
 1295            searchable: true,
 1296            cursor_shape: EditorSettings::get_global(cx)
 1297                .cursor_shape
 1298                .unwrap_or_default(),
 1299            current_line_highlight: None,
 1300            autoindent_mode: Some(AutoindentMode::EachLine),
 1301            collapse_matches: false,
 1302            workspace: None,
 1303            input_enabled: true,
 1304            use_modal_editing: mode == EditorMode::Full,
 1305            read_only: false,
 1306            use_autoclose: true,
 1307            use_auto_surround: true,
 1308            auto_replace_emoji_shortcode: false,
 1309            leader_peer_id: None,
 1310            remote_id: None,
 1311            hover_state: Default::default(),
 1312            hovered_link_state: Default::default(),
 1313            inline_completion_provider: None,
 1314            active_inline_completion: None,
 1315            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1316            diff_map: DiffMap::default(),
 1317            gutter_hovered: false,
 1318            pixel_position_of_newest_cursor: None,
 1319            last_bounds: None,
 1320            expect_bounds_change: None,
 1321            gutter_dimensions: GutterDimensions::default(),
 1322            style: None,
 1323            show_cursor_names: false,
 1324            hovered_cursors: Default::default(),
 1325            next_editor_action_id: EditorActionId::default(),
 1326            editor_actions: Rc::default(),
 1327            show_inline_completions_override: None,
 1328            enable_inline_completions: true,
 1329            custom_context_menu: None,
 1330            show_git_blame_gutter: false,
 1331            show_git_blame_inline: false,
 1332            show_selection_menu: None,
 1333            show_git_blame_inline_delay_task: None,
 1334            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1335            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1336                .session
 1337                .restore_unsaved_buffers,
 1338            blame: None,
 1339            blame_subscription: None,
 1340            tasks: Default::default(),
 1341            _subscriptions: vec![
 1342                cx.observe(&buffer, Self::on_buffer_changed),
 1343                cx.subscribe(&buffer, Self::on_buffer_event),
 1344                cx.observe(&display_map, Self::on_display_map_changed),
 1345                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1346                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1347                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1348                cx.observe_window_activation(|editor, cx| {
 1349                    let active = cx.is_window_active();
 1350                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1351                        if active {
 1352                            blink_manager.enable(cx);
 1353                        } else {
 1354                            blink_manager.disable(cx);
 1355                        }
 1356                    });
 1357                }),
 1358            ],
 1359            tasks_update_task: None,
 1360            linked_edit_ranges: Default::default(),
 1361            previous_search_ranges: None,
 1362            breadcrumb_header: None,
 1363            focused_block: None,
 1364            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1365            addons: HashMap::default(),
 1366            registered_buffers: HashMap::default(),
 1367            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1368            toggle_fold_multiple_buffers: Task::ready(()),
 1369            text_style_refinement: None,
 1370        };
 1371        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1372        this._subscriptions.extend(project_subscriptions);
 1373
 1374        this.end_selection(cx);
 1375        this.scroll_manager.show_scrollbar(cx);
 1376
 1377        if mode == EditorMode::Full {
 1378            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1379            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1380
 1381            if this.git_blame_inline_enabled {
 1382                this.git_blame_inline_enabled = true;
 1383                this.start_git_blame_inline(false, cx);
 1384            }
 1385
 1386            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1387                if let Some(project) = this.project.as_ref() {
 1388                    let lsp_store = project.read(cx).lsp_store();
 1389                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1390                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1391                    });
 1392                    this.registered_buffers
 1393                        .insert(buffer.read(cx).remote_id(), handle);
 1394                }
 1395            }
 1396        }
 1397
 1398        this.report_editor_event("Editor Opened", None, cx);
 1399        this
 1400    }
 1401
 1402    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1403        self.mouse_context_menu
 1404            .as_ref()
 1405            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1406    }
 1407
 1408    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1409        let mut key_context = KeyContext::new_with_defaults();
 1410        key_context.add("Editor");
 1411        let mode = match self.mode {
 1412            EditorMode::SingleLine { .. } => "single_line",
 1413            EditorMode::AutoHeight { .. } => "auto_height",
 1414            EditorMode::Full => "full",
 1415        };
 1416
 1417        if EditorSettings::jupyter_enabled(cx) {
 1418            key_context.add("jupyter");
 1419        }
 1420
 1421        key_context.set("mode", mode);
 1422        if self.pending_rename.is_some() {
 1423            key_context.add("renaming");
 1424        }
 1425        match self.context_menu.borrow().as_ref() {
 1426            Some(CodeContextMenu::Completions(_)) => {
 1427                key_context.add("menu");
 1428                key_context.add("showing_completions")
 1429            }
 1430            Some(CodeContextMenu::CodeActions(_)) => {
 1431                key_context.add("menu");
 1432                key_context.add("showing_code_actions")
 1433            }
 1434            None => {}
 1435        }
 1436
 1437        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1438        if !self.focus_handle(cx).contains_focused(cx)
 1439            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1440        {
 1441            for addon in self.addons.values() {
 1442                addon.extend_key_context(&mut key_context, cx)
 1443            }
 1444        }
 1445
 1446        if let Some(extension) = self
 1447            .buffer
 1448            .read(cx)
 1449            .as_singleton()
 1450            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1451        {
 1452            key_context.set("extension", extension.to_string());
 1453        }
 1454
 1455        if self.has_active_inline_completion() {
 1456            key_context.add("copilot_suggestion");
 1457            key_context.add("inline_completion");
 1458        }
 1459
 1460        if !self
 1461            .selections
 1462            .disjoint
 1463            .iter()
 1464            .all(|selection| selection.start == selection.end)
 1465        {
 1466            key_context.add("selection");
 1467        }
 1468
 1469        key_context
 1470    }
 1471
 1472    pub fn new_file(
 1473        workspace: &mut Workspace,
 1474        _: &workspace::NewFile,
 1475        cx: &mut ViewContext<Workspace>,
 1476    ) {
 1477        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1478            "Failed to create buffer",
 1479            cx,
 1480            |e, _| match e.error_code() {
 1481                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1482                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1483                e.error_tag("required").unwrap_or("the latest version")
 1484            )),
 1485                _ => None,
 1486            },
 1487        );
 1488    }
 1489
 1490    pub fn new_in_workspace(
 1491        workspace: &mut Workspace,
 1492        cx: &mut ViewContext<Workspace>,
 1493    ) -> Task<Result<View<Editor>>> {
 1494        let project = workspace.project().clone();
 1495        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1496
 1497        cx.spawn(|workspace, mut cx| async move {
 1498            let buffer = create.await?;
 1499            workspace.update(&mut cx, |workspace, cx| {
 1500                let editor =
 1501                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1502                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1503                editor
 1504            })
 1505        })
 1506    }
 1507
 1508    fn new_file_vertical(
 1509        workspace: &mut Workspace,
 1510        _: &workspace::NewFileSplitVertical,
 1511        cx: &mut ViewContext<Workspace>,
 1512    ) {
 1513        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1514    }
 1515
 1516    fn new_file_horizontal(
 1517        workspace: &mut Workspace,
 1518        _: &workspace::NewFileSplitHorizontal,
 1519        cx: &mut ViewContext<Workspace>,
 1520    ) {
 1521        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1522    }
 1523
 1524    fn new_file_in_direction(
 1525        workspace: &mut Workspace,
 1526        direction: SplitDirection,
 1527        cx: &mut ViewContext<Workspace>,
 1528    ) {
 1529        let project = workspace.project().clone();
 1530        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1531
 1532        cx.spawn(|workspace, mut cx| async move {
 1533            let buffer = create.await?;
 1534            workspace.update(&mut cx, move |workspace, cx| {
 1535                workspace.split_item(
 1536                    direction,
 1537                    Box::new(
 1538                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1539                    ),
 1540                    cx,
 1541                )
 1542            })?;
 1543            anyhow::Ok(())
 1544        })
 1545        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1546            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1547                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1548                e.error_tag("required").unwrap_or("the latest version")
 1549            )),
 1550            _ => None,
 1551        });
 1552    }
 1553
 1554    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1555        self.leader_peer_id
 1556    }
 1557
 1558    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1559        &self.buffer
 1560    }
 1561
 1562    pub fn workspace(&self) -> Option<View<Workspace>> {
 1563        self.workspace.as_ref()?.0.upgrade()
 1564    }
 1565
 1566    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1567        self.buffer().read(cx).title(cx)
 1568    }
 1569
 1570    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1571        let git_blame_gutter_max_author_length = self
 1572            .render_git_blame_gutter(cx)
 1573            .then(|| {
 1574                if let Some(blame) = self.blame.as_ref() {
 1575                    let max_author_length =
 1576                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1577                    Some(max_author_length)
 1578                } else {
 1579                    None
 1580                }
 1581            })
 1582            .flatten();
 1583
 1584        EditorSnapshot {
 1585            mode: self.mode,
 1586            show_gutter: self.show_gutter,
 1587            show_line_numbers: self.show_line_numbers,
 1588            show_git_diff_gutter: self.show_git_diff_gutter,
 1589            show_code_actions: self.show_code_actions,
 1590            show_runnables: self.show_runnables,
 1591            git_blame_gutter_max_author_length,
 1592            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1593            scroll_anchor: self.scroll_manager.anchor(),
 1594            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1595            placeholder_text: self.placeholder_text.clone(),
 1596            diff_map: self.diff_map.snapshot(),
 1597            is_focused: self.focus_handle.is_focused(cx),
 1598            current_line_highlight: self
 1599                .current_line_highlight
 1600                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1601            gutter_hovered: self.gutter_hovered,
 1602        }
 1603    }
 1604
 1605    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1606        self.buffer.read(cx).language_at(point, cx)
 1607    }
 1608
 1609    pub fn file_at<T: ToOffset>(
 1610        &self,
 1611        point: T,
 1612        cx: &AppContext,
 1613    ) -> Option<Arc<dyn language::File>> {
 1614        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1615    }
 1616
 1617    pub fn active_excerpt(
 1618        &self,
 1619        cx: &AppContext,
 1620    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1621        self.buffer
 1622            .read(cx)
 1623            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1624    }
 1625
 1626    pub fn mode(&self) -> EditorMode {
 1627        self.mode
 1628    }
 1629
 1630    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1631        self.collaboration_hub.as_deref()
 1632    }
 1633
 1634    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1635        self.collaboration_hub = Some(hub);
 1636    }
 1637
 1638    pub fn set_custom_context_menu(
 1639        &mut self,
 1640        f: impl 'static
 1641            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1642    ) {
 1643        self.custom_context_menu = Some(Box::new(f))
 1644    }
 1645
 1646    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1647        self.completion_provider = provider;
 1648    }
 1649
 1650    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1651        self.semantics_provider.clone()
 1652    }
 1653
 1654    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1655        self.semantics_provider = provider;
 1656    }
 1657
 1658    pub fn set_inline_completion_provider<T>(
 1659        &mut self,
 1660        provider: Option<Model<T>>,
 1661        cx: &mut ViewContext<Self>,
 1662    ) where
 1663        T: InlineCompletionProvider,
 1664    {
 1665        self.inline_completion_provider =
 1666            provider.map(|provider| RegisteredInlineCompletionProvider {
 1667                _subscription: cx.observe(&provider, |this, _, cx| {
 1668                    if this.focus_handle.is_focused(cx) {
 1669                        this.update_visible_inline_completion(cx);
 1670                    }
 1671                }),
 1672                provider: Arc::new(provider),
 1673            });
 1674        self.refresh_inline_completion(false, false, cx);
 1675    }
 1676
 1677    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1678        self.placeholder_text.as_deref()
 1679    }
 1680
 1681    pub fn set_placeholder_text(
 1682        &mut self,
 1683        placeholder_text: impl Into<Arc<str>>,
 1684        cx: &mut ViewContext<Self>,
 1685    ) {
 1686        let placeholder_text = Some(placeholder_text.into());
 1687        if self.placeholder_text != placeholder_text {
 1688            self.placeholder_text = placeholder_text;
 1689            cx.notify();
 1690        }
 1691    }
 1692
 1693    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1694        self.cursor_shape = cursor_shape;
 1695
 1696        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1697        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1698
 1699        cx.notify();
 1700    }
 1701
 1702    pub fn set_current_line_highlight(
 1703        &mut self,
 1704        current_line_highlight: Option<CurrentLineHighlight>,
 1705    ) {
 1706        self.current_line_highlight = current_line_highlight;
 1707    }
 1708
 1709    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1710        self.collapse_matches = collapse_matches;
 1711    }
 1712
 1713    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1714        let buffers = self.buffer.read(cx).all_buffers();
 1715        let Some(lsp_store) = self.lsp_store(cx) else {
 1716            return;
 1717        };
 1718        lsp_store.update(cx, |lsp_store, cx| {
 1719            for buffer in buffers {
 1720                self.registered_buffers
 1721                    .entry(buffer.read(cx).remote_id())
 1722                    .or_insert_with(|| {
 1723                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1724                    });
 1725            }
 1726        })
 1727    }
 1728
 1729    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1730        if self.collapse_matches {
 1731            return range.start..range.start;
 1732        }
 1733        range.clone()
 1734    }
 1735
 1736    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1737        if self.display_map.read(cx).clip_at_line_ends != clip {
 1738            self.display_map
 1739                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1740        }
 1741    }
 1742
 1743    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1744        self.input_enabled = input_enabled;
 1745    }
 1746
 1747    pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
 1748        self.enable_inline_completions = enabled;
 1749        if !self.enable_inline_completions {
 1750            self.take_active_inline_completion(cx);
 1751            cx.notify();
 1752        }
 1753    }
 1754
 1755    pub fn set_autoindent(&mut self, autoindent: bool) {
 1756        if autoindent {
 1757            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1758        } else {
 1759            self.autoindent_mode = None;
 1760        }
 1761    }
 1762
 1763    pub fn read_only(&self, cx: &AppContext) -> bool {
 1764        self.read_only || self.buffer.read(cx).read_only()
 1765    }
 1766
 1767    pub fn set_read_only(&mut self, read_only: bool) {
 1768        self.read_only = read_only;
 1769    }
 1770
 1771    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1772        self.use_autoclose = autoclose;
 1773    }
 1774
 1775    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1776        self.use_auto_surround = auto_surround;
 1777    }
 1778
 1779    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1780        self.auto_replace_emoji_shortcode = auto_replace;
 1781    }
 1782
 1783    pub fn toggle_inline_completions(
 1784        &mut self,
 1785        _: &ToggleInlineCompletions,
 1786        cx: &mut ViewContext<Self>,
 1787    ) {
 1788        if self.show_inline_completions_override.is_some() {
 1789            self.set_show_inline_completions(None, cx);
 1790        } else {
 1791            let cursor = self.selections.newest_anchor().head();
 1792            if let Some((buffer, cursor_buffer_position)) =
 1793                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1794            {
 1795                let show_inline_completions =
 1796                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1797                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1798            }
 1799        }
 1800    }
 1801
 1802    pub fn set_show_inline_completions(
 1803        &mut self,
 1804        show_inline_completions: Option<bool>,
 1805        cx: &mut ViewContext<Self>,
 1806    ) {
 1807        self.show_inline_completions_override = show_inline_completions;
 1808        self.refresh_inline_completion(false, true, cx);
 1809    }
 1810
 1811    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1812        let cursor = self.selections.newest_anchor().head();
 1813        if let Some((buffer, buffer_position)) =
 1814            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1815        {
 1816            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1817        } else {
 1818            false
 1819        }
 1820    }
 1821
 1822    fn should_show_inline_completions(
 1823        &self,
 1824        buffer: &Model<Buffer>,
 1825        buffer_position: language::Anchor,
 1826        cx: &AppContext,
 1827    ) -> bool {
 1828        if !self.snippet_stack.is_empty() {
 1829            return false;
 1830        }
 1831
 1832        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1833            return false;
 1834        }
 1835
 1836        if let Some(provider) = self.inline_completion_provider() {
 1837            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1838                show_inline_completions
 1839            } else {
 1840                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1841            }
 1842        } else {
 1843            false
 1844        }
 1845    }
 1846
 1847    fn inline_completions_disabled_in_scope(
 1848        &self,
 1849        buffer: &Model<Buffer>,
 1850        buffer_position: language::Anchor,
 1851        cx: &AppContext,
 1852    ) -> bool {
 1853        let snapshot = buffer.read(cx).snapshot();
 1854        let settings = snapshot.settings_at(buffer_position, cx);
 1855
 1856        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1857            return false;
 1858        };
 1859
 1860        scope.override_name().map_or(false, |scope_name| {
 1861            settings
 1862                .inline_completions_disabled_in
 1863                .iter()
 1864                .any(|s| s == scope_name)
 1865        })
 1866    }
 1867
 1868    pub fn set_use_modal_editing(&mut self, to: bool) {
 1869        self.use_modal_editing = to;
 1870    }
 1871
 1872    pub fn use_modal_editing(&self) -> bool {
 1873        self.use_modal_editing
 1874    }
 1875
 1876    fn selections_did_change(
 1877        &mut self,
 1878        local: bool,
 1879        old_cursor_position: &Anchor,
 1880        show_completions: bool,
 1881        cx: &mut ViewContext<Self>,
 1882    ) {
 1883        cx.invalidate_character_coordinates();
 1884
 1885        // Copy selections to primary selection buffer
 1886        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1887        if local {
 1888            let selections = self.selections.all::<usize>(cx);
 1889            let buffer_handle = self.buffer.read(cx).read(cx);
 1890
 1891            let mut text = String::new();
 1892            for (index, selection) in selections.iter().enumerate() {
 1893                let text_for_selection = buffer_handle
 1894                    .text_for_range(selection.start..selection.end)
 1895                    .collect::<String>();
 1896
 1897                text.push_str(&text_for_selection);
 1898                if index != selections.len() - 1 {
 1899                    text.push('\n');
 1900                }
 1901            }
 1902
 1903            if !text.is_empty() {
 1904                cx.write_to_primary(ClipboardItem::new_string(text));
 1905            }
 1906        }
 1907
 1908        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1909            self.buffer.update(cx, |buffer, cx| {
 1910                buffer.set_active_selections(
 1911                    &self.selections.disjoint_anchors(),
 1912                    self.selections.line_mode,
 1913                    self.cursor_shape,
 1914                    cx,
 1915                )
 1916            });
 1917        }
 1918        let display_map = self
 1919            .display_map
 1920            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1921        let buffer = &display_map.buffer_snapshot;
 1922        self.add_selections_state = None;
 1923        self.select_next_state = None;
 1924        self.select_prev_state = None;
 1925        self.select_larger_syntax_node_stack.clear();
 1926        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1927        self.snippet_stack
 1928            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1929        self.take_rename(false, cx);
 1930
 1931        let new_cursor_position = self.selections.newest_anchor().head();
 1932
 1933        self.push_to_nav_history(
 1934            *old_cursor_position,
 1935            Some(new_cursor_position.to_point(buffer)),
 1936            cx,
 1937        );
 1938
 1939        if local {
 1940            let new_cursor_position = self.selections.newest_anchor().head();
 1941            let mut context_menu = self.context_menu.borrow_mut();
 1942            let completion_menu = match context_menu.as_ref() {
 1943                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1944                _ => {
 1945                    *context_menu = None;
 1946                    None
 1947                }
 1948            };
 1949
 1950            if let Some(completion_menu) = completion_menu {
 1951                let cursor_position = new_cursor_position.to_offset(buffer);
 1952                let (word_range, kind) =
 1953                    buffer.surrounding_word(completion_menu.initial_position, true);
 1954                if kind == Some(CharKind::Word)
 1955                    && word_range.to_inclusive().contains(&cursor_position)
 1956                {
 1957                    let mut completion_menu = completion_menu.clone();
 1958                    drop(context_menu);
 1959
 1960                    let query = Self::completion_query(buffer, cursor_position);
 1961                    cx.spawn(move |this, mut cx| async move {
 1962                        completion_menu
 1963                            .filter(query.as_deref(), cx.background_executor().clone())
 1964                            .await;
 1965
 1966                        this.update(&mut cx, |this, cx| {
 1967                            let mut context_menu = this.context_menu.borrow_mut();
 1968                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1969                            else {
 1970                                return;
 1971                            };
 1972
 1973                            if menu.id > completion_menu.id {
 1974                                return;
 1975                            }
 1976
 1977                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1978                            drop(context_menu);
 1979                            cx.notify();
 1980                        })
 1981                    })
 1982                    .detach();
 1983
 1984                    if show_completions {
 1985                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1986                    }
 1987                } else {
 1988                    drop(context_menu);
 1989                    self.hide_context_menu(cx);
 1990                }
 1991            } else {
 1992                drop(context_menu);
 1993            }
 1994
 1995            hide_hover(self, cx);
 1996
 1997            if old_cursor_position.to_display_point(&display_map).row()
 1998                != new_cursor_position.to_display_point(&display_map).row()
 1999            {
 2000                self.available_code_actions.take();
 2001            }
 2002            self.refresh_code_actions(cx);
 2003            self.refresh_document_highlights(cx);
 2004            refresh_matching_bracket_highlights(self, cx);
 2005            self.update_visible_inline_completion(cx);
 2006            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2007            if self.git_blame_inline_enabled {
 2008                self.start_inline_blame_timer(cx);
 2009            }
 2010        }
 2011
 2012        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2013        cx.emit(EditorEvent::SelectionsChanged { local });
 2014
 2015        if self.selections.disjoint_anchors().len() == 1 {
 2016            cx.emit(SearchEvent::ActiveMatchChanged)
 2017        }
 2018        cx.notify();
 2019    }
 2020
 2021    pub fn change_selections<R>(
 2022        &mut self,
 2023        autoscroll: Option<Autoscroll>,
 2024        cx: &mut ViewContext<Self>,
 2025        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2026    ) -> R {
 2027        self.change_selections_inner(autoscroll, true, cx, change)
 2028    }
 2029
 2030    pub fn change_selections_inner<R>(
 2031        &mut self,
 2032        autoscroll: Option<Autoscroll>,
 2033        request_completions: bool,
 2034        cx: &mut ViewContext<Self>,
 2035        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2036    ) -> R {
 2037        let old_cursor_position = self.selections.newest_anchor().head();
 2038        self.push_to_selection_history();
 2039
 2040        let (changed, result) = self.selections.change_with(cx, change);
 2041
 2042        if changed {
 2043            if let Some(autoscroll) = autoscroll {
 2044                self.request_autoscroll(autoscroll, cx);
 2045            }
 2046            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2047
 2048            if self.should_open_signature_help_automatically(
 2049                &old_cursor_position,
 2050                self.signature_help_state.backspace_pressed(),
 2051                cx,
 2052            ) {
 2053                self.show_signature_help(&ShowSignatureHelp, cx);
 2054            }
 2055            self.signature_help_state.set_backspace_pressed(false);
 2056        }
 2057
 2058        result
 2059    }
 2060
 2061    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2062    where
 2063        I: IntoIterator<Item = (Range<S>, T)>,
 2064        S: ToOffset,
 2065        T: Into<Arc<str>>,
 2066    {
 2067        if self.read_only(cx) {
 2068            return;
 2069        }
 2070
 2071        self.buffer
 2072            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2073    }
 2074
 2075    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2076    where
 2077        I: IntoIterator<Item = (Range<S>, T)>,
 2078        S: ToOffset,
 2079        T: Into<Arc<str>>,
 2080    {
 2081        if self.read_only(cx) {
 2082            return;
 2083        }
 2084
 2085        self.buffer.update(cx, |buffer, cx| {
 2086            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2087        });
 2088    }
 2089
 2090    pub fn edit_with_block_indent<I, S, T>(
 2091        &mut self,
 2092        edits: I,
 2093        original_indent_columns: Vec<u32>,
 2094        cx: &mut ViewContext<Self>,
 2095    ) where
 2096        I: IntoIterator<Item = (Range<S>, T)>,
 2097        S: ToOffset,
 2098        T: Into<Arc<str>>,
 2099    {
 2100        if self.read_only(cx) {
 2101            return;
 2102        }
 2103
 2104        self.buffer.update(cx, |buffer, cx| {
 2105            buffer.edit(
 2106                edits,
 2107                Some(AutoindentMode::Block {
 2108                    original_indent_columns,
 2109                }),
 2110                cx,
 2111            )
 2112        });
 2113    }
 2114
 2115    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2116        self.hide_context_menu(cx);
 2117
 2118        match phase {
 2119            SelectPhase::Begin {
 2120                position,
 2121                add,
 2122                click_count,
 2123            } => self.begin_selection(position, add, click_count, cx),
 2124            SelectPhase::BeginColumnar {
 2125                position,
 2126                goal_column,
 2127                reset,
 2128            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2129            SelectPhase::Extend {
 2130                position,
 2131                click_count,
 2132            } => self.extend_selection(position, click_count, cx),
 2133            SelectPhase::Update {
 2134                position,
 2135                goal_column,
 2136                scroll_delta,
 2137            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2138            SelectPhase::End => self.end_selection(cx),
 2139        }
 2140    }
 2141
 2142    fn extend_selection(
 2143        &mut self,
 2144        position: DisplayPoint,
 2145        click_count: usize,
 2146        cx: &mut ViewContext<Self>,
 2147    ) {
 2148        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2149        let tail = self.selections.newest::<usize>(cx).tail();
 2150        self.begin_selection(position, false, click_count, cx);
 2151
 2152        let position = position.to_offset(&display_map, Bias::Left);
 2153        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2154
 2155        let mut pending_selection = self
 2156            .selections
 2157            .pending_anchor()
 2158            .expect("extend_selection not called with pending selection");
 2159        if position >= tail {
 2160            pending_selection.start = tail_anchor;
 2161        } else {
 2162            pending_selection.end = tail_anchor;
 2163            pending_selection.reversed = true;
 2164        }
 2165
 2166        let mut pending_mode = self.selections.pending_mode().unwrap();
 2167        match &mut pending_mode {
 2168            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2169            _ => {}
 2170        }
 2171
 2172        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2173            s.set_pending(pending_selection, pending_mode)
 2174        });
 2175    }
 2176
 2177    fn begin_selection(
 2178        &mut self,
 2179        position: DisplayPoint,
 2180        add: bool,
 2181        click_count: usize,
 2182        cx: &mut ViewContext<Self>,
 2183    ) {
 2184        if !self.focus_handle.is_focused(cx) {
 2185            self.last_focused_descendant = None;
 2186            cx.focus(&self.focus_handle);
 2187        }
 2188
 2189        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2190        let buffer = &display_map.buffer_snapshot;
 2191        let newest_selection = self.selections.newest_anchor().clone();
 2192        let position = display_map.clip_point(position, Bias::Left);
 2193
 2194        let start;
 2195        let end;
 2196        let mode;
 2197        let mut auto_scroll;
 2198        match click_count {
 2199            1 => {
 2200                start = buffer.anchor_before(position.to_point(&display_map));
 2201                end = start;
 2202                mode = SelectMode::Character;
 2203                auto_scroll = true;
 2204            }
 2205            2 => {
 2206                let range = movement::surrounding_word(&display_map, position);
 2207                start = buffer.anchor_before(range.start.to_point(&display_map));
 2208                end = buffer.anchor_before(range.end.to_point(&display_map));
 2209                mode = SelectMode::Word(start..end);
 2210                auto_scroll = true;
 2211            }
 2212            3 => {
 2213                let position = display_map
 2214                    .clip_point(position, Bias::Left)
 2215                    .to_point(&display_map);
 2216                let line_start = display_map.prev_line_boundary(position).0;
 2217                let next_line_start = buffer.clip_point(
 2218                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2219                    Bias::Left,
 2220                );
 2221                start = buffer.anchor_before(line_start);
 2222                end = buffer.anchor_before(next_line_start);
 2223                mode = SelectMode::Line(start..end);
 2224                auto_scroll = true;
 2225            }
 2226            _ => {
 2227                start = buffer.anchor_before(0);
 2228                end = buffer.anchor_before(buffer.len());
 2229                mode = SelectMode::All;
 2230                auto_scroll = false;
 2231            }
 2232        }
 2233        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2234
 2235        let point_to_delete: Option<usize> = {
 2236            let selected_points: Vec<Selection<Point>> =
 2237                self.selections.disjoint_in_range(start..end, cx);
 2238
 2239            if !add || click_count > 1 {
 2240                None
 2241            } else if !selected_points.is_empty() {
 2242                Some(selected_points[0].id)
 2243            } else {
 2244                let clicked_point_already_selected =
 2245                    self.selections.disjoint.iter().find(|selection| {
 2246                        selection.start.to_point(buffer) == start.to_point(buffer)
 2247                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2248                    });
 2249
 2250                clicked_point_already_selected.map(|selection| selection.id)
 2251            }
 2252        };
 2253
 2254        let selections_count = self.selections.count();
 2255
 2256        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2257            if let Some(point_to_delete) = point_to_delete {
 2258                s.delete(point_to_delete);
 2259
 2260                if selections_count == 1 {
 2261                    s.set_pending_anchor_range(start..end, mode);
 2262                }
 2263            } else {
 2264                if !add {
 2265                    s.clear_disjoint();
 2266                } else if click_count > 1 {
 2267                    s.delete(newest_selection.id)
 2268                }
 2269
 2270                s.set_pending_anchor_range(start..end, mode);
 2271            }
 2272        });
 2273    }
 2274
 2275    fn begin_columnar_selection(
 2276        &mut self,
 2277        position: DisplayPoint,
 2278        goal_column: u32,
 2279        reset: bool,
 2280        cx: &mut ViewContext<Self>,
 2281    ) {
 2282        if !self.focus_handle.is_focused(cx) {
 2283            self.last_focused_descendant = None;
 2284            cx.focus(&self.focus_handle);
 2285        }
 2286
 2287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2288
 2289        if reset {
 2290            let pointer_position = display_map
 2291                .buffer_snapshot
 2292                .anchor_before(position.to_point(&display_map));
 2293
 2294            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2295                s.clear_disjoint();
 2296                s.set_pending_anchor_range(
 2297                    pointer_position..pointer_position,
 2298                    SelectMode::Character,
 2299                );
 2300            });
 2301        }
 2302
 2303        let tail = self.selections.newest::<Point>(cx).tail();
 2304        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2305
 2306        if !reset {
 2307            self.select_columns(
 2308                tail.to_display_point(&display_map),
 2309                position,
 2310                goal_column,
 2311                &display_map,
 2312                cx,
 2313            );
 2314        }
 2315    }
 2316
 2317    fn update_selection(
 2318        &mut self,
 2319        position: DisplayPoint,
 2320        goal_column: u32,
 2321        scroll_delta: gpui::Point<f32>,
 2322        cx: &mut ViewContext<Self>,
 2323    ) {
 2324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2325
 2326        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2327            let tail = tail.to_display_point(&display_map);
 2328            self.select_columns(tail, position, goal_column, &display_map, cx);
 2329        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2330            let buffer = self.buffer.read(cx).snapshot(cx);
 2331            let head;
 2332            let tail;
 2333            let mode = self.selections.pending_mode().unwrap();
 2334            match &mode {
 2335                SelectMode::Character => {
 2336                    head = position.to_point(&display_map);
 2337                    tail = pending.tail().to_point(&buffer);
 2338                }
 2339                SelectMode::Word(original_range) => {
 2340                    let original_display_range = original_range.start.to_display_point(&display_map)
 2341                        ..original_range.end.to_display_point(&display_map);
 2342                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2343                        ..original_display_range.end.to_point(&display_map);
 2344                    if movement::is_inside_word(&display_map, position)
 2345                        || original_display_range.contains(&position)
 2346                    {
 2347                        let word_range = movement::surrounding_word(&display_map, position);
 2348                        if word_range.start < original_display_range.start {
 2349                            head = word_range.start.to_point(&display_map);
 2350                        } else {
 2351                            head = word_range.end.to_point(&display_map);
 2352                        }
 2353                    } else {
 2354                        head = position.to_point(&display_map);
 2355                    }
 2356
 2357                    if head <= original_buffer_range.start {
 2358                        tail = original_buffer_range.end;
 2359                    } else {
 2360                        tail = original_buffer_range.start;
 2361                    }
 2362                }
 2363                SelectMode::Line(original_range) => {
 2364                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2365
 2366                    let position = display_map
 2367                        .clip_point(position, Bias::Left)
 2368                        .to_point(&display_map);
 2369                    let line_start = display_map.prev_line_boundary(position).0;
 2370                    let next_line_start = buffer.clip_point(
 2371                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2372                        Bias::Left,
 2373                    );
 2374
 2375                    if line_start < original_range.start {
 2376                        head = line_start
 2377                    } else {
 2378                        head = next_line_start
 2379                    }
 2380
 2381                    if head <= original_range.start {
 2382                        tail = original_range.end;
 2383                    } else {
 2384                        tail = original_range.start;
 2385                    }
 2386                }
 2387                SelectMode::All => {
 2388                    return;
 2389                }
 2390            };
 2391
 2392            if head < tail {
 2393                pending.start = buffer.anchor_before(head);
 2394                pending.end = buffer.anchor_before(tail);
 2395                pending.reversed = true;
 2396            } else {
 2397                pending.start = buffer.anchor_before(tail);
 2398                pending.end = buffer.anchor_before(head);
 2399                pending.reversed = false;
 2400            }
 2401
 2402            self.change_selections(None, cx, |s| {
 2403                s.set_pending(pending, mode);
 2404            });
 2405        } else {
 2406            log::error!("update_selection dispatched with no pending selection");
 2407            return;
 2408        }
 2409
 2410        self.apply_scroll_delta(scroll_delta, cx);
 2411        cx.notify();
 2412    }
 2413
 2414    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2415        self.columnar_selection_tail.take();
 2416        if self.selections.pending_anchor().is_some() {
 2417            let selections = self.selections.all::<usize>(cx);
 2418            self.change_selections(None, cx, |s| {
 2419                s.select(selections);
 2420                s.clear_pending();
 2421            });
 2422        }
 2423    }
 2424
 2425    fn select_columns(
 2426        &mut self,
 2427        tail: DisplayPoint,
 2428        head: DisplayPoint,
 2429        goal_column: u32,
 2430        display_map: &DisplaySnapshot,
 2431        cx: &mut ViewContext<Self>,
 2432    ) {
 2433        let start_row = cmp::min(tail.row(), head.row());
 2434        let end_row = cmp::max(tail.row(), head.row());
 2435        let start_column = cmp::min(tail.column(), goal_column);
 2436        let end_column = cmp::max(tail.column(), goal_column);
 2437        let reversed = start_column < tail.column();
 2438
 2439        let selection_ranges = (start_row.0..=end_row.0)
 2440            .map(DisplayRow)
 2441            .filter_map(|row| {
 2442                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2443                    let start = display_map
 2444                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2445                        .to_point(display_map);
 2446                    let end = display_map
 2447                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2448                        .to_point(display_map);
 2449                    if reversed {
 2450                        Some(end..start)
 2451                    } else {
 2452                        Some(start..end)
 2453                    }
 2454                } else {
 2455                    None
 2456                }
 2457            })
 2458            .collect::<Vec<_>>();
 2459
 2460        self.change_selections(None, cx, |s| {
 2461            s.select_ranges(selection_ranges);
 2462        });
 2463        cx.notify();
 2464    }
 2465
 2466    pub fn has_pending_nonempty_selection(&self) -> bool {
 2467        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2468            Some(Selection { start, end, .. }) => start != end,
 2469            None => false,
 2470        };
 2471
 2472        pending_nonempty_selection
 2473            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2474    }
 2475
 2476    pub fn has_pending_selection(&self) -> bool {
 2477        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2478    }
 2479
 2480    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2481        if self.clear_expanded_diff_hunks(cx) {
 2482            cx.notify();
 2483            return;
 2484        }
 2485        if self.dismiss_menus_and_popups(true, cx) {
 2486            return;
 2487        }
 2488
 2489        if self.mode == EditorMode::Full
 2490            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2491        {
 2492            return;
 2493        }
 2494
 2495        cx.propagate();
 2496    }
 2497
 2498    pub fn dismiss_menus_and_popups(
 2499        &mut self,
 2500        should_report_inline_completion_event: bool,
 2501        cx: &mut ViewContext<Self>,
 2502    ) -> bool {
 2503        if self.take_rename(false, cx).is_some() {
 2504            return true;
 2505        }
 2506
 2507        if hide_hover(self, cx) {
 2508            return true;
 2509        }
 2510
 2511        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2512            return true;
 2513        }
 2514
 2515        if self.hide_context_menu(cx).is_some() {
 2516            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2517                self.update_visible_inline_completion(cx);
 2518            }
 2519            return true;
 2520        }
 2521
 2522        if self.mouse_context_menu.take().is_some() {
 2523            return true;
 2524        }
 2525
 2526        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2527            return true;
 2528        }
 2529
 2530        if self.snippet_stack.pop().is_some() {
 2531            return true;
 2532        }
 2533
 2534        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2535            self.dismiss_diagnostics(cx);
 2536            return true;
 2537        }
 2538
 2539        false
 2540    }
 2541
 2542    fn linked_editing_ranges_for(
 2543        &self,
 2544        selection: Range<text::Anchor>,
 2545        cx: &AppContext,
 2546    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2547        if self.linked_edit_ranges.is_empty() {
 2548            return None;
 2549        }
 2550        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2551            selection.end.buffer_id.and_then(|end_buffer_id| {
 2552                if selection.start.buffer_id != Some(end_buffer_id) {
 2553                    return None;
 2554                }
 2555                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2556                let snapshot = buffer.read(cx).snapshot();
 2557                self.linked_edit_ranges
 2558                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2559                    .map(|ranges| (ranges, snapshot, buffer))
 2560            })?;
 2561        use text::ToOffset as TO;
 2562        // find offset from the start of current range to current cursor position
 2563        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2564
 2565        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2566        let start_difference = start_offset - start_byte_offset;
 2567        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2568        let end_difference = end_offset - start_byte_offset;
 2569        // Current range has associated linked ranges.
 2570        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2571        for range in linked_ranges.iter() {
 2572            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2573            let end_offset = start_offset + end_difference;
 2574            let start_offset = start_offset + start_difference;
 2575            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2576                continue;
 2577            }
 2578            if self.selections.disjoint_anchor_ranges().any(|s| {
 2579                if s.start.buffer_id != selection.start.buffer_id
 2580                    || s.end.buffer_id != selection.end.buffer_id
 2581                {
 2582                    return false;
 2583                }
 2584                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2585                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2586            }) {
 2587                continue;
 2588            }
 2589            let start = buffer_snapshot.anchor_after(start_offset);
 2590            let end = buffer_snapshot.anchor_after(end_offset);
 2591            linked_edits
 2592                .entry(buffer.clone())
 2593                .or_default()
 2594                .push(start..end);
 2595        }
 2596        Some(linked_edits)
 2597    }
 2598
 2599    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2600        let text: Arc<str> = text.into();
 2601
 2602        if self.read_only(cx) {
 2603            return;
 2604        }
 2605
 2606        let selections = self.selections.all_adjusted(cx);
 2607        let mut bracket_inserted = false;
 2608        let mut edits = Vec::new();
 2609        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2610        let mut new_selections = Vec::with_capacity(selections.len());
 2611        let mut new_autoclose_regions = Vec::new();
 2612        let snapshot = self.buffer.read(cx).read(cx);
 2613
 2614        for (selection, autoclose_region) in
 2615            self.selections_with_autoclose_regions(selections, &snapshot)
 2616        {
 2617            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2618                // Determine if the inserted text matches the opening or closing
 2619                // bracket of any of this language's bracket pairs.
 2620                let mut bracket_pair = None;
 2621                let mut is_bracket_pair_start = false;
 2622                let mut is_bracket_pair_end = false;
 2623                if !text.is_empty() {
 2624                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2625                    //  and they are removing the character that triggered IME popup.
 2626                    for (pair, enabled) in scope.brackets() {
 2627                        if !pair.close && !pair.surround {
 2628                            continue;
 2629                        }
 2630
 2631                        if enabled && pair.start.ends_with(text.as_ref()) {
 2632                            let prefix_len = pair.start.len() - text.len();
 2633                            let preceding_text_matches_prefix = prefix_len == 0
 2634                                || (selection.start.column >= (prefix_len as u32)
 2635                                    && snapshot.contains_str_at(
 2636                                        Point::new(
 2637                                            selection.start.row,
 2638                                            selection.start.column - (prefix_len as u32),
 2639                                        ),
 2640                                        &pair.start[..prefix_len],
 2641                                    ));
 2642                            if preceding_text_matches_prefix {
 2643                                bracket_pair = Some(pair.clone());
 2644                                is_bracket_pair_start = true;
 2645                                break;
 2646                            }
 2647                        }
 2648                        if pair.end.as_str() == text.as_ref() {
 2649                            bracket_pair = Some(pair.clone());
 2650                            is_bracket_pair_end = true;
 2651                            break;
 2652                        }
 2653                    }
 2654                }
 2655
 2656                if let Some(bracket_pair) = bracket_pair {
 2657                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2658                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2659                    let auto_surround =
 2660                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2661                    if selection.is_empty() {
 2662                        if is_bracket_pair_start {
 2663                            // If the inserted text is a suffix of an opening bracket and the
 2664                            // selection is preceded by the rest of the opening bracket, then
 2665                            // insert the closing bracket.
 2666                            let following_text_allows_autoclose = snapshot
 2667                                .chars_at(selection.start)
 2668                                .next()
 2669                                .map_or(true, |c| scope.should_autoclose_before(c));
 2670
 2671                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2672                                && bracket_pair.start.len() == 1
 2673                            {
 2674                                let target = bracket_pair.start.chars().next().unwrap();
 2675                                let current_line_count = snapshot
 2676                                    .reversed_chars_at(selection.start)
 2677                                    .take_while(|&c| c != '\n')
 2678                                    .filter(|&c| c == target)
 2679                                    .count();
 2680                                current_line_count % 2 == 1
 2681                            } else {
 2682                                false
 2683                            };
 2684
 2685                            if autoclose
 2686                                && bracket_pair.close
 2687                                && following_text_allows_autoclose
 2688                                && !is_closing_quote
 2689                            {
 2690                                let anchor = snapshot.anchor_before(selection.end);
 2691                                new_selections.push((selection.map(|_| anchor), text.len()));
 2692                                new_autoclose_regions.push((
 2693                                    anchor,
 2694                                    text.len(),
 2695                                    selection.id,
 2696                                    bracket_pair.clone(),
 2697                                ));
 2698                                edits.push((
 2699                                    selection.range(),
 2700                                    format!("{}{}", text, bracket_pair.end).into(),
 2701                                ));
 2702                                bracket_inserted = true;
 2703                                continue;
 2704                            }
 2705                        }
 2706
 2707                        if let Some(region) = autoclose_region {
 2708                            // If the selection is followed by an auto-inserted closing bracket,
 2709                            // then don't insert that closing bracket again; just move the selection
 2710                            // past the closing bracket.
 2711                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2712                                && text.as_ref() == region.pair.end.as_str();
 2713                            if should_skip {
 2714                                let anchor = snapshot.anchor_after(selection.end);
 2715                                new_selections
 2716                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2717                                continue;
 2718                            }
 2719                        }
 2720
 2721                        let always_treat_brackets_as_autoclosed = snapshot
 2722                            .settings_at(selection.start, cx)
 2723                            .always_treat_brackets_as_autoclosed;
 2724                        if always_treat_brackets_as_autoclosed
 2725                            && is_bracket_pair_end
 2726                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2727                        {
 2728                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2729                            // and the inserted text is a closing bracket and the selection is followed
 2730                            // by the closing bracket then move the selection past the closing bracket.
 2731                            let anchor = snapshot.anchor_after(selection.end);
 2732                            new_selections.push((selection.map(|_| anchor), text.len()));
 2733                            continue;
 2734                        }
 2735                    }
 2736                    // If an opening bracket is 1 character long and is typed while
 2737                    // text is selected, then surround that text with the bracket pair.
 2738                    else if auto_surround
 2739                        && bracket_pair.surround
 2740                        && is_bracket_pair_start
 2741                        && bracket_pair.start.chars().count() == 1
 2742                    {
 2743                        edits.push((selection.start..selection.start, text.clone()));
 2744                        edits.push((
 2745                            selection.end..selection.end,
 2746                            bracket_pair.end.as_str().into(),
 2747                        ));
 2748                        bracket_inserted = true;
 2749                        new_selections.push((
 2750                            Selection {
 2751                                id: selection.id,
 2752                                start: snapshot.anchor_after(selection.start),
 2753                                end: snapshot.anchor_before(selection.end),
 2754                                reversed: selection.reversed,
 2755                                goal: selection.goal,
 2756                            },
 2757                            0,
 2758                        ));
 2759                        continue;
 2760                    }
 2761                }
 2762            }
 2763
 2764            if self.auto_replace_emoji_shortcode
 2765                && selection.is_empty()
 2766                && text.as_ref().ends_with(':')
 2767            {
 2768                if let Some(possible_emoji_short_code) =
 2769                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2770                {
 2771                    if !possible_emoji_short_code.is_empty() {
 2772                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2773                            let emoji_shortcode_start = Point::new(
 2774                                selection.start.row,
 2775                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2776                            );
 2777
 2778                            // Remove shortcode from buffer
 2779                            edits.push((
 2780                                emoji_shortcode_start..selection.start,
 2781                                "".to_string().into(),
 2782                            ));
 2783                            new_selections.push((
 2784                                Selection {
 2785                                    id: selection.id,
 2786                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2787                                    end: snapshot.anchor_before(selection.start),
 2788                                    reversed: selection.reversed,
 2789                                    goal: selection.goal,
 2790                                },
 2791                                0,
 2792                            ));
 2793
 2794                            // Insert emoji
 2795                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2796                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2797                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2798
 2799                            continue;
 2800                        }
 2801                    }
 2802                }
 2803            }
 2804
 2805            // If not handling any auto-close operation, then just replace the selected
 2806            // text with the given input and move the selection to the end of the
 2807            // newly inserted text.
 2808            let anchor = snapshot.anchor_after(selection.end);
 2809            if !self.linked_edit_ranges.is_empty() {
 2810                let start_anchor = snapshot.anchor_before(selection.start);
 2811
 2812                let is_word_char = text.chars().next().map_or(true, |char| {
 2813                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2814                    classifier.is_word(char)
 2815                });
 2816
 2817                if is_word_char {
 2818                    if let Some(ranges) = self
 2819                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2820                    {
 2821                        for (buffer, edits) in ranges {
 2822                            linked_edits
 2823                                .entry(buffer.clone())
 2824                                .or_default()
 2825                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2826                        }
 2827                    }
 2828                }
 2829            }
 2830
 2831            new_selections.push((selection.map(|_| anchor), 0));
 2832            edits.push((selection.start..selection.end, text.clone()));
 2833        }
 2834
 2835        drop(snapshot);
 2836
 2837        self.transact(cx, |this, cx| {
 2838            this.buffer.update(cx, |buffer, cx| {
 2839                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2840            });
 2841            for (buffer, edits) in linked_edits {
 2842                buffer.update(cx, |buffer, cx| {
 2843                    let snapshot = buffer.snapshot();
 2844                    let edits = edits
 2845                        .into_iter()
 2846                        .map(|(range, text)| {
 2847                            use text::ToPoint as TP;
 2848                            let end_point = TP::to_point(&range.end, &snapshot);
 2849                            let start_point = TP::to_point(&range.start, &snapshot);
 2850                            (start_point..end_point, text)
 2851                        })
 2852                        .sorted_by_key(|(range, _)| range.start)
 2853                        .collect::<Vec<_>>();
 2854                    buffer.edit(edits, None, cx);
 2855                })
 2856            }
 2857            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2858            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2859            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2860            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2861                .zip(new_selection_deltas)
 2862                .map(|(selection, delta)| Selection {
 2863                    id: selection.id,
 2864                    start: selection.start + delta,
 2865                    end: selection.end + delta,
 2866                    reversed: selection.reversed,
 2867                    goal: SelectionGoal::None,
 2868                })
 2869                .collect::<Vec<_>>();
 2870
 2871            let mut i = 0;
 2872            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2873                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2874                let start = map.buffer_snapshot.anchor_before(position);
 2875                let end = map.buffer_snapshot.anchor_after(position);
 2876                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2877                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2878                        Ordering::Less => i += 1,
 2879                        Ordering::Greater => break,
 2880                        Ordering::Equal => {
 2881                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2882                                Ordering::Less => i += 1,
 2883                                Ordering::Equal => break,
 2884                                Ordering::Greater => break,
 2885                            }
 2886                        }
 2887                    }
 2888                }
 2889                this.autoclose_regions.insert(
 2890                    i,
 2891                    AutocloseRegion {
 2892                        selection_id,
 2893                        range: start..end,
 2894                        pair,
 2895                    },
 2896                );
 2897            }
 2898
 2899            let had_active_inline_completion = this.has_active_inline_completion();
 2900            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2901                s.select(new_selections)
 2902            });
 2903
 2904            if !bracket_inserted {
 2905                if let Some(on_type_format_task) =
 2906                    this.trigger_on_type_formatting(text.to_string(), cx)
 2907                {
 2908                    on_type_format_task.detach_and_log_err(cx);
 2909                }
 2910            }
 2911
 2912            let editor_settings = EditorSettings::get_global(cx);
 2913            if bracket_inserted
 2914                && (editor_settings.auto_signature_help
 2915                    || editor_settings.show_signature_help_after_edits)
 2916            {
 2917                this.show_signature_help(&ShowSignatureHelp, cx);
 2918            }
 2919
 2920            let trigger_in_words =
 2921                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2922            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2923            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2924            this.refresh_inline_completion(true, false, cx);
 2925        });
 2926    }
 2927
 2928    fn find_possible_emoji_shortcode_at_position(
 2929        snapshot: &MultiBufferSnapshot,
 2930        position: Point,
 2931    ) -> Option<String> {
 2932        let mut chars = Vec::new();
 2933        let mut found_colon = false;
 2934        for char in snapshot.reversed_chars_at(position).take(100) {
 2935            // Found a possible emoji shortcode in the middle of the buffer
 2936            if found_colon {
 2937                if char.is_whitespace() {
 2938                    chars.reverse();
 2939                    return Some(chars.iter().collect());
 2940                }
 2941                // If the previous character is not a whitespace, we are in the middle of a word
 2942                // and we only want to complete the shortcode if the word is made up of other emojis
 2943                let mut containing_word = String::new();
 2944                for ch in snapshot
 2945                    .reversed_chars_at(position)
 2946                    .skip(chars.len() + 1)
 2947                    .take(100)
 2948                {
 2949                    if ch.is_whitespace() {
 2950                        break;
 2951                    }
 2952                    containing_word.push(ch);
 2953                }
 2954                let containing_word = containing_word.chars().rev().collect::<String>();
 2955                if util::word_consists_of_emojis(containing_word.as_str()) {
 2956                    chars.reverse();
 2957                    return Some(chars.iter().collect());
 2958                }
 2959            }
 2960
 2961            if char.is_whitespace() || !char.is_ascii() {
 2962                return None;
 2963            }
 2964            if char == ':' {
 2965                found_colon = true;
 2966            } else {
 2967                chars.push(char);
 2968            }
 2969        }
 2970        // Found a possible emoji shortcode at the beginning of the buffer
 2971        chars.reverse();
 2972        Some(chars.iter().collect())
 2973    }
 2974
 2975    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2976        self.transact(cx, |this, cx| {
 2977            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2978                let selections = this.selections.all::<usize>(cx);
 2979                let multi_buffer = this.buffer.read(cx);
 2980                let buffer = multi_buffer.snapshot(cx);
 2981                selections
 2982                    .iter()
 2983                    .map(|selection| {
 2984                        let start_point = selection.start.to_point(&buffer);
 2985                        let mut indent =
 2986                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2987                        indent.len = cmp::min(indent.len, start_point.column);
 2988                        let start = selection.start;
 2989                        let end = selection.end;
 2990                        let selection_is_empty = start == end;
 2991                        let language_scope = buffer.language_scope_at(start);
 2992                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2993                            &language_scope
 2994                        {
 2995                            let leading_whitespace_len = buffer
 2996                                .reversed_chars_at(start)
 2997                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2998                                .map(|c| c.len_utf8())
 2999                                .sum::<usize>();
 3000
 3001                            let trailing_whitespace_len = buffer
 3002                                .chars_at(end)
 3003                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3004                                .map(|c| c.len_utf8())
 3005                                .sum::<usize>();
 3006
 3007                            let insert_extra_newline =
 3008                                language.brackets().any(|(pair, enabled)| {
 3009                                    let pair_start = pair.start.trim_end();
 3010                                    let pair_end = pair.end.trim_start();
 3011
 3012                                    enabled
 3013                                        && pair.newline
 3014                                        && buffer.contains_str_at(
 3015                                            end + trailing_whitespace_len,
 3016                                            pair_end,
 3017                                        )
 3018                                        && buffer.contains_str_at(
 3019                                            (start - leading_whitespace_len)
 3020                                                .saturating_sub(pair_start.len()),
 3021                                            pair_start,
 3022                                        )
 3023                                });
 3024
 3025                            // Comment extension on newline is allowed only for cursor selections
 3026                            let comment_delimiter = maybe!({
 3027                                if !selection_is_empty {
 3028                                    return None;
 3029                                }
 3030
 3031                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3032                                    return None;
 3033                                }
 3034
 3035                                let delimiters = language.line_comment_prefixes();
 3036                                let max_len_of_delimiter =
 3037                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3038                                let (snapshot, range) =
 3039                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3040
 3041                                let mut index_of_first_non_whitespace = 0;
 3042                                let comment_candidate = snapshot
 3043                                    .chars_for_range(range)
 3044                                    .skip_while(|c| {
 3045                                        let should_skip = c.is_whitespace();
 3046                                        if should_skip {
 3047                                            index_of_first_non_whitespace += 1;
 3048                                        }
 3049                                        should_skip
 3050                                    })
 3051                                    .take(max_len_of_delimiter)
 3052                                    .collect::<String>();
 3053                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3054                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3055                                })?;
 3056                                let cursor_is_placed_after_comment_marker =
 3057                                    index_of_first_non_whitespace + comment_prefix.len()
 3058                                        <= start_point.column as usize;
 3059                                if cursor_is_placed_after_comment_marker {
 3060                                    Some(comment_prefix.clone())
 3061                                } else {
 3062                                    None
 3063                                }
 3064                            });
 3065                            (comment_delimiter, insert_extra_newline)
 3066                        } else {
 3067                            (None, false)
 3068                        };
 3069
 3070                        let capacity_for_delimiter = comment_delimiter
 3071                            .as_deref()
 3072                            .map(str::len)
 3073                            .unwrap_or_default();
 3074                        let mut new_text =
 3075                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3076                        new_text.push('\n');
 3077                        new_text.extend(indent.chars());
 3078                        if let Some(delimiter) = &comment_delimiter {
 3079                            new_text.push_str(delimiter);
 3080                        }
 3081                        if insert_extra_newline {
 3082                            new_text = new_text.repeat(2);
 3083                        }
 3084
 3085                        let anchor = buffer.anchor_after(end);
 3086                        let new_selection = selection.map(|_| anchor);
 3087                        (
 3088                            (start..end, new_text),
 3089                            (insert_extra_newline, new_selection),
 3090                        )
 3091                    })
 3092                    .unzip()
 3093            };
 3094
 3095            this.edit_with_autoindent(edits, cx);
 3096            let buffer = this.buffer.read(cx).snapshot(cx);
 3097            let new_selections = selection_fixup_info
 3098                .into_iter()
 3099                .map(|(extra_newline_inserted, new_selection)| {
 3100                    let mut cursor = new_selection.end.to_point(&buffer);
 3101                    if extra_newline_inserted {
 3102                        cursor.row -= 1;
 3103                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3104                    }
 3105                    new_selection.map(|_| cursor)
 3106                })
 3107                .collect();
 3108
 3109            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3110            this.refresh_inline_completion(true, false, cx);
 3111        });
 3112    }
 3113
 3114    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3115        let buffer = self.buffer.read(cx);
 3116        let snapshot = buffer.snapshot(cx);
 3117
 3118        let mut edits = Vec::new();
 3119        let mut rows = Vec::new();
 3120
 3121        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3122            let cursor = selection.head();
 3123            let row = cursor.row;
 3124
 3125            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3126
 3127            let newline = "\n".to_string();
 3128            edits.push((start_of_line..start_of_line, newline));
 3129
 3130            rows.push(row + rows_inserted as u32);
 3131        }
 3132
 3133        self.transact(cx, |editor, cx| {
 3134            editor.edit(edits, cx);
 3135
 3136            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3137                let mut index = 0;
 3138                s.move_cursors_with(|map, _, _| {
 3139                    let row = rows[index];
 3140                    index += 1;
 3141
 3142                    let point = Point::new(row, 0);
 3143                    let boundary = map.next_line_boundary(point).1;
 3144                    let clipped = map.clip_point(boundary, Bias::Left);
 3145
 3146                    (clipped, SelectionGoal::None)
 3147                });
 3148            });
 3149
 3150            let mut indent_edits = Vec::new();
 3151            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3152            for row in rows {
 3153                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3154                for (row, indent) in indents {
 3155                    if indent.len == 0 {
 3156                        continue;
 3157                    }
 3158
 3159                    let text = match indent.kind {
 3160                        IndentKind::Space => " ".repeat(indent.len as usize),
 3161                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3162                    };
 3163                    let point = Point::new(row.0, 0);
 3164                    indent_edits.push((point..point, text));
 3165                }
 3166            }
 3167            editor.edit(indent_edits, cx);
 3168        });
 3169    }
 3170
 3171    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3172        let buffer = self.buffer.read(cx);
 3173        let snapshot = buffer.snapshot(cx);
 3174
 3175        let mut edits = Vec::new();
 3176        let mut rows = Vec::new();
 3177        let mut rows_inserted = 0;
 3178
 3179        for selection in self.selections.all_adjusted(cx) {
 3180            let cursor = selection.head();
 3181            let row = cursor.row;
 3182
 3183            let point = Point::new(row + 1, 0);
 3184            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3185
 3186            let newline = "\n".to_string();
 3187            edits.push((start_of_line..start_of_line, newline));
 3188
 3189            rows_inserted += 1;
 3190            rows.push(row + rows_inserted);
 3191        }
 3192
 3193        self.transact(cx, |editor, cx| {
 3194            editor.edit(edits, cx);
 3195
 3196            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3197                let mut index = 0;
 3198                s.move_cursors_with(|map, _, _| {
 3199                    let row = rows[index];
 3200                    index += 1;
 3201
 3202                    let point = Point::new(row, 0);
 3203                    let boundary = map.next_line_boundary(point).1;
 3204                    let clipped = map.clip_point(boundary, Bias::Left);
 3205
 3206                    (clipped, SelectionGoal::None)
 3207                });
 3208            });
 3209
 3210            let mut indent_edits = Vec::new();
 3211            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3212            for row in rows {
 3213                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3214                for (row, indent) in indents {
 3215                    if indent.len == 0 {
 3216                        continue;
 3217                    }
 3218
 3219                    let text = match indent.kind {
 3220                        IndentKind::Space => " ".repeat(indent.len as usize),
 3221                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3222                    };
 3223                    let point = Point::new(row.0, 0);
 3224                    indent_edits.push((point..point, text));
 3225                }
 3226            }
 3227            editor.edit(indent_edits, cx);
 3228        });
 3229    }
 3230
 3231    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3232        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3233            original_indent_columns: Vec::new(),
 3234        });
 3235        self.insert_with_autoindent_mode(text, autoindent, cx);
 3236    }
 3237
 3238    fn insert_with_autoindent_mode(
 3239        &mut self,
 3240        text: &str,
 3241        autoindent_mode: Option<AutoindentMode>,
 3242        cx: &mut ViewContext<Self>,
 3243    ) {
 3244        if self.read_only(cx) {
 3245            return;
 3246        }
 3247
 3248        let text: Arc<str> = text.into();
 3249        self.transact(cx, |this, cx| {
 3250            let old_selections = this.selections.all_adjusted(cx);
 3251            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3252                let anchors = {
 3253                    let snapshot = buffer.read(cx);
 3254                    old_selections
 3255                        .iter()
 3256                        .map(|s| {
 3257                            let anchor = snapshot.anchor_after(s.head());
 3258                            s.map(|_| anchor)
 3259                        })
 3260                        .collect::<Vec<_>>()
 3261                };
 3262                buffer.edit(
 3263                    old_selections
 3264                        .iter()
 3265                        .map(|s| (s.start..s.end, text.clone())),
 3266                    autoindent_mode,
 3267                    cx,
 3268                );
 3269                anchors
 3270            });
 3271
 3272            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3273                s.select_anchors(selection_anchors);
 3274            })
 3275        });
 3276    }
 3277
 3278    fn trigger_completion_on_input(
 3279        &mut self,
 3280        text: &str,
 3281        trigger_in_words: bool,
 3282        cx: &mut ViewContext<Self>,
 3283    ) {
 3284        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3285            self.show_completions(
 3286                &ShowCompletions {
 3287                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3288                },
 3289                cx,
 3290            );
 3291        } else {
 3292            self.hide_context_menu(cx);
 3293        }
 3294    }
 3295
 3296    fn is_completion_trigger(
 3297        &self,
 3298        text: &str,
 3299        trigger_in_words: bool,
 3300        cx: &mut ViewContext<Self>,
 3301    ) -> bool {
 3302        let position = self.selections.newest_anchor().head();
 3303        let multibuffer = self.buffer.read(cx);
 3304        let Some(buffer) = position
 3305            .buffer_id
 3306            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3307        else {
 3308            return false;
 3309        };
 3310
 3311        if let Some(completion_provider) = &self.completion_provider {
 3312            completion_provider.is_completion_trigger(
 3313                &buffer,
 3314                position.text_anchor,
 3315                text,
 3316                trigger_in_words,
 3317                cx,
 3318            )
 3319        } else {
 3320            false
 3321        }
 3322    }
 3323
 3324    /// If any empty selections is touching the start of its innermost containing autoclose
 3325    /// region, expand it to select the brackets.
 3326    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3327        let selections = self.selections.all::<usize>(cx);
 3328        let buffer = self.buffer.read(cx).read(cx);
 3329        let new_selections = self
 3330            .selections_with_autoclose_regions(selections, &buffer)
 3331            .map(|(mut selection, region)| {
 3332                if !selection.is_empty() {
 3333                    return selection;
 3334                }
 3335
 3336                if let Some(region) = region {
 3337                    let mut range = region.range.to_offset(&buffer);
 3338                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3339                        range.start -= region.pair.start.len();
 3340                        if buffer.contains_str_at(range.start, &region.pair.start)
 3341                            && buffer.contains_str_at(range.end, &region.pair.end)
 3342                        {
 3343                            range.end += region.pair.end.len();
 3344                            selection.start = range.start;
 3345                            selection.end = range.end;
 3346
 3347                            return selection;
 3348                        }
 3349                    }
 3350                }
 3351
 3352                let always_treat_brackets_as_autoclosed = buffer
 3353                    .settings_at(selection.start, cx)
 3354                    .always_treat_brackets_as_autoclosed;
 3355
 3356                if !always_treat_brackets_as_autoclosed {
 3357                    return selection;
 3358                }
 3359
 3360                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3361                    for (pair, enabled) in scope.brackets() {
 3362                        if !enabled || !pair.close {
 3363                            continue;
 3364                        }
 3365
 3366                        if buffer.contains_str_at(selection.start, &pair.end) {
 3367                            let pair_start_len = pair.start.len();
 3368                            if buffer.contains_str_at(
 3369                                selection.start.saturating_sub(pair_start_len),
 3370                                &pair.start,
 3371                            ) {
 3372                                selection.start -= pair_start_len;
 3373                                selection.end += pair.end.len();
 3374
 3375                                return selection;
 3376                            }
 3377                        }
 3378                    }
 3379                }
 3380
 3381                selection
 3382            })
 3383            .collect();
 3384
 3385        drop(buffer);
 3386        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3387    }
 3388
 3389    /// Iterate the given selections, and for each one, find the smallest surrounding
 3390    /// autoclose region. This uses the ordering of the selections and the autoclose
 3391    /// regions to avoid repeated comparisons.
 3392    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3393        &'a self,
 3394        selections: impl IntoIterator<Item = Selection<D>>,
 3395        buffer: &'a MultiBufferSnapshot,
 3396    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3397        let mut i = 0;
 3398        let mut regions = self.autoclose_regions.as_slice();
 3399        selections.into_iter().map(move |selection| {
 3400            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3401
 3402            let mut enclosing = None;
 3403            while let Some(pair_state) = regions.get(i) {
 3404                if pair_state.range.end.to_offset(buffer) < range.start {
 3405                    regions = &regions[i + 1..];
 3406                    i = 0;
 3407                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3408                    break;
 3409                } else {
 3410                    if pair_state.selection_id == selection.id {
 3411                        enclosing = Some(pair_state);
 3412                    }
 3413                    i += 1;
 3414                }
 3415            }
 3416
 3417            (selection, enclosing)
 3418        })
 3419    }
 3420
 3421    /// Remove any autoclose regions that no longer contain their selection.
 3422    fn invalidate_autoclose_regions(
 3423        &mut self,
 3424        mut selections: &[Selection<Anchor>],
 3425        buffer: &MultiBufferSnapshot,
 3426    ) {
 3427        self.autoclose_regions.retain(|state| {
 3428            let mut i = 0;
 3429            while let Some(selection) = selections.get(i) {
 3430                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3431                    selections = &selections[1..];
 3432                    continue;
 3433                }
 3434                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3435                    break;
 3436                }
 3437                if selection.id == state.selection_id {
 3438                    return true;
 3439                } else {
 3440                    i += 1;
 3441                }
 3442            }
 3443            false
 3444        });
 3445    }
 3446
 3447    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3448        let offset = position.to_offset(buffer);
 3449        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3450        if offset > word_range.start && kind == Some(CharKind::Word) {
 3451            Some(
 3452                buffer
 3453                    .text_for_range(word_range.start..offset)
 3454                    .collect::<String>(),
 3455            )
 3456        } else {
 3457            None
 3458        }
 3459    }
 3460
 3461    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3462        self.refresh_inlay_hints(
 3463            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3464            cx,
 3465        );
 3466    }
 3467
 3468    pub fn inlay_hints_enabled(&self) -> bool {
 3469        self.inlay_hint_cache.enabled
 3470    }
 3471
 3472    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3473        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3474            return;
 3475        }
 3476
 3477        let reason_description = reason.description();
 3478        let ignore_debounce = matches!(
 3479            reason,
 3480            InlayHintRefreshReason::SettingsChange(_)
 3481                | InlayHintRefreshReason::Toggle(_)
 3482                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3483        );
 3484        let (invalidate_cache, required_languages) = match reason {
 3485            InlayHintRefreshReason::Toggle(enabled) => {
 3486                self.inlay_hint_cache.enabled = enabled;
 3487                if enabled {
 3488                    (InvalidationStrategy::RefreshRequested, None)
 3489                } else {
 3490                    self.inlay_hint_cache.clear();
 3491                    self.splice_inlays(
 3492                        self.visible_inlay_hints(cx)
 3493                            .iter()
 3494                            .map(|inlay| inlay.id)
 3495                            .collect(),
 3496                        Vec::new(),
 3497                        cx,
 3498                    );
 3499                    return;
 3500                }
 3501            }
 3502            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3503                match self.inlay_hint_cache.update_settings(
 3504                    &self.buffer,
 3505                    new_settings,
 3506                    self.visible_inlay_hints(cx),
 3507                    cx,
 3508                ) {
 3509                    ControlFlow::Break(Some(InlaySplice {
 3510                        to_remove,
 3511                        to_insert,
 3512                    })) => {
 3513                        self.splice_inlays(to_remove, to_insert, cx);
 3514                        return;
 3515                    }
 3516                    ControlFlow::Break(None) => return,
 3517                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3518                }
 3519            }
 3520            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3521                if let Some(InlaySplice {
 3522                    to_remove,
 3523                    to_insert,
 3524                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3525                {
 3526                    self.splice_inlays(to_remove, to_insert, cx);
 3527                }
 3528                return;
 3529            }
 3530            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3531            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3532                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3533            }
 3534            InlayHintRefreshReason::RefreshRequested => {
 3535                (InvalidationStrategy::RefreshRequested, None)
 3536            }
 3537        };
 3538
 3539        if let Some(InlaySplice {
 3540            to_remove,
 3541            to_insert,
 3542        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3543            reason_description,
 3544            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3545            invalidate_cache,
 3546            ignore_debounce,
 3547            cx,
 3548        ) {
 3549            self.splice_inlays(to_remove, to_insert, cx);
 3550        }
 3551    }
 3552
 3553    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3554        self.display_map
 3555            .read(cx)
 3556            .current_inlays()
 3557            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3558            .cloned()
 3559            .collect()
 3560    }
 3561
 3562    pub fn excerpts_for_inlay_hints_query(
 3563        &self,
 3564        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3565        cx: &mut ViewContext<Editor>,
 3566    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3567        let Some(project) = self.project.as_ref() else {
 3568            return HashMap::default();
 3569        };
 3570        let project = project.read(cx);
 3571        let multi_buffer = self.buffer().read(cx);
 3572        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3573        let multi_buffer_visible_start = self
 3574            .scroll_manager
 3575            .anchor()
 3576            .anchor
 3577            .to_point(&multi_buffer_snapshot);
 3578        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3579            multi_buffer_visible_start
 3580                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3581            Bias::Left,
 3582        );
 3583        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3584        multi_buffer_snapshot
 3585            .range_to_buffer_ranges(multi_buffer_visible_range)
 3586            .into_iter()
 3587            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3588            .filter_map(|(excerpt, excerpt_visible_range)| {
 3589                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3590                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3591                let worktree_entry = buffer_worktree
 3592                    .read(cx)
 3593                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3594                if worktree_entry.is_ignored {
 3595                    return None;
 3596                }
 3597
 3598                let language = excerpt.buffer().language()?;
 3599                if let Some(restrict_to_languages) = restrict_to_languages {
 3600                    if !restrict_to_languages.contains(language) {
 3601                        return None;
 3602                    }
 3603                }
 3604                Some((
 3605                    excerpt.id(),
 3606                    (
 3607                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3608                        excerpt.buffer().version().clone(),
 3609                        excerpt_visible_range,
 3610                    ),
 3611                ))
 3612            })
 3613            .collect()
 3614    }
 3615
 3616    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3617        TextLayoutDetails {
 3618            text_system: cx.text_system().clone(),
 3619            editor_style: self.style.clone().unwrap(),
 3620            rem_size: cx.rem_size(),
 3621            scroll_anchor: self.scroll_manager.anchor(),
 3622            visible_rows: self.visible_line_count(),
 3623            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3624        }
 3625    }
 3626
 3627    pub fn splice_inlays(
 3628        &self,
 3629        to_remove: Vec<InlayId>,
 3630        to_insert: Vec<Inlay>,
 3631        cx: &mut ViewContext<Self>,
 3632    ) {
 3633        self.display_map.update(cx, |display_map, cx| {
 3634            display_map.splice_inlays(to_remove, to_insert, cx)
 3635        });
 3636        cx.notify();
 3637    }
 3638
 3639    fn trigger_on_type_formatting(
 3640        &self,
 3641        input: String,
 3642        cx: &mut ViewContext<Self>,
 3643    ) -> Option<Task<Result<()>>> {
 3644        if input.len() != 1 {
 3645            return None;
 3646        }
 3647
 3648        let project = self.project.as_ref()?;
 3649        let position = self.selections.newest_anchor().head();
 3650        let (buffer, buffer_position) = self
 3651            .buffer
 3652            .read(cx)
 3653            .text_anchor_for_position(position, cx)?;
 3654
 3655        let settings = language_settings::language_settings(
 3656            buffer
 3657                .read(cx)
 3658                .language_at(buffer_position)
 3659                .map(|l| l.name()),
 3660            buffer.read(cx).file(),
 3661            cx,
 3662        );
 3663        if !settings.use_on_type_format {
 3664            return None;
 3665        }
 3666
 3667        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3668        // hence we do LSP request & edit on host side only — add formats to host's history.
 3669        let push_to_lsp_host_history = true;
 3670        // If this is not the host, append its history with new edits.
 3671        let push_to_client_history = project.read(cx).is_via_collab();
 3672
 3673        let on_type_formatting = project.update(cx, |project, cx| {
 3674            project.on_type_format(
 3675                buffer.clone(),
 3676                buffer_position,
 3677                input,
 3678                push_to_lsp_host_history,
 3679                cx,
 3680            )
 3681        });
 3682        Some(cx.spawn(|editor, mut cx| async move {
 3683            if let Some(transaction) = on_type_formatting.await? {
 3684                if push_to_client_history {
 3685                    buffer
 3686                        .update(&mut cx, |buffer, _| {
 3687                            buffer.push_transaction(transaction, Instant::now());
 3688                        })
 3689                        .ok();
 3690                }
 3691                editor.update(&mut cx, |editor, cx| {
 3692                    editor.refresh_document_highlights(cx);
 3693                })?;
 3694            }
 3695            Ok(())
 3696        }))
 3697    }
 3698
 3699    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3700        if self.pending_rename.is_some() {
 3701            return;
 3702        }
 3703
 3704        let Some(provider) = self.completion_provider.as_ref() else {
 3705            return;
 3706        };
 3707
 3708        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3709            return;
 3710        }
 3711
 3712        let position = self.selections.newest_anchor().head();
 3713        let (buffer, buffer_position) =
 3714            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3715                output
 3716            } else {
 3717                return;
 3718            };
 3719        let show_completion_documentation = buffer
 3720            .read(cx)
 3721            .snapshot()
 3722            .settings_at(buffer_position, cx)
 3723            .show_completion_documentation;
 3724
 3725        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3726
 3727        let trigger_kind = match &options.trigger {
 3728            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3729                CompletionTriggerKind::TRIGGER_CHARACTER
 3730            }
 3731            _ => CompletionTriggerKind::INVOKED,
 3732        };
 3733        let completion_context = CompletionContext {
 3734            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3735                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3736                    Some(String::from(trigger))
 3737                } else {
 3738                    None
 3739                }
 3740            }),
 3741            trigger_kind,
 3742        };
 3743        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3744        let sort_completions = provider.sort_completions();
 3745
 3746        let id = post_inc(&mut self.next_completion_id);
 3747        let task = cx.spawn(|editor, mut cx| {
 3748            async move {
 3749                editor.update(&mut cx, |this, _| {
 3750                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3751                })?;
 3752                let completions = completions.await.log_err();
 3753                let menu = if let Some(completions) = completions {
 3754                    let mut menu = CompletionsMenu::new(
 3755                        id,
 3756                        sort_completions,
 3757                        show_completion_documentation,
 3758                        position,
 3759                        buffer.clone(),
 3760                        completions.into(),
 3761                    );
 3762
 3763                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3764                        .await;
 3765
 3766                    menu.visible().then_some(menu)
 3767                } else {
 3768                    None
 3769                };
 3770
 3771                editor.update(&mut cx, |editor, cx| {
 3772                    match editor.context_menu.borrow().as_ref() {
 3773                        None => {}
 3774                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3775                            if prev_menu.id > id {
 3776                                return;
 3777                            }
 3778                        }
 3779                        _ => return,
 3780                    }
 3781
 3782                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3783                        let mut menu = menu.unwrap();
 3784                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3785
 3786                        if editor.show_inline_completions_in_menu(cx) {
 3787                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3788                                menu.show_inline_completion_hint(hint);
 3789                            }
 3790                        } else {
 3791                            editor.discard_inline_completion(false, cx);
 3792                        }
 3793
 3794                        *editor.context_menu.borrow_mut() =
 3795                            Some(CodeContextMenu::Completions(menu));
 3796
 3797                        cx.notify();
 3798                    } else if editor.completion_tasks.len() <= 1 {
 3799                        // If there are no more completion tasks and the last menu was
 3800                        // empty, we should hide it.
 3801                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3802                        // If it was already hidden and we don't show inline
 3803                        // completions in the menu, we should also show the
 3804                        // inline-completion when available.
 3805                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3806                            editor.update_visible_inline_completion(cx);
 3807                        }
 3808                    }
 3809                })?;
 3810
 3811                Ok::<_, anyhow::Error>(())
 3812            }
 3813            .log_err()
 3814        });
 3815
 3816        self.completion_tasks.push((id, task));
 3817    }
 3818
 3819    pub fn confirm_completion(
 3820        &mut self,
 3821        action: &ConfirmCompletion,
 3822        cx: &mut ViewContext<Self>,
 3823    ) -> Option<Task<Result<()>>> {
 3824        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3825    }
 3826
 3827    pub fn compose_completion(
 3828        &mut self,
 3829        action: &ComposeCompletion,
 3830        cx: &mut ViewContext<Self>,
 3831    ) -> Option<Task<Result<()>>> {
 3832        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3833    }
 3834
 3835    fn do_completion(
 3836        &mut self,
 3837        item_ix: Option<usize>,
 3838        intent: CompletionIntent,
 3839        cx: &mut ViewContext<Editor>,
 3840    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3841        use language::ToOffset as _;
 3842
 3843        {
 3844            let context_menu = self.context_menu.borrow();
 3845            if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
 3846                let entries = menu.entries.borrow();
 3847                let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
 3848                match entry {
 3849                    Some(CompletionEntry::InlineCompletionHint(
 3850                        InlineCompletionMenuHint::Loading,
 3851                    )) => return Some(Task::ready(Ok(()))),
 3852                    Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
 3853                        drop(entries);
 3854                        drop(context_menu);
 3855                        self.context_menu_next(&Default::default(), cx);
 3856                        return Some(Task::ready(Ok(())));
 3857                    }
 3858                    _ => {}
 3859                }
 3860            }
 3861        }
 3862
 3863        let completions_menu =
 3864            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3865                menu
 3866            } else {
 3867                return None;
 3868            };
 3869
 3870        let entries = completions_menu.entries.borrow();
 3871        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3872        let mat = match mat {
 3873            CompletionEntry::InlineCompletionHint(_) => {
 3874                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3875                cx.stop_propagation();
 3876                return Some(Task::ready(Ok(())));
 3877            }
 3878            CompletionEntry::Match(mat) => {
 3879                if self.show_inline_completions_in_menu(cx) {
 3880                    self.discard_inline_completion(true, cx);
 3881                }
 3882                mat
 3883            }
 3884        };
 3885        let candidate_id = mat.candidate_id;
 3886        drop(entries);
 3887
 3888        let buffer_handle = completions_menu.buffer;
 3889        let completion = completions_menu
 3890            .completions
 3891            .borrow()
 3892            .get(candidate_id)?
 3893            .clone();
 3894        cx.stop_propagation();
 3895
 3896        let snippet;
 3897        let text;
 3898
 3899        if completion.is_snippet() {
 3900            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3901            text = snippet.as_ref().unwrap().text.clone();
 3902        } else {
 3903            snippet = None;
 3904            text = completion.new_text.clone();
 3905        };
 3906        let selections = self.selections.all::<usize>(cx);
 3907        let buffer = buffer_handle.read(cx);
 3908        let old_range = completion.old_range.to_offset(buffer);
 3909        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3910
 3911        let newest_selection = self.selections.newest_anchor();
 3912        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3913            return None;
 3914        }
 3915
 3916        let lookbehind = newest_selection
 3917            .start
 3918            .text_anchor
 3919            .to_offset(buffer)
 3920            .saturating_sub(old_range.start);
 3921        let lookahead = old_range
 3922            .end
 3923            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3924        let mut common_prefix_len = old_text
 3925            .bytes()
 3926            .zip(text.bytes())
 3927            .take_while(|(a, b)| a == b)
 3928            .count();
 3929
 3930        let snapshot = self.buffer.read(cx).snapshot(cx);
 3931        let mut range_to_replace: Option<Range<isize>> = None;
 3932        let mut ranges = Vec::new();
 3933        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3934        for selection in &selections {
 3935            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3936                let start = selection.start.saturating_sub(lookbehind);
 3937                let end = selection.end + lookahead;
 3938                if selection.id == newest_selection.id {
 3939                    range_to_replace = Some(
 3940                        ((start + common_prefix_len) as isize - selection.start as isize)
 3941                            ..(end as isize - selection.start as isize),
 3942                    );
 3943                }
 3944                ranges.push(start + common_prefix_len..end);
 3945            } else {
 3946                common_prefix_len = 0;
 3947                ranges.clear();
 3948                ranges.extend(selections.iter().map(|s| {
 3949                    if s.id == newest_selection.id {
 3950                        range_to_replace = Some(
 3951                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3952                                - selection.start as isize
 3953                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3954                                    - selection.start as isize,
 3955                        );
 3956                        old_range.clone()
 3957                    } else {
 3958                        s.start..s.end
 3959                    }
 3960                }));
 3961                break;
 3962            }
 3963            if !self.linked_edit_ranges.is_empty() {
 3964                let start_anchor = snapshot.anchor_before(selection.head());
 3965                let end_anchor = snapshot.anchor_after(selection.tail());
 3966                if let Some(ranges) = self
 3967                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3968                {
 3969                    for (buffer, edits) in ranges {
 3970                        linked_edits.entry(buffer.clone()).or_default().extend(
 3971                            edits
 3972                                .into_iter()
 3973                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3974                        );
 3975                    }
 3976                }
 3977            }
 3978        }
 3979        let text = &text[common_prefix_len..];
 3980
 3981        cx.emit(EditorEvent::InputHandled {
 3982            utf16_range_to_replace: range_to_replace,
 3983            text: text.into(),
 3984        });
 3985
 3986        self.transact(cx, |this, cx| {
 3987            if let Some(mut snippet) = snippet {
 3988                snippet.text = text.to_string();
 3989                for tabstop in snippet
 3990                    .tabstops
 3991                    .iter_mut()
 3992                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3993                {
 3994                    tabstop.start -= common_prefix_len as isize;
 3995                    tabstop.end -= common_prefix_len as isize;
 3996                }
 3997
 3998                this.insert_snippet(&ranges, snippet, cx).log_err();
 3999            } else {
 4000                this.buffer.update(cx, |buffer, cx| {
 4001                    buffer.edit(
 4002                        ranges.iter().map(|range| (range.clone(), text)),
 4003                        this.autoindent_mode.clone(),
 4004                        cx,
 4005                    );
 4006                });
 4007            }
 4008            for (buffer, edits) in linked_edits {
 4009                buffer.update(cx, |buffer, cx| {
 4010                    let snapshot = buffer.snapshot();
 4011                    let edits = edits
 4012                        .into_iter()
 4013                        .map(|(range, text)| {
 4014                            use text::ToPoint as TP;
 4015                            let end_point = TP::to_point(&range.end, &snapshot);
 4016                            let start_point = TP::to_point(&range.start, &snapshot);
 4017                            (start_point..end_point, text)
 4018                        })
 4019                        .sorted_by_key(|(range, _)| range.start)
 4020                        .collect::<Vec<_>>();
 4021                    buffer.edit(edits, None, cx);
 4022                })
 4023            }
 4024
 4025            this.refresh_inline_completion(true, false, cx);
 4026        });
 4027
 4028        let show_new_completions_on_confirm = completion
 4029            .confirm
 4030            .as_ref()
 4031            .map_or(false, |confirm| confirm(intent, cx));
 4032        if show_new_completions_on_confirm {
 4033            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4034        }
 4035
 4036        let provider = self.completion_provider.as_ref()?;
 4037        drop(completion);
 4038        let apply_edits = provider.apply_additional_edits_for_completion(
 4039            buffer_handle,
 4040            completions_menu.completions.clone(),
 4041            candidate_id,
 4042            true,
 4043            cx,
 4044        );
 4045
 4046        let editor_settings = EditorSettings::get_global(cx);
 4047        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4048            // After the code completion is finished, users often want to know what signatures are needed.
 4049            // so we should automatically call signature_help
 4050            self.show_signature_help(&ShowSignatureHelp, cx);
 4051        }
 4052
 4053        Some(cx.foreground_executor().spawn(async move {
 4054            apply_edits.await?;
 4055            Ok(())
 4056        }))
 4057    }
 4058
 4059    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4060        let mut context_menu = self.context_menu.borrow_mut();
 4061        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4062            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4063                // Toggle if we're selecting the same one
 4064                *context_menu = None;
 4065                cx.notify();
 4066                return;
 4067            } else {
 4068                // Otherwise, clear it and start a new one
 4069                *context_menu = None;
 4070                cx.notify();
 4071            }
 4072        }
 4073        drop(context_menu);
 4074        let snapshot = self.snapshot(cx);
 4075        let deployed_from_indicator = action.deployed_from_indicator;
 4076        let mut task = self.code_actions_task.take();
 4077        let action = action.clone();
 4078        cx.spawn(|editor, mut cx| async move {
 4079            while let Some(prev_task) = task {
 4080                prev_task.await.log_err();
 4081                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4082            }
 4083
 4084            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4085                if editor.focus_handle.is_focused(cx) {
 4086                    let multibuffer_point = action
 4087                        .deployed_from_indicator
 4088                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4089                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4090                    let (buffer, buffer_row) = snapshot
 4091                        .buffer_snapshot
 4092                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4093                        .and_then(|(buffer_snapshot, range)| {
 4094                            editor
 4095                                .buffer
 4096                                .read(cx)
 4097                                .buffer(buffer_snapshot.remote_id())
 4098                                .map(|buffer| (buffer, range.start.row))
 4099                        })?;
 4100                    let (_, code_actions) = editor
 4101                        .available_code_actions
 4102                        .clone()
 4103                        .and_then(|(location, code_actions)| {
 4104                            let snapshot = location.buffer.read(cx).snapshot();
 4105                            let point_range = location.range.to_point(&snapshot);
 4106                            let point_range = point_range.start.row..=point_range.end.row;
 4107                            if point_range.contains(&buffer_row) {
 4108                                Some((location, code_actions))
 4109                            } else {
 4110                                None
 4111                            }
 4112                        })
 4113                        .unzip();
 4114                    let buffer_id = buffer.read(cx).remote_id();
 4115                    let tasks = editor
 4116                        .tasks
 4117                        .get(&(buffer_id, buffer_row))
 4118                        .map(|t| Arc::new(t.to_owned()));
 4119                    if tasks.is_none() && code_actions.is_none() {
 4120                        return None;
 4121                    }
 4122
 4123                    editor.completion_tasks.clear();
 4124                    editor.discard_inline_completion(false, cx);
 4125                    let task_context =
 4126                        tasks
 4127                            .as_ref()
 4128                            .zip(editor.project.clone())
 4129                            .map(|(tasks, project)| {
 4130                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4131                            });
 4132
 4133                    Some(cx.spawn(|editor, mut cx| async move {
 4134                        let task_context = match task_context {
 4135                            Some(task_context) => task_context.await,
 4136                            None => None,
 4137                        };
 4138                        let resolved_tasks =
 4139                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4140                                Rc::new(ResolvedTasks {
 4141                                    templates: tasks.resolve(&task_context).collect(),
 4142                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4143                                        multibuffer_point.row,
 4144                                        tasks.column,
 4145                                    )),
 4146                                })
 4147                            });
 4148                        let spawn_straight_away = resolved_tasks
 4149                            .as_ref()
 4150                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4151                            && code_actions
 4152                                .as_ref()
 4153                                .map_or(true, |actions| actions.is_empty());
 4154                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4155                            *editor.context_menu.borrow_mut() =
 4156                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4157                                    buffer,
 4158                                    actions: CodeActionContents {
 4159                                        tasks: resolved_tasks,
 4160                                        actions: code_actions,
 4161                                    },
 4162                                    selected_item: Default::default(),
 4163                                    scroll_handle: UniformListScrollHandle::default(),
 4164                                    deployed_from_indicator,
 4165                                }));
 4166                            if spawn_straight_away {
 4167                                if let Some(task) = editor.confirm_code_action(
 4168                                    &ConfirmCodeAction { item_ix: Some(0) },
 4169                                    cx,
 4170                                ) {
 4171                                    cx.notify();
 4172                                    return task;
 4173                                }
 4174                            }
 4175                            cx.notify();
 4176                            Task::ready(Ok(()))
 4177                        }) {
 4178                            task.await
 4179                        } else {
 4180                            Ok(())
 4181                        }
 4182                    }))
 4183                } else {
 4184                    Some(Task::ready(Ok(())))
 4185                }
 4186            })?;
 4187            if let Some(task) = spawned_test_task {
 4188                task.await?;
 4189            }
 4190
 4191            Ok::<_, anyhow::Error>(())
 4192        })
 4193        .detach_and_log_err(cx);
 4194    }
 4195
 4196    pub fn confirm_code_action(
 4197        &mut self,
 4198        action: &ConfirmCodeAction,
 4199        cx: &mut ViewContext<Self>,
 4200    ) -> Option<Task<Result<()>>> {
 4201        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4202            menu
 4203        } else {
 4204            return None;
 4205        };
 4206        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4207        let action = actions_menu.actions.get(action_ix)?;
 4208        let title = action.label();
 4209        let buffer = actions_menu.buffer;
 4210        let workspace = self.workspace()?;
 4211
 4212        match action {
 4213            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4214                workspace.update(cx, |workspace, cx| {
 4215                    workspace::tasks::schedule_resolved_task(
 4216                        workspace,
 4217                        task_source_kind,
 4218                        resolved_task,
 4219                        false,
 4220                        cx,
 4221                    );
 4222
 4223                    Some(Task::ready(Ok(())))
 4224                })
 4225            }
 4226            CodeActionsItem::CodeAction {
 4227                excerpt_id,
 4228                action,
 4229                provider,
 4230            } => {
 4231                let apply_code_action =
 4232                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4233                let workspace = workspace.downgrade();
 4234                Some(cx.spawn(|editor, cx| async move {
 4235                    let project_transaction = apply_code_action.await?;
 4236                    Self::open_project_transaction(
 4237                        &editor,
 4238                        workspace,
 4239                        project_transaction,
 4240                        title,
 4241                        cx,
 4242                    )
 4243                    .await
 4244                }))
 4245            }
 4246        }
 4247    }
 4248
 4249    pub async fn open_project_transaction(
 4250        this: &WeakView<Editor>,
 4251        workspace: WeakView<Workspace>,
 4252        transaction: ProjectTransaction,
 4253        title: String,
 4254        mut cx: AsyncWindowContext,
 4255    ) -> Result<()> {
 4256        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4257        cx.update(|cx| {
 4258            entries.sort_unstable_by_key(|(buffer, _)| {
 4259                buffer.read(cx).file().map(|f| f.path().clone())
 4260            });
 4261        })?;
 4262
 4263        // If the project transaction's edits are all contained within this editor, then
 4264        // avoid opening a new editor to display them.
 4265
 4266        if let Some((buffer, transaction)) = entries.first() {
 4267            if entries.len() == 1 {
 4268                let excerpt = this.update(&mut cx, |editor, cx| {
 4269                    editor
 4270                        .buffer()
 4271                        .read(cx)
 4272                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4273                })?;
 4274                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4275                    if excerpted_buffer == *buffer {
 4276                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4277                            let excerpt_range = excerpt_range.to_offset(buffer);
 4278                            buffer
 4279                                .edited_ranges_for_transaction::<usize>(transaction)
 4280                                .all(|range| {
 4281                                    excerpt_range.start <= range.start
 4282                                        && excerpt_range.end >= range.end
 4283                                })
 4284                        })?;
 4285
 4286                        if all_edits_within_excerpt {
 4287                            return Ok(());
 4288                        }
 4289                    }
 4290                }
 4291            }
 4292        } else {
 4293            return Ok(());
 4294        }
 4295
 4296        let mut ranges_to_highlight = Vec::new();
 4297        let excerpt_buffer = cx.new_model(|cx| {
 4298            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4299            for (buffer_handle, transaction) in &entries {
 4300                let buffer = buffer_handle.read(cx);
 4301                ranges_to_highlight.extend(
 4302                    multibuffer.push_excerpts_with_context_lines(
 4303                        buffer_handle.clone(),
 4304                        buffer
 4305                            .edited_ranges_for_transaction::<usize>(transaction)
 4306                            .collect(),
 4307                        DEFAULT_MULTIBUFFER_CONTEXT,
 4308                        cx,
 4309                    ),
 4310                );
 4311            }
 4312            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4313            multibuffer
 4314        })?;
 4315
 4316        workspace.update(&mut cx, |workspace, cx| {
 4317            let project = workspace.project().clone();
 4318            let editor =
 4319                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4320            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4321            editor.update(cx, |editor, cx| {
 4322                editor.highlight_background::<Self>(
 4323                    &ranges_to_highlight,
 4324                    |theme| theme.editor_highlighted_line_background,
 4325                    cx,
 4326                );
 4327            });
 4328        })?;
 4329
 4330        Ok(())
 4331    }
 4332
 4333    pub fn clear_code_action_providers(&mut self) {
 4334        self.code_action_providers.clear();
 4335        self.available_code_actions.take();
 4336    }
 4337
 4338    pub fn add_code_action_provider(
 4339        &mut self,
 4340        provider: Rc<dyn CodeActionProvider>,
 4341        cx: &mut ViewContext<Self>,
 4342    ) {
 4343        if self
 4344            .code_action_providers
 4345            .iter()
 4346            .any(|existing_provider| existing_provider.id() == provider.id())
 4347        {
 4348            return;
 4349        }
 4350
 4351        self.code_action_providers.push(provider);
 4352        self.refresh_code_actions(cx);
 4353    }
 4354
 4355    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4356        self.code_action_providers
 4357            .retain(|provider| provider.id() != id);
 4358        self.refresh_code_actions(cx);
 4359    }
 4360
 4361    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4362        let buffer = self.buffer.read(cx);
 4363        let newest_selection = self.selections.newest_anchor().clone();
 4364        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4365        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4366        if start_buffer != end_buffer {
 4367            return None;
 4368        }
 4369
 4370        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4371            cx.background_executor()
 4372                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4373                .await;
 4374
 4375            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4376                let providers = this.code_action_providers.clone();
 4377                let tasks = this
 4378                    .code_action_providers
 4379                    .iter()
 4380                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4381                    .collect::<Vec<_>>();
 4382                (providers, tasks)
 4383            })?;
 4384
 4385            let mut actions = Vec::new();
 4386            for (provider, provider_actions) in
 4387                providers.into_iter().zip(future::join_all(tasks).await)
 4388            {
 4389                if let Some(provider_actions) = provider_actions.log_err() {
 4390                    actions.extend(provider_actions.into_iter().map(|action| {
 4391                        AvailableCodeAction {
 4392                            excerpt_id: newest_selection.start.excerpt_id,
 4393                            action,
 4394                            provider: provider.clone(),
 4395                        }
 4396                    }));
 4397                }
 4398            }
 4399
 4400            this.update(&mut cx, |this, cx| {
 4401                this.available_code_actions = if actions.is_empty() {
 4402                    None
 4403                } else {
 4404                    Some((
 4405                        Location {
 4406                            buffer: start_buffer,
 4407                            range: start..end,
 4408                        },
 4409                        actions.into(),
 4410                    ))
 4411                };
 4412                cx.notify();
 4413            })
 4414        }));
 4415        None
 4416    }
 4417
 4418    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4419        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4420            self.show_git_blame_inline = false;
 4421
 4422            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4423                cx.background_executor().timer(delay).await;
 4424
 4425                this.update(&mut cx, |this, cx| {
 4426                    this.show_git_blame_inline = true;
 4427                    cx.notify();
 4428                })
 4429                .log_err();
 4430            }));
 4431        }
 4432    }
 4433
 4434    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4435        if self.pending_rename.is_some() {
 4436            return None;
 4437        }
 4438
 4439        let provider = self.semantics_provider.clone()?;
 4440        let buffer = self.buffer.read(cx);
 4441        let newest_selection = self.selections.newest_anchor().clone();
 4442        let cursor_position = newest_selection.head();
 4443        let (cursor_buffer, cursor_buffer_position) =
 4444            buffer.text_anchor_for_position(cursor_position, cx)?;
 4445        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4446        if cursor_buffer != tail_buffer {
 4447            return None;
 4448        }
 4449        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4450        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4451            cx.background_executor()
 4452                .timer(Duration::from_millis(debounce))
 4453                .await;
 4454
 4455            let highlights = if let Some(highlights) = cx
 4456                .update(|cx| {
 4457                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4458                })
 4459                .ok()
 4460                .flatten()
 4461            {
 4462                highlights.await.log_err()
 4463            } else {
 4464                None
 4465            };
 4466
 4467            if let Some(highlights) = highlights {
 4468                this.update(&mut cx, |this, cx| {
 4469                    if this.pending_rename.is_some() {
 4470                        return;
 4471                    }
 4472
 4473                    let buffer_id = cursor_position.buffer_id;
 4474                    let buffer = this.buffer.read(cx);
 4475                    if !buffer
 4476                        .text_anchor_for_position(cursor_position, cx)
 4477                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4478                    {
 4479                        return;
 4480                    }
 4481
 4482                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4483                    let mut write_ranges = Vec::new();
 4484                    let mut read_ranges = Vec::new();
 4485                    for highlight in highlights {
 4486                        for (excerpt_id, excerpt_range) in
 4487                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4488                        {
 4489                            let start = highlight
 4490                                .range
 4491                                .start
 4492                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4493                            let end = highlight
 4494                                .range
 4495                                .end
 4496                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4497                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4498                                continue;
 4499                            }
 4500
 4501                            let range = Anchor {
 4502                                buffer_id,
 4503                                excerpt_id,
 4504                                text_anchor: start,
 4505                            }..Anchor {
 4506                                buffer_id,
 4507                                excerpt_id,
 4508                                text_anchor: end,
 4509                            };
 4510                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4511                                write_ranges.push(range);
 4512                            } else {
 4513                                read_ranges.push(range);
 4514                            }
 4515                        }
 4516                    }
 4517
 4518                    this.highlight_background::<DocumentHighlightRead>(
 4519                        &read_ranges,
 4520                        |theme| theme.editor_document_highlight_read_background,
 4521                        cx,
 4522                    );
 4523                    this.highlight_background::<DocumentHighlightWrite>(
 4524                        &write_ranges,
 4525                        |theme| theme.editor_document_highlight_write_background,
 4526                        cx,
 4527                    );
 4528                    cx.notify();
 4529                })
 4530                .log_err();
 4531            }
 4532        }));
 4533        None
 4534    }
 4535
 4536    pub fn refresh_inline_completion(
 4537        &mut self,
 4538        debounce: bool,
 4539        user_requested: bool,
 4540        cx: &mut ViewContext<Self>,
 4541    ) -> Option<()> {
 4542        let provider = self.inline_completion_provider()?;
 4543        let cursor = self.selections.newest_anchor().head();
 4544        let (buffer, cursor_buffer_position) =
 4545            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4546
 4547        if !user_requested
 4548            && (!self.enable_inline_completions
 4549                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4550                || !self.is_focused(cx)
 4551                || buffer.read(cx).is_empty())
 4552        {
 4553            self.discard_inline_completion(false, cx);
 4554            return None;
 4555        }
 4556
 4557        self.update_visible_inline_completion(cx);
 4558        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4559        Some(())
 4560    }
 4561
 4562    fn cycle_inline_completion(
 4563        &mut self,
 4564        direction: Direction,
 4565        cx: &mut ViewContext<Self>,
 4566    ) -> Option<()> {
 4567        let provider = self.inline_completion_provider()?;
 4568        let cursor = self.selections.newest_anchor().head();
 4569        let (buffer, cursor_buffer_position) =
 4570            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4571        if !self.enable_inline_completions
 4572            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4573        {
 4574            return None;
 4575        }
 4576
 4577        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4578        self.update_visible_inline_completion(cx);
 4579
 4580        Some(())
 4581    }
 4582
 4583    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4584        if !self.has_active_inline_completion() {
 4585            self.refresh_inline_completion(false, true, cx);
 4586            return;
 4587        }
 4588
 4589        self.update_visible_inline_completion(cx);
 4590    }
 4591
 4592    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4593        self.show_cursor_names(cx);
 4594    }
 4595
 4596    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4597        self.show_cursor_names = true;
 4598        cx.notify();
 4599        cx.spawn(|this, mut cx| async move {
 4600            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4601            this.update(&mut cx, |this, cx| {
 4602                this.show_cursor_names = false;
 4603                cx.notify()
 4604            })
 4605            .ok()
 4606        })
 4607        .detach();
 4608    }
 4609
 4610    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4611        if self.has_active_inline_completion() {
 4612            self.cycle_inline_completion(Direction::Next, cx);
 4613        } else {
 4614            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4615            if is_copilot_disabled {
 4616                cx.propagate();
 4617            }
 4618        }
 4619    }
 4620
 4621    pub fn previous_inline_completion(
 4622        &mut self,
 4623        _: &PreviousInlineCompletion,
 4624        cx: &mut ViewContext<Self>,
 4625    ) {
 4626        if self.has_active_inline_completion() {
 4627            self.cycle_inline_completion(Direction::Prev, cx);
 4628        } else {
 4629            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4630            if is_copilot_disabled {
 4631                cx.propagate();
 4632            }
 4633        }
 4634    }
 4635
 4636    pub fn accept_inline_completion(
 4637        &mut self,
 4638        _: &AcceptInlineCompletion,
 4639        cx: &mut ViewContext<Self>,
 4640    ) {
 4641        let buffer = self.buffer.read(cx);
 4642        let snapshot = buffer.snapshot(cx);
 4643        let selection = self.selections.newest_adjusted(cx);
 4644        let cursor = selection.head();
 4645        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4646        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4647        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4648        {
 4649            if cursor.column < suggested_indent.len
 4650                && cursor.column <= current_indent.len
 4651                && current_indent.len <= suggested_indent.len
 4652            {
 4653                self.tab(&Default::default(), cx);
 4654                return;
 4655            }
 4656        }
 4657
 4658        if self.show_inline_completions_in_menu(cx) {
 4659            self.hide_context_menu(cx);
 4660        }
 4661
 4662        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4663            return;
 4664        };
 4665
 4666        self.report_inline_completion_event(true, cx);
 4667
 4668        match &active_inline_completion.completion {
 4669            InlineCompletion::Move(position) => {
 4670                let position = *position;
 4671                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4672                    selections.select_anchor_ranges([position..position]);
 4673                });
 4674            }
 4675            InlineCompletion::Edit(edits) => {
 4676                if let Some(provider) = self.inline_completion_provider() {
 4677                    provider.accept(cx);
 4678                }
 4679
 4680                let snapshot = self.buffer.read(cx).snapshot(cx);
 4681                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4682
 4683                self.buffer.update(cx, |buffer, cx| {
 4684                    buffer.edit(edits.iter().cloned(), None, cx)
 4685                });
 4686
 4687                self.change_selections(None, cx, |s| {
 4688                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4689                });
 4690
 4691                self.update_visible_inline_completion(cx);
 4692                if self.active_inline_completion.is_none() {
 4693                    self.refresh_inline_completion(true, true, cx);
 4694                }
 4695
 4696                cx.notify();
 4697            }
 4698        }
 4699    }
 4700
 4701    pub fn accept_partial_inline_completion(
 4702        &mut self,
 4703        _: &AcceptPartialInlineCompletion,
 4704        cx: &mut ViewContext<Self>,
 4705    ) {
 4706        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4707            return;
 4708        };
 4709        if self.selections.count() != 1 {
 4710            return;
 4711        }
 4712
 4713        self.report_inline_completion_event(true, cx);
 4714
 4715        match &active_inline_completion.completion {
 4716            InlineCompletion::Move(position) => {
 4717                let position = *position;
 4718                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4719                    selections.select_anchor_ranges([position..position]);
 4720                });
 4721            }
 4722            InlineCompletion::Edit(edits) => {
 4723                // Find an insertion that starts at the cursor position.
 4724                let snapshot = self.buffer.read(cx).snapshot(cx);
 4725                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4726                let insertion = edits.iter().find_map(|(range, text)| {
 4727                    let range = range.to_offset(&snapshot);
 4728                    if range.is_empty() && range.start == cursor_offset {
 4729                        Some(text)
 4730                    } else {
 4731                        None
 4732                    }
 4733                });
 4734
 4735                if let Some(text) = insertion {
 4736                    let mut partial_completion = text
 4737                        .chars()
 4738                        .by_ref()
 4739                        .take_while(|c| c.is_alphabetic())
 4740                        .collect::<String>();
 4741                    if partial_completion.is_empty() {
 4742                        partial_completion = text
 4743                            .chars()
 4744                            .by_ref()
 4745                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4746                            .collect::<String>();
 4747                    }
 4748
 4749                    cx.emit(EditorEvent::InputHandled {
 4750                        utf16_range_to_replace: None,
 4751                        text: partial_completion.clone().into(),
 4752                    });
 4753
 4754                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4755
 4756                    self.refresh_inline_completion(true, true, cx);
 4757                    cx.notify();
 4758                } else {
 4759                    self.accept_inline_completion(&Default::default(), cx);
 4760                }
 4761            }
 4762        }
 4763    }
 4764
 4765    fn discard_inline_completion(
 4766        &mut self,
 4767        should_report_inline_completion_event: bool,
 4768        cx: &mut ViewContext<Self>,
 4769    ) -> bool {
 4770        if should_report_inline_completion_event {
 4771            self.report_inline_completion_event(false, cx);
 4772        }
 4773
 4774        if let Some(provider) = self.inline_completion_provider() {
 4775            provider.discard(cx);
 4776        }
 4777
 4778        self.take_active_inline_completion(cx).is_some()
 4779    }
 4780
 4781    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4782        let Some(provider) = self.inline_completion_provider() else {
 4783            return;
 4784        };
 4785
 4786        let Some((_, buffer, _)) = self
 4787            .buffer
 4788            .read(cx)
 4789            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4790        else {
 4791            return;
 4792        };
 4793
 4794        let extension = buffer
 4795            .read(cx)
 4796            .file()
 4797            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4798
 4799        let event_type = match accepted {
 4800            true => "Inline Completion Accepted",
 4801            false => "Inline Completion Discarded",
 4802        };
 4803        telemetry::event!(
 4804            event_type,
 4805            provider = provider.name(),
 4806            suggestion_accepted = accepted,
 4807            file_extension = extension,
 4808        );
 4809    }
 4810
 4811    pub fn has_active_inline_completion(&self) -> bool {
 4812        self.active_inline_completion.is_some()
 4813    }
 4814
 4815    fn take_active_inline_completion(
 4816        &mut self,
 4817        cx: &mut ViewContext<Self>,
 4818    ) -> Option<InlineCompletion> {
 4819        let active_inline_completion = self.active_inline_completion.take()?;
 4820        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4821        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4822        Some(active_inline_completion.completion)
 4823    }
 4824
 4825    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4826        let selection = self.selections.newest_anchor();
 4827        let cursor = selection.head();
 4828        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4829        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4830        let excerpt_id = cursor.excerpt_id;
 4831
 4832        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4833            && (self.context_menu.borrow().is_some()
 4834                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4835        if completions_menu_has_precedence
 4836            || !offset_selection.is_empty()
 4837            || !self.enable_inline_completions
 4838            || self
 4839                .active_inline_completion
 4840                .as_ref()
 4841                .map_or(false, |completion| {
 4842                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4843                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4844                    !invalidation_range.contains(&offset_selection.head())
 4845                })
 4846        {
 4847            self.discard_inline_completion(false, cx);
 4848            return None;
 4849        }
 4850
 4851        self.take_active_inline_completion(cx);
 4852        let provider = self.inline_completion_provider()?;
 4853
 4854        let (buffer, cursor_buffer_position) =
 4855            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4856
 4857        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4858        let edits = completion
 4859            .edits
 4860            .into_iter()
 4861            .flat_map(|(range, new_text)| {
 4862                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4863                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4864                Some((start..end, new_text))
 4865            })
 4866            .collect::<Vec<_>>();
 4867        if edits.is_empty() {
 4868            return None;
 4869        }
 4870
 4871        let first_edit_start = edits.first().unwrap().0.start;
 4872        let edit_start_row = first_edit_start
 4873            .to_point(&multibuffer)
 4874            .row
 4875            .saturating_sub(2);
 4876
 4877        let last_edit_end = edits.last().unwrap().0.end;
 4878        let edit_end_row = cmp::min(
 4879            multibuffer.max_point().row,
 4880            last_edit_end.to_point(&multibuffer).row + 2,
 4881        );
 4882
 4883        let cursor_row = cursor.to_point(&multibuffer).row;
 4884
 4885        let mut inlay_ids = Vec::new();
 4886        let invalidation_row_range;
 4887        let completion;
 4888        if cursor_row < edit_start_row {
 4889            invalidation_row_range = cursor_row..edit_end_row;
 4890            completion = InlineCompletion::Move(first_edit_start);
 4891        } else if cursor_row > edit_end_row {
 4892            invalidation_row_range = edit_start_row..cursor_row;
 4893            completion = InlineCompletion::Move(first_edit_start);
 4894        } else {
 4895            if edits
 4896                .iter()
 4897                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4898            {
 4899                let mut inlays = Vec::new();
 4900                for (range, new_text) in &edits {
 4901                    let inlay = Inlay::inline_completion(
 4902                        post_inc(&mut self.next_inlay_id),
 4903                        range.start,
 4904                        new_text.as_str(),
 4905                    );
 4906                    inlay_ids.push(inlay.id);
 4907                    inlays.push(inlay);
 4908                }
 4909
 4910                self.splice_inlays(vec![], inlays, cx);
 4911            } else {
 4912                let background_color = cx.theme().status().deleted_background;
 4913                self.highlight_text::<InlineCompletionHighlight>(
 4914                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4915                    HighlightStyle {
 4916                        background_color: Some(background_color),
 4917                        ..Default::default()
 4918                    },
 4919                    cx,
 4920                );
 4921            }
 4922
 4923            invalidation_row_range = edit_start_row..edit_end_row;
 4924            completion = InlineCompletion::Edit(edits);
 4925        };
 4926
 4927        let invalidation_range = multibuffer
 4928            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4929            ..multibuffer.anchor_after(Point::new(
 4930                invalidation_row_range.end,
 4931                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4932            ));
 4933
 4934        self.active_inline_completion = Some(InlineCompletionState {
 4935            inlay_ids,
 4936            completion,
 4937            invalidation_range,
 4938        });
 4939
 4940        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4941            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4942                match self.context_menu.borrow_mut().as_mut() {
 4943                    Some(CodeContextMenu::Completions(menu)) => {
 4944                        menu.show_inline_completion_hint(hint);
 4945                    }
 4946                    _ => {}
 4947                }
 4948            }
 4949        }
 4950
 4951        cx.notify();
 4952
 4953        Some(())
 4954    }
 4955
 4956    fn inline_completion_menu_hint(
 4957        &mut self,
 4958        cx: &mut ViewContext<Self>,
 4959    ) -> Option<InlineCompletionMenuHint> {
 4960        let provider = self.inline_completion_provider()?;
 4961        if self.has_active_inline_completion() {
 4962            let editor_snapshot = self.snapshot(cx);
 4963
 4964            let text = match &self.active_inline_completion.as_ref()?.completion {
 4965                InlineCompletion::Edit(edits) => {
 4966                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4967                }
 4968                InlineCompletion::Move(target) => {
 4969                    let target_point =
 4970                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4971                    let target_line = target_point.row + 1;
 4972                    InlineCompletionText::Move(
 4973                        format!("Jump to edit in line {}", target_line).into(),
 4974                    )
 4975                }
 4976            };
 4977
 4978            Some(InlineCompletionMenuHint::Loaded { text })
 4979        } else if provider.is_refreshing(cx) {
 4980            Some(InlineCompletionMenuHint::Loading)
 4981        } else {
 4982            Some(InlineCompletionMenuHint::None)
 4983        }
 4984    }
 4985
 4986    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4987        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4988    }
 4989
 4990    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4991        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4992            && self
 4993                .inline_completion_provider()
 4994                .map_or(false, |provider| provider.show_completions_in_menu())
 4995    }
 4996
 4997    fn render_code_actions_indicator(
 4998        &self,
 4999        _style: &EditorStyle,
 5000        row: DisplayRow,
 5001        is_active: bool,
 5002        cx: &mut ViewContext<Self>,
 5003    ) -> Option<IconButton> {
 5004        if self.available_code_actions.is_some() {
 5005            Some(
 5006                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5007                    .shape(ui::IconButtonShape::Square)
 5008                    .icon_size(IconSize::XSmall)
 5009                    .icon_color(Color::Muted)
 5010                    .toggle_state(is_active)
 5011                    .tooltip({
 5012                        let focus_handle = self.focus_handle.clone();
 5013                        move |cx| {
 5014                            Tooltip::for_action_in(
 5015                                "Toggle Code Actions",
 5016                                &ToggleCodeActions {
 5017                                    deployed_from_indicator: None,
 5018                                },
 5019                                &focus_handle,
 5020                                cx,
 5021                            )
 5022                        }
 5023                    })
 5024                    .on_click(cx.listener(move |editor, _e, cx| {
 5025                        editor.focus(cx);
 5026                        editor.toggle_code_actions(
 5027                            &ToggleCodeActions {
 5028                                deployed_from_indicator: Some(row),
 5029                            },
 5030                            cx,
 5031                        );
 5032                    })),
 5033            )
 5034        } else {
 5035            None
 5036        }
 5037    }
 5038
 5039    fn clear_tasks(&mut self) {
 5040        self.tasks.clear()
 5041    }
 5042
 5043    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5044        if self.tasks.insert(key, value).is_some() {
 5045            // This case should hopefully be rare, but just in case...
 5046            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5047        }
 5048    }
 5049
 5050    fn build_tasks_context(
 5051        project: &Model<Project>,
 5052        buffer: &Model<Buffer>,
 5053        buffer_row: u32,
 5054        tasks: &Arc<RunnableTasks>,
 5055        cx: &mut ViewContext<Self>,
 5056    ) -> Task<Option<task::TaskContext>> {
 5057        let position = Point::new(buffer_row, tasks.column);
 5058        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5059        let location = Location {
 5060            buffer: buffer.clone(),
 5061            range: range_start..range_start,
 5062        };
 5063        // Fill in the environmental variables from the tree-sitter captures
 5064        let mut captured_task_variables = TaskVariables::default();
 5065        for (capture_name, value) in tasks.extra_variables.clone() {
 5066            captured_task_variables.insert(
 5067                task::VariableName::Custom(capture_name.into()),
 5068                value.clone(),
 5069            );
 5070        }
 5071        project.update(cx, |project, cx| {
 5072            project.task_store().update(cx, |task_store, cx| {
 5073                task_store.task_context_for_location(captured_task_variables, location, cx)
 5074            })
 5075        })
 5076    }
 5077
 5078    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5079        let Some((workspace, _)) = self.workspace.clone() else {
 5080            return;
 5081        };
 5082        let Some(project) = self.project.clone() else {
 5083            return;
 5084        };
 5085
 5086        // Try to find a closest, enclosing node using tree-sitter that has a
 5087        // task
 5088        let Some((buffer, buffer_row, tasks)) = self
 5089            .find_enclosing_node_task(cx)
 5090            // Or find the task that's closest in row-distance.
 5091            .or_else(|| self.find_closest_task(cx))
 5092        else {
 5093            return;
 5094        };
 5095
 5096        let reveal_strategy = action.reveal;
 5097        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5098        cx.spawn(|_, mut cx| async move {
 5099            let context = task_context.await?;
 5100            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5101
 5102            let resolved = resolved_task.resolved.as_mut()?;
 5103            resolved.reveal = reveal_strategy;
 5104
 5105            workspace
 5106                .update(&mut cx, |workspace, cx| {
 5107                    workspace::tasks::schedule_resolved_task(
 5108                        workspace,
 5109                        task_source_kind,
 5110                        resolved_task,
 5111                        false,
 5112                        cx,
 5113                    );
 5114                })
 5115                .ok()
 5116        })
 5117        .detach();
 5118    }
 5119
 5120    fn find_closest_task(
 5121        &mut self,
 5122        cx: &mut ViewContext<Self>,
 5123    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5124        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5125
 5126        let ((buffer_id, row), tasks) = self
 5127            .tasks
 5128            .iter()
 5129            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5130
 5131        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5132        let tasks = Arc::new(tasks.to_owned());
 5133        Some((buffer, *row, tasks))
 5134    }
 5135
 5136    fn find_enclosing_node_task(
 5137        &mut self,
 5138        cx: &mut ViewContext<Self>,
 5139    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5140        let snapshot = self.buffer.read(cx).snapshot(cx);
 5141        let offset = self.selections.newest::<usize>(cx).head();
 5142        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5143        let buffer_id = excerpt.buffer().remote_id();
 5144
 5145        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5146        let mut cursor = layer.node().walk();
 5147
 5148        while cursor.goto_first_child_for_byte(offset).is_some() {
 5149            if cursor.node().end_byte() == offset {
 5150                cursor.goto_next_sibling();
 5151            }
 5152        }
 5153
 5154        // Ascend to the smallest ancestor that contains the range and has a task.
 5155        loop {
 5156            let node = cursor.node();
 5157            let node_range = node.byte_range();
 5158            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5159
 5160            // Check if this node contains our offset
 5161            if node_range.start <= offset && node_range.end >= offset {
 5162                // If it contains offset, check for task
 5163                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5164                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5165                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5166                }
 5167            }
 5168
 5169            if !cursor.goto_parent() {
 5170                break;
 5171            }
 5172        }
 5173        None
 5174    }
 5175
 5176    fn render_run_indicator(
 5177        &self,
 5178        _style: &EditorStyle,
 5179        is_active: bool,
 5180        row: DisplayRow,
 5181        cx: &mut ViewContext<Self>,
 5182    ) -> IconButton {
 5183        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5184            .shape(ui::IconButtonShape::Square)
 5185            .icon_size(IconSize::XSmall)
 5186            .icon_color(Color::Muted)
 5187            .toggle_state(is_active)
 5188            .on_click(cx.listener(move |editor, _e, cx| {
 5189                editor.focus(cx);
 5190                editor.toggle_code_actions(
 5191                    &ToggleCodeActions {
 5192                        deployed_from_indicator: Some(row),
 5193                    },
 5194                    cx,
 5195                );
 5196            }))
 5197    }
 5198
 5199    #[cfg(any(feature = "test-support", test))]
 5200    pub fn context_menu_visible(&self) -> bool {
 5201        self.context_menu
 5202            .borrow()
 5203            .as_ref()
 5204            .map_or(false, |menu| menu.visible())
 5205    }
 5206
 5207    #[cfg(feature = "test-support")]
 5208    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5209        self.context_menu
 5210            .borrow()
 5211            .as_ref()
 5212            .map_or(false, |menu| match menu {
 5213                CodeContextMenu::Completions(menu) => {
 5214                    menu.entries.borrow().first().map_or(false, |entry| {
 5215                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5216                    })
 5217                }
 5218                CodeContextMenu::CodeActions(_) => false,
 5219            })
 5220    }
 5221
 5222    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5223        self.context_menu
 5224            .borrow()
 5225            .as_ref()
 5226            .map(|menu| menu.origin(cursor_position))
 5227    }
 5228
 5229    fn render_context_menu(
 5230        &self,
 5231        style: &EditorStyle,
 5232        max_height_in_lines: u32,
 5233        cx: &mut ViewContext<Editor>,
 5234    ) -> Option<AnyElement> {
 5235        self.context_menu.borrow().as_ref().and_then(|menu| {
 5236            if menu.visible() {
 5237                Some(menu.render(style, max_height_in_lines, cx))
 5238            } else {
 5239                None
 5240            }
 5241        })
 5242    }
 5243
 5244    fn render_context_menu_aside(
 5245        &self,
 5246        style: &EditorStyle,
 5247        max_size: Size<Pixels>,
 5248        cx: &mut ViewContext<Editor>,
 5249    ) -> Option<AnyElement> {
 5250        self.context_menu.borrow().as_ref().and_then(|menu| {
 5251            if menu.visible() {
 5252                menu.render_aside(
 5253                    style,
 5254                    max_size,
 5255                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5256                    cx,
 5257                )
 5258            } else {
 5259                None
 5260            }
 5261        })
 5262    }
 5263
 5264    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5265        cx.notify();
 5266        self.completion_tasks.clear();
 5267        let context_menu = self.context_menu.borrow_mut().take();
 5268        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5269            self.update_visible_inline_completion(cx);
 5270        }
 5271        context_menu
 5272    }
 5273
 5274    fn show_snippet_choices(
 5275        &mut self,
 5276        choices: &Vec<String>,
 5277        selection: Range<Anchor>,
 5278        cx: &mut ViewContext<Self>,
 5279    ) {
 5280        if selection.start.buffer_id.is_none() {
 5281            return;
 5282        }
 5283        let buffer_id = selection.start.buffer_id.unwrap();
 5284        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5285        let id = post_inc(&mut self.next_completion_id);
 5286
 5287        if let Some(buffer) = buffer {
 5288            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5289                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5290            ));
 5291        }
 5292    }
 5293
 5294    pub fn insert_snippet(
 5295        &mut self,
 5296        insertion_ranges: &[Range<usize>],
 5297        snippet: Snippet,
 5298        cx: &mut ViewContext<Self>,
 5299    ) -> Result<()> {
 5300        struct Tabstop<T> {
 5301            is_end_tabstop: bool,
 5302            ranges: Vec<Range<T>>,
 5303            choices: Option<Vec<String>>,
 5304        }
 5305
 5306        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5307            let snippet_text: Arc<str> = snippet.text.clone().into();
 5308            buffer.edit(
 5309                insertion_ranges
 5310                    .iter()
 5311                    .cloned()
 5312                    .map(|range| (range, snippet_text.clone())),
 5313                Some(AutoindentMode::EachLine),
 5314                cx,
 5315            );
 5316
 5317            let snapshot = &*buffer.read(cx);
 5318            let snippet = &snippet;
 5319            snippet
 5320                .tabstops
 5321                .iter()
 5322                .map(|tabstop| {
 5323                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5324                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5325                    });
 5326                    let mut tabstop_ranges = tabstop
 5327                        .ranges
 5328                        .iter()
 5329                        .flat_map(|tabstop_range| {
 5330                            let mut delta = 0_isize;
 5331                            insertion_ranges.iter().map(move |insertion_range| {
 5332                                let insertion_start = insertion_range.start as isize + delta;
 5333                                delta +=
 5334                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5335
 5336                                let start = ((insertion_start + tabstop_range.start) as usize)
 5337                                    .min(snapshot.len());
 5338                                let end = ((insertion_start + tabstop_range.end) as usize)
 5339                                    .min(snapshot.len());
 5340                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5341                            })
 5342                        })
 5343                        .collect::<Vec<_>>();
 5344                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5345
 5346                    Tabstop {
 5347                        is_end_tabstop,
 5348                        ranges: tabstop_ranges,
 5349                        choices: tabstop.choices.clone(),
 5350                    }
 5351                })
 5352                .collect::<Vec<_>>()
 5353        });
 5354        if let Some(tabstop) = tabstops.first() {
 5355            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5356                s.select_ranges(tabstop.ranges.iter().cloned());
 5357            });
 5358
 5359            if let Some(choices) = &tabstop.choices {
 5360                if let Some(selection) = tabstop.ranges.first() {
 5361                    self.show_snippet_choices(choices, selection.clone(), cx)
 5362                }
 5363            }
 5364
 5365            // If we're already at the last tabstop and it's at the end of the snippet,
 5366            // we're done, we don't need to keep the state around.
 5367            if !tabstop.is_end_tabstop {
 5368                let choices = tabstops
 5369                    .iter()
 5370                    .map(|tabstop| tabstop.choices.clone())
 5371                    .collect();
 5372
 5373                let ranges = tabstops
 5374                    .into_iter()
 5375                    .map(|tabstop| tabstop.ranges)
 5376                    .collect::<Vec<_>>();
 5377
 5378                self.snippet_stack.push(SnippetState {
 5379                    active_index: 0,
 5380                    ranges,
 5381                    choices,
 5382                });
 5383            }
 5384
 5385            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5386            if self.autoclose_regions.is_empty() {
 5387                let snapshot = self.buffer.read(cx).snapshot(cx);
 5388                for selection in &mut self.selections.all::<Point>(cx) {
 5389                    let selection_head = selection.head();
 5390                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5391                        continue;
 5392                    };
 5393
 5394                    let mut bracket_pair = None;
 5395                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5396                    let prev_chars = snapshot
 5397                        .reversed_chars_at(selection_head)
 5398                        .collect::<String>();
 5399                    for (pair, enabled) in scope.brackets() {
 5400                        if enabled
 5401                            && pair.close
 5402                            && prev_chars.starts_with(pair.start.as_str())
 5403                            && next_chars.starts_with(pair.end.as_str())
 5404                        {
 5405                            bracket_pair = Some(pair.clone());
 5406                            break;
 5407                        }
 5408                    }
 5409                    if let Some(pair) = bracket_pair {
 5410                        let start = snapshot.anchor_after(selection_head);
 5411                        let end = snapshot.anchor_after(selection_head);
 5412                        self.autoclose_regions.push(AutocloseRegion {
 5413                            selection_id: selection.id,
 5414                            range: start..end,
 5415                            pair,
 5416                        });
 5417                    }
 5418                }
 5419            }
 5420        }
 5421        Ok(())
 5422    }
 5423
 5424    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5425        self.move_to_snippet_tabstop(Bias::Right, cx)
 5426    }
 5427
 5428    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5429        self.move_to_snippet_tabstop(Bias::Left, cx)
 5430    }
 5431
 5432    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5433        if let Some(mut snippet) = self.snippet_stack.pop() {
 5434            match bias {
 5435                Bias::Left => {
 5436                    if snippet.active_index > 0 {
 5437                        snippet.active_index -= 1;
 5438                    } else {
 5439                        self.snippet_stack.push(snippet);
 5440                        return false;
 5441                    }
 5442                }
 5443                Bias::Right => {
 5444                    if snippet.active_index + 1 < snippet.ranges.len() {
 5445                        snippet.active_index += 1;
 5446                    } else {
 5447                        self.snippet_stack.push(snippet);
 5448                        return false;
 5449                    }
 5450                }
 5451            }
 5452            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5453                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5454                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5455                });
 5456
 5457                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5458                    if let Some(selection) = current_ranges.first() {
 5459                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5460                    }
 5461                }
 5462
 5463                // If snippet state is not at the last tabstop, push it back on the stack
 5464                if snippet.active_index + 1 < snippet.ranges.len() {
 5465                    self.snippet_stack.push(snippet);
 5466                }
 5467                return true;
 5468            }
 5469        }
 5470
 5471        false
 5472    }
 5473
 5474    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5475        self.transact(cx, |this, cx| {
 5476            this.select_all(&SelectAll, cx);
 5477            this.insert("", cx);
 5478        });
 5479    }
 5480
 5481    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5482        self.transact(cx, |this, cx| {
 5483            this.select_autoclose_pair(cx);
 5484            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5485            if !this.linked_edit_ranges.is_empty() {
 5486                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5487                let snapshot = this.buffer.read(cx).snapshot(cx);
 5488
 5489                for selection in selections.iter() {
 5490                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5491                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5492                    if selection_start.buffer_id != selection_end.buffer_id {
 5493                        continue;
 5494                    }
 5495                    if let Some(ranges) =
 5496                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5497                    {
 5498                        for (buffer, entries) in ranges {
 5499                            linked_ranges.entry(buffer).or_default().extend(entries);
 5500                        }
 5501                    }
 5502                }
 5503            }
 5504
 5505            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5506            if !this.selections.line_mode {
 5507                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5508                for selection in &mut selections {
 5509                    if selection.is_empty() {
 5510                        let old_head = selection.head();
 5511                        let mut new_head =
 5512                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5513                                .to_point(&display_map);
 5514                        if let Some((buffer, line_buffer_range)) = display_map
 5515                            .buffer_snapshot
 5516                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5517                        {
 5518                            let indent_size =
 5519                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5520                            let indent_len = match indent_size.kind {
 5521                                IndentKind::Space => {
 5522                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5523                                }
 5524                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5525                            };
 5526                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5527                                let indent_len = indent_len.get();
 5528                                new_head = cmp::min(
 5529                                    new_head,
 5530                                    MultiBufferPoint::new(
 5531                                        old_head.row,
 5532                                        ((old_head.column - 1) / indent_len) * indent_len,
 5533                                    ),
 5534                                );
 5535                            }
 5536                        }
 5537
 5538                        selection.set_head(new_head, SelectionGoal::None);
 5539                    }
 5540                }
 5541            }
 5542
 5543            this.signature_help_state.set_backspace_pressed(true);
 5544            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5545            this.insert("", cx);
 5546            let empty_str: Arc<str> = Arc::from("");
 5547            for (buffer, edits) in linked_ranges {
 5548                let snapshot = buffer.read(cx).snapshot();
 5549                use text::ToPoint as TP;
 5550
 5551                let edits = edits
 5552                    .into_iter()
 5553                    .map(|range| {
 5554                        let end_point = TP::to_point(&range.end, &snapshot);
 5555                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5556
 5557                        if end_point == start_point {
 5558                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5559                                .saturating_sub(1);
 5560                            start_point =
 5561                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5562                        };
 5563
 5564                        (start_point..end_point, empty_str.clone())
 5565                    })
 5566                    .sorted_by_key(|(range, _)| range.start)
 5567                    .collect::<Vec<_>>();
 5568                buffer.update(cx, |this, cx| {
 5569                    this.edit(edits, None, cx);
 5570                })
 5571            }
 5572            this.refresh_inline_completion(true, false, cx);
 5573            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5574        });
 5575    }
 5576
 5577    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5578        self.transact(cx, |this, cx| {
 5579            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5580                let line_mode = s.line_mode;
 5581                s.move_with(|map, selection| {
 5582                    if selection.is_empty() && !line_mode {
 5583                        let cursor = movement::right(map, selection.head());
 5584                        selection.end = cursor;
 5585                        selection.reversed = true;
 5586                        selection.goal = SelectionGoal::None;
 5587                    }
 5588                })
 5589            });
 5590            this.insert("", cx);
 5591            this.refresh_inline_completion(true, false, cx);
 5592        });
 5593    }
 5594
 5595    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5596        if self.move_to_prev_snippet_tabstop(cx) {
 5597            return;
 5598        }
 5599
 5600        self.outdent(&Outdent, cx);
 5601    }
 5602
 5603    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5604        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5605            return;
 5606        }
 5607
 5608        let mut selections = self.selections.all_adjusted(cx);
 5609        let buffer = self.buffer.read(cx);
 5610        let snapshot = buffer.snapshot(cx);
 5611        let rows_iter = selections.iter().map(|s| s.head().row);
 5612        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5613
 5614        let mut edits = Vec::new();
 5615        let mut prev_edited_row = 0;
 5616        let mut row_delta = 0;
 5617        for selection in &mut selections {
 5618            if selection.start.row != prev_edited_row {
 5619                row_delta = 0;
 5620            }
 5621            prev_edited_row = selection.end.row;
 5622
 5623            // If the selection is non-empty, then increase the indentation of the selected lines.
 5624            if !selection.is_empty() {
 5625                row_delta =
 5626                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5627                continue;
 5628            }
 5629
 5630            // If the selection is empty and the cursor is in the leading whitespace before the
 5631            // suggested indentation, then auto-indent the line.
 5632            let cursor = selection.head();
 5633            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5634            if let Some(suggested_indent) =
 5635                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5636            {
 5637                if cursor.column < suggested_indent.len
 5638                    && cursor.column <= current_indent.len
 5639                    && current_indent.len <= suggested_indent.len
 5640                {
 5641                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5642                    selection.end = selection.start;
 5643                    if row_delta == 0 {
 5644                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5645                            cursor.row,
 5646                            current_indent,
 5647                            suggested_indent,
 5648                        ));
 5649                        row_delta = suggested_indent.len - current_indent.len;
 5650                    }
 5651                    continue;
 5652                }
 5653            }
 5654
 5655            // Otherwise, insert a hard or soft tab.
 5656            let settings = buffer.settings_at(cursor, cx);
 5657            let tab_size = if settings.hard_tabs {
 5658                IndentSize::tab()
 5659            } else {
 5660                let tab_size = settings.tab_size.get();
 5661                let char_column = snapshot
 5662                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5663                    .flat_map(str::chars)
 5664                    .count()
 5665                    + row_delta as usize;
 5666                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5667                IndentSize::spaces(chars_to_next_tab_stop)
 5668            };
 5669            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5670            selection.end = selection.start;
 5671            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5672            row_delta += tab_size.len;
 5673        }
 5674
 5675        self.transact(cx, |this, cx| {
 5676            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5677            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5678            this.refresh_inline_completion(true, false, cx);
 5679        });
 5680    }
 5681
 5682    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5683        if self.read_only(cx) {
 5684            return;
 5685        }
 5686        let mut selections = self.selections.all::<Point>(cx);
 5687        let mut prev_edited_row = 0;
 5688        let mut row_delta = 0;
 5689        let mut edits = Vec::new();
 5690        let buffer = self.buffer.read(cx);
 5691        let snapshot = buffer.snapshot(cx);
 5692        for selection in &mut selections {
 5693            if selection.start.row != prev_edited_row {
 5694                row_delta = 0;
 5695            }
 5696            prev_edited_row = selection.end.row;
 5697
 5698            row_delta =
 5699                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5700        }
 5701
 5702        self.transact(cx, |this, cx| {
 5703            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5704            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5705        });
 5706    }
 5707
 5708    fn indent_selection(
 5709        buffer: &MultiBuffer,
 5710        snapshot: &MultiBufferSnapshot,
 5711        selection: &mut Selection<Point>,
 5712        edits: &mut Vec<(Range<Point>, String)>,
 5713        delta_for_start_row: u32,
 5714        cx: &AppContext,
 5715    ) -> u32 {
 5716        let settings = buffer.settings_at(selection.start, cx);
 5717        let tab_size = settings.tab_size.get();
 5718        let indent_kind = if settings.hard_tabs {
 5719            IndentKind::Tab
 5720        } else {
 5721            IndentKind::Space
 5722        };
 5723        let mut start_row = selection.start.row;
 5724        let mut end_row = selection.end.row + 1;
 5725
 5726        // If a selection ends at the beginning of a line, don't indent
 5727        // that last line.
 5728        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5729            end_row -= 1;
 5730        }
 5731
 5732        // Avoid re-indenting a row that has already been indented by a
 5733        // previous selection, but still update this selection's column
 5734        // to reflect that indentation.
 5735        if delta_for_start_row > 0 {
 5736            start_row += 1;
 5737            selection.start.column += delta_for_start_row;
 5738            if selection.end.row == selection.start.row {
 5739                selection.end.column += delta_for_start_row;
 5740            }
 5741        }
 5742
 5743        let mut delta_for_end_row = 0;
 5744        let has_multiple_rows = start_row + 1 != end_row;
 5745        for row in start_row..end_row {
 5746            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5747            let indent_delta = match (current_indent.kind, indent_kind) {
 5748                (IndentKind::Space, IndentKind::Space) => {
 5749                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5750                    IndentSize::spaces(columns_to_next_tab_stop)
 5751                }
 5752                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5753                (_, IndentKind::Tab) => IndentSize::tab(),
 5754            };
 5755
 5756            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5757                0
 5758            } else {
 5759                selection.start.column
 5760            };
 5761            let row_start = Point::new(row, start);
 5762            edits.push((
 5763                row_start..row_start,
 5764                indent_delta.chars().collect::<String>(),
 5765            ));
 5766
 5767            // Update this selection's endpoints to reflect the indentation.
 5768            if row == selection.start.row {
 5769                selection.start.column += indent_delta.len;
 5770            }
 5771            if row == selection.end.row {
 5772                selection.end.column += indent_delta.len;
 5773                delta_for_end_row = indent_delta.len;
 5774            }
 5775        }
 5776
 5777        if selection.start.row == selection.end.row {
 5778            delta_for_start_row + delta_for_end_row
 5779        } else {
 5780            delta_for_end_row
 5781        }
 5782    }
 5783
 5784    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5785        if self.read_only(cx) {
 5786            return;
 5787        }
 5788        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5789        let selections = self.selections.all::<Point>(cx);
 5790        let mut deletion_ranges = Vec::new();
 5791        let mut last_outdent = None;
 5792        {
 5793            let buffer = self.buffer.read(cx);
 5794            let snapshot = buffer.snapshot(cx);
 5795            for selection in &selections {
 5796                let settings = buffer.settings_at(selection.start, cx);
 5797                let tab_size = settings.tab_size.get();
 5798                let mut rows = selection.spanned_rows(false, &display_map);
 5799
 5800                // Avoid re-outdenting a row that has already been outdented by a
 5801                // previous selection.
 5802                if let Some(last_row) = last_outdent {
 5803                    if last_row == rows.start {
 5804                        rows.start = rows.start.next_row();
 5805                    }
 5806                }
 5807                let has_multiple_rows = rows.len() > 1;
 5808                for row in rows.iter_rows() {
 5809                    let indent_size = snapshot.indent_size_for_line(row);
 5810                    if indent_size.len > 0 {
 5811                        let deletion_len = match indent_size.kind {
 5812                            IndentKind::Space => {
 5813                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5814                                if columns_to_prev_tab_stop == 0 {
 5815                                    tab_size
 5816                                } else {
 5817                                    columns_to_prev_tab_stop
 5818                                }
 5819                            }
 5820                            IndentKind::Tab => 1,
 5821                        };
 5822                        let start = if has_multiple_rows
 5823                            || deletion_len > selection.start.column
 5824                            || indent_size.len < selection.start.column
 5825                        {
 5826                            0
 5827                        } else {
 5828                            selection.start.column - deletion_len
 5829                        };
 5830                        deletion_ranges.push(
 5831                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5832                        );
 5833                        last_outdent = Some(row);
 5834                    }
 5835                }
 5836            }
 5837        }
 5838
 5839        self.transact(cx, |this, cx| {
 5840            this.buffer.update(cx, |buffer, cx| {
 5841                let empty_str: Arc<str> = Arc::default();
 5842                buffer.edit(
 5843                    deletion_ranges
 5844                        .into_iter()
 5845                        .map(|range| (range, empty_str.clone())),
 5846                    None,
 5847                    cx,
 5848                );
 5849            });
 5850            let selections = this.selections.all::<usize>(cx);
 5851            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5852        });
 5853    }
 5854
 5855    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5856        if self.read_only(cx) {
 5857            return;
 5858        }
 5859        let selections = self
 5860            .selections
 5861            .all::<usize>(cx)
 5862            .into_iter()
 5863            .map(|s| s.range());
 5864
 5865        self.transact(cx, |this, cx| {
 5866            this.buffer.update(cx, |buffer, cx| {
 5867                buffer.autoindent_ranges(selections, cx);
 5868            });
 5869            let selections = this.selections.all::<usize>(cx);
 5870            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5871        });
 5872    }
 5873
 5874    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5875        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5876        let selections = self.selections.all::<Point>(cx);
 5877
 5878        let mut new_cursors = Vec::new();
 5879        let mut edit_ranges = Vec::new();
 5880        let mut selections = selections.iter().peekable();
 5881        while let Some(selection) = selections.next() {
 5882            let mut rows = selection.spanned_rows(false, &display_map);
 5883            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5884
 5885            // Accumulate contiguous regions of rows that we want to delete.
 5886            while let Some(next_selection) = selections.peek() {
 5887                let next_rows = next_selection.spanned_rows(false, &display_map);
 5888                if next_rows.start <= rows.end {
 5889                    rows.end = next_rows.end;
 5890                    selections.next().unwrap();
 5891                } else {
 5892                    break;
 5893                }
 5894            }
 5895
 5896            let buffer = &display_map.buffer_snapshot;
 5897            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5898            let edit_end;
 5899            let cursor_buffer_row;
 5900            if buffer.max_point().row >= rows.end.0 {
 5901                // If there's a line after the range, delete the \n from the end of the row range
 5902                // and position the cursor on the next line.
 5903                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5904                cursor_buffer_row = rows.end;
 5905            } else {
 5906                // If there isn't a line after the range, delete the \n from the line before the
 5907                // start of the row range and position the cursor there.
 5908                edit_start = edit_start.saturating_sub(1);
 5909                edit_end = buffer.len();
 5910                cursor_buffer_row = rows.start.previous_row();
 5911            }
 5912
 5913            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5914            *cursor.column_mut() =
 5915                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5916
 5917            new_cursors.push((
 5918                selection.id,
 5919                buffer.anchor_after(cursor.to_point(&display_map)),
 5920            ));
 5921            edit_ranges.push(edit_start..edit_end);
 5922        }
 5923
 5924        self.transact(cx, |this, cx| {
 5925            let buffer = this.buffer.update(cx, |buffer, cx| {
 5926                let empty_str: Arc<str> = Arc::default();
 5927                buffer.edit(
 5928                    edit_ranges
 5929                        .into_iter()
 5930                        .map(|range| (range, empty_str.clone())),
 5931                    None,
 5932                    cx,
 5933                );
 5934                buffer.snapshot(cx)
 5935            });
 5936            let new_selections = new_cursors
 5937                .into_iter()
 5938                .map(|(id, cursor)| {
 5939                    let cursor = cursor.to_point(&buffer);
 5940                    Selection {
 5941                        id,
 5942                        start: cursor,
 5943                        end: cursor,
 5944                        reversed: false,
 5945                        goal: SelectionGoal::None,
 5946                    }
 5947                })
 5948                .collect();
 5949
 5950            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5951                s.select(new_selections);
 5952            });
 5953        });
 5954    }
 5955
 5956    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5957        if self.read_only(cx) {
 5958            return;
 5959        }
 5960        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5961        for selection in self.selections.all::<Point>(cx) {
 5962            let start = MultiBufferRow(selection.start.row);
 5963            // Treat single line selections as if they include the next line. Otherwise this action
 5964            // would do nothing for single line selections individual cursors.
 5965            let end = if selection.start.row == selection.end.row {
 5966                MultiBufferRow(selection.start.row + 1)
 5967            } else {
 5968                MultiBufferRow(selection.end.row)
 5969            };
 5970
 5971            if let Some(last_row_range) = row_ranges.last_mut() {
 5972                if start <= last_row_range.end {
 5973                    last_row_range.end = end;
 5974                    continue;
 5975                }
 5976            }
 5977            row_ranges.push(start..end);
 5978        }
 5979
 5980        let snapshot = self.buffer.read(cx).snapshot(cx);
 5981        let mut cursor_positions = Vec::new();
 5982        for row_range in &row_ranges {
 5983            let anchor = snapshot.anchor_before(Point::new(
 5984                row_range.end.previous_row().0,
 5985                snapshot.line_len(row_range.end.previous_row()),
 5986            ));
 5987            cursor_positions.push(anchor..anchor);
 5988        }
 5989
 5990        self.transact(cx, |this, cx| {
 5991            for row_range in row_ranges.into_iter().rev() {
 5992                for row in row_range.iter_rows().rev() {
 5993                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5994                    let next_line_row = row.next_row();
 5995                    let indent = snapshot.indent_size_for_line(next_line_row);
 5996                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5997
 5998                    let replace =
 5999                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6000                            " "
 6001                        } else {
 6002                            ""
 6003                        };
 6004
 6005                    this.buffer.update(cx, |buffer, cx| {
 6006                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6007                    });
 6008                }
 6009            }
 6010
 6011            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6012                s.select_anchor_ranges(cursor_positions)
 6013            });
 6014        });
 6015    }
 6016
 6017    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 6018        self.join_lines_impl(true, cx);
 6019    }
 6020
 6021    pub fn sort_lines_case_sensitive(
 6022        &mut self,
 6023        _: &SortLinesCaseSensitive,
 6024        cx: &mut ViewContext<Self>,
 6025    ) {
 6026        self.manipulate_lines(cx, |lines| lines.sort())
 6027    }
 6028
 6029    pub fn sort_lines_case_insensitive(
 6030        &mut self,
 6031        _: &SortLinesCaseInsensitive,
 6032        cx: &mut ViewContext<Self>,
 6033    ) {
 6034        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6035    }
 6036
 6037    pub fn unique_lines_case_insensitive(
 6038        &mut self,
 6039        _: &UniqueLinesCaseInsensitive,
 6040        cx: &mut ViewContext<Self>,
 6041    ) {
 6042        self.manipulate_lines(cx, |lines| {
 6043            let mut seen = HashSet::default();
 6044            lines.retain(|line| seen.insert(line.to_lowercase()));
 6045        })
 6046    }
 6047
 6048    pub fn unique_lines_case_sensitive(
 6049        &mut self,
 6050        _: &UniqueLinesCaseSensitive,
 6051        cx: &mut ViewContext<Self>,
 6052    ) {
 6053        self.manipulate_lines(cx, |lines| {
 6054            let mut seen = HashSet::default();
 6055            lines.retain(|line| seen.insert(*line));
 6056        })
 6057    }
 6058
 6059    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6060        let mut revert_changes = HashMap::default();
 6061        let snapshot = self.snapshot(cx);
 6062        for hunk in hunks_for_ranges(
 6063            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6064            &snapshot,
 6065        ) {
 6066            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6067        }
 6068        if !revert_changes.is_empty() {
 6069            self.transact(cx, |editor, cx| {
 6070                editor.revert(revert_changes, cx);
 6071            });
 6072        }
 6073    }
 6074
 6075    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6076        let Some(project) = self.project.clone() else {
 6077            return;
 6078        };
 6079        self.reload(project, cx).detach_and_notify_err(cx);
 6080    }
 6081
 6082    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6083        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6084        if !revert_changes.is_empty() {
 6085            self.transact(cx, |editor, cx| {
 6086                editor.revert(revert_changes, cx);
 6087            });
 6088        }
 6089    }
 6090
 6091    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6092        let snapshot = self.buffer.read(cx).read(cx);
 6093        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6094            drop(snapshot);
 6095            let mut revert_changes = HashMap::default();
 6096            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6097            if !revert_changes.is_empty() {
 6098                self.revert(revert_changes, cx)
 6099            }
 6100        }
 6101    }
 6102
 6103    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6104        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6105            let project_path = buffer.read(cx).project_path(cx)?;
 6106            let project = self.project.as_ref()?.read(cx);
 6107            let entry = project.entry_for_path(&project_path, cx)?;
 6108            let parent = match &entry.canonical_path {
 6109                Some(canonical_path) => canonical_path.to_path_buf(),
 6110                None => project.absolute_path(&project_path, cx)?,
 6111            }
 6112            .parent()?
 6113            .to_path_buf();
 6114            Some(parent)
 6115        }) {
 6116            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6117        }
 6118    }
 6119
 6120    fn gather_revert_changes(
 6121        &mut self,
 6122        selections: &[Selection<Point>],
 6123        cx: &mut ViewContext<Editor>,
 6124    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6125        let mut revert_changes = HashMap::default();
 6126        let snapshot = self.snapshot(cx);
 6127        for hunk in hunks_for_selections(&snapshot, selections) {
 6128            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6129        }
 6130        revert_changes
 6131    }
 6132
 6133    pub fn prepare_revert_change(
 6134        &mut self,
 6135        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6136        hunk: &MultiBufferDiffHunk,
 6137        cx: &AppContext,
 6138    ) -> Option<()> {
 6139        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6140        let buffer = buffer.read(cx);
 6141        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6142        let original_text = change_set
 6143            .read(cx)
 6144            .base_text
 6145            .as_ref()?
 6146            .read(cx)
 6147            .as_rope()
 6148            .slice(hunk.diff_base_byte_range.clone());
 6149        let buffer_snapshot = buffer.snapshot();
 6150        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6151        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6152            probe
 6153                .0
 6154                .start
 6155                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6156                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6157        }) {
 6158            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6159            Some(())
 6160        } else {
 6161            None
 6162        }
 6163    }
 6164
 6165    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6166        self.manipulate_lines(cx, |lines| lines.reverse())
 6167    }
 6168
 6169    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6170        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6171    }
 6172
 6173    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6174    where
 6175        Fn: FnMut(&mut Vec<&str>),
 6176    {
 6177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6178        let buffer = self.buffer.read(cx).snapshot(cx);
 6179
 6180        let mut edits = Vec::new();
 6181
 6182        let selections = self.selections.all::<Point>(cx);
 6183        let mut selections = selections.iter().peekable();
 6184        let mut contiguous_row_selections = Vec::new();
 6185        let mut new_selections = Vec::new();
 6186        let mut added_lines = 0;
 6187        let mut removed_lines = 0;
 6188
 6189        while let Some(selection) = selections.next() {
 6190            let (start_row, end_row) = consume_contiguous_rows(
 6191                &mut contiguous_row_selections,
 6192                selection,
 6193                &display_map,
 6194                &mut selections,
 6195            );
 6196
 6197            let start_point = Point::new(start_row.0, 0);
 6198            let end_point = Point::new(
 6199                end_row.previous_row().0,
 6200                buffer.line_len(end_row.previous_row()),
 6201            );
 6202            let text = buffer
 6203                .text_for_range(start_point..end_point)
 6204                .collect::<String>();
 6205
 6206            let mut lines = text.split('\n').collect_vec();
 6207
 6208            let lines_before = lines.len();
 6209            callback(&mut lines);
 6210            let lines_after = lines.len();
 6211
 6212            edits.push((start_point..end_point, lines.join("\n")));
 6213
 6214            // Selections must change based on added and removed line count
 6215            let start_row =
 6216                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6217            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6218            new_selections.push(Selection {
 6219                id: selection.id,
 6220                start: start_row,
 6221                end: end_row,
 6222                goal: SelectionGoal::None,
 6223                reversed: selection.reversed,
 6224            });
 6225
 6226            if lines_after > lines_before {
 6227                added_lines += lines_after - lines_before;
 6228            } else if lines_before > lines_after {
 6229                removed_lines += lines_before - lines_after;
 6230            }
 6231        }
 6232
 6233        self.transact(cx, |this, cx| {
 6234            let buffer = this.buffer.update(cx, |buffer, cx| {
 6235                buffer.edit(edits, None, cx);
 6236                buffer.snapshot(cx)
 6237            });
 6238
 6239            // Recalculate offsets on newly edited buffer
 6240            let new_selections = new_selections
 6241                .iter()
 6242                .map(|s| {
 6243                    let start_point = Point::new(s.start.0, 0);
 6244                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6245                    Selection {
 6246                        id: s.id,
 6247                        start: buffer.point_to_offset(start_point),
 6248                        end: buffer.point_to_offset(end_point),
 6249                        goal: s.goal,
 6250                        reversed: s.reversed,
 6251                    }
 6252                })
 6253                .collect();
 6254
 6255            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6256                s.select(new_selections);
 6257            });
 6258
 6259            this.request_autoscroll(Autoscroll::fit(), cx);
 6260        });
 6261    }
 6262
 6263    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6264        self.manipulate_text(cx, |text| text.to_uppercase())
 6265    }
 6266
 6267    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6268        self.manipulate_text(cx, |text| text.to_lowercase())
 6269    }
 6270
 6271    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6272        self.manipulate_text(cx, |text| {
 6273            text.split('\n')
 6274                .map(|line| line.to_case(Case::Title))
 6275                .join("\n")
 6276        })
 6277    }
 6278
 6279    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6280        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6281    }
 6282
 6283    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6284        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6285    }
 6286
 6287    pub fn convert_to_upper_camel_case(
 6288        &mut self,
 6289        _: &ConvertToUpperCamelCase,
 6290        cx: &mut ViewContext<Self>,
 6291    ) {
 6292        self.manipulate_text(cx, |text| {
 6293            text.split('\n')
 6294                .map(|line| line.to_case(Case::UpperCamel))
 6295                .join("\n")
 6296        })
 6297    }
 6298
 6299    pub fn convert_to_lower_camel_case(
 6300        &mut self,
 6301        _: &ConvertToLowerCamelCase,
 6302        cx: &mut ViewContext<Self>,
 6303    ) {
 6304        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6305    }
 6306
 6307    pub fn convert_to_opposite_case(
 6308        &mut self,
 6309        _: &ConvertToOppositeCase,
 6310        cx: &mut ViewContext<Self>,
 6311    ) {
 6312        self.manipulate_text(cx, |text| {
 6313            text.chars()
 6314                .fold(String::with_capacity(text.len()), |mut t, c| {
 6315                    if c.is_uppercase() {
 6316                        t.extend(c.to_lowercase());
 6317                    } else {
 6318                        t.extend(c.to_uppercase());
 6319                    }
 6320                    t
 6321                })
 6322        })
 6323    }
 6324
 6325    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6326    where
 6327        Fn: FnMut(&str) -> String,
 6328    {
 6329        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6330        let buffer = self.buffer.read(cx).snapshot(cx);
 6331
 6332        let mut new_selections = Vec::new();
 6333        let mut edits = Vec::new();
 6334        let mut selection_adjustment = 0i32;
 6335
 6336        for selection in self.selections.all::<usize>(cx) {
 6337            let selection_is_empty = selection.is_empty();
 6338
 6339            let (start, end) = if selection_is_empty {
 6340                let word_range = movement::surrounding_word(
 6341                    &display_map,
 6342                    selection.start.to_display_point(&display_map),
 6343                );
 6344                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6345                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6346                (start, end)
 6347            } else {
 6348                (selection.start, selection.end)
 6349            };
 6350
 6351            let text = buffer.text_for_range(start..end).collect::<String>();
 6352            let old_length = text.len() as i32;
 6353            let text = callback(&text);
 6354
 6355            new_selections.push(Selection {
 6356                start: (start as i32 - selection_adjustment) as usize,
 6357                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6358                goal: SelectionGoal::None,
 6359                ..selection
 6360            });
 6361
 6362            selection_adjustment += old_length - text.len() as i32;
 6363
 6364            edits.push((start..end, text));
 6365        }
 6366
 6367        self.transact(cx, |this, cx| {
 6368            this.buffer.update(cx, |buffer, cx| {
 6369                buffer.edit(edits, None, cx);
 6370            });
 6371
 6372            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6373                s.select(new_selections);
 6374            });
 6375
 6376            this.request_autoscroll(Autoscroll::fit(), cx);
 6377        });
 6378    }
 6379
 6380    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6381        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6382        let buffer = &display_map.buffer_snapshot;
 6383        let selections = self.selections.all::<Point>(cx);
 6384
 6385        let mut edits = Vec::new();
 6386        let mut selections_iter = selections.iter().peekable();
 6387        while let Some(selection) = selections_iter.next() {
 6388            let mut rows = selection.spanned_rows(false, &display_map);
 6389            // duplicate line-wise
 6390            if whole_lines || selection.start == selection.end {
 6391                // Avoid duplicating the same lines twice.
 6392                while let Some(next_selection) = selections_iter.peek() {
 6393                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6394                    if next_rows.start < rows.end {
 6395                        rows.end = next_rows.end;
 6396                        selections_iter.next().unwrap();
 6397                    } else {
 6398                        break;
 6399                    }
 6400                }
 6401
 6402                // Copy the text from the selected row region and splice it either at the start
 6403                // or end of the region.
 6404                let start = Point::new(rows.start.0, 0);
 6405                let end = Point::new(
 6406                    rows.end.previous_row().0,
 6407                    buffer.line_len(rows.end.previous_row()),
 6408                );
 6409                let text = buffer
 6410                    .text_for_range(start..end)
 6411                    .chain(Some("\n"))
 6412                    .collect::<String>();
 6413                let insert_location = if upwards {
 6414                    Point::new(rows.end.0, 0)
 6415                } else {
 6416                    start
 6417                };
 6418                edits.push((insert_location..insert_location, text));
 6419            } else {
 6420                // duplicate character-wise
 6421                let start = selection.start;
 6422                let end = selection.end;
 6423                let text = buffer.text_for_range(start..end).collect::<String>();
 6424                edits.push((selection.end..selection.end, text));
 6425            }
 6426        }
 6427
 6428        self.transact(cx, |this, cx| {
 6429            this.buffer.update(cx, |buffer, cx| {
 6430                buffer.edit(edits, None, cx);
 6431            });
 6432
 6433            this.request_autoscroll(Autoscroll::fit(), cx);
 6434        });
 6435    }
 6436
 6437    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6438        self.duplicate(true, true, cx);
 6439    }
 6440
 6441    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6442        self.duplicate(false, true, cx);
 6443    }
 6444
 6445    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6446        self.duplicate(false, false, cx);
 6447    }
 6448
 6449    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6450        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6451        let buffer = self.buffer.read(cx).snapshot(cx);
 6452
 6453        let mut edits = Vec::new();
 6454        let mut unfold_ranges = Vec::new();
 6455        let mut refold_creases = Vec::new();
 6456
 6457        let selections = self.selections.all::<Point>(cx);
 6458        let mut selections = selections.iter().peekable();
 6459        let mut contiguous_row_selections = Vec::new();
 6460        let mut new_selections = Vec::new();
 6461
 6462        while let Some(selection) = selections.next() {
 6463            // Find all the selections that span a contiguous row range
 6464            let (start_row, end_row) = consume_contiguous_rows(
 6465                &mut contiguous_row_selections,
 6466                selection,
 6467                &display_map,
 6468                &mut selections,
 6469            );
 6470
 6471            // Move the text spanned by the row range to be before the line preceding the row range
 6472            if start_row.0 > 0 {
 6473                let range_to_move = Point::new(
 6474                    start_row.previous_row().0,
 6475                    buffer.line_len(start_row.previous_row()),
 6476                )
 6477                    ..Point::new(
 6478                        end_row.previous_row().0,
 6479                        buffer.line_len(end_row.previous_row()),
 6480                    );
 6481                let insertion_point = display_map
 6482                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6483                    .0;
 6484
 6485                // Don't move lines across excerpts
 6486                if buffer
 6487                    .excerpt_boundaries_in_range((
 6488                        Bound::Excluded(insertion_point),
 6489                        Bound::Included(range_to_move.end),
 6490                    ))
 6491                    .next()
 6492                    .is_none()
 6493                {
 6494                    let text = buffer
 6495                        .text_for_range(range_to_move.clone())
 6496                        .flat_map(|s| s.chars())
 6497                        .skip(1)
 6498                        .chain(['\n'])
 6499                        .collect::<String>();
 6500
 6501                    edits.push((
 6502                        buffer.anchor_after(range_to_move.start)
 6503                            ..buffer.anchor_before(range_to_move.end),
 6504                        String::new(),
 6505                    ));
 6506                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6507                    edits.push((insertion_anchor..insertion_anchor, text));
 6508
 6509                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6510
 6511                    // Move selections up
 6512                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6513                        |mut selection| {
 6514                            selection.start.row -= row_delta;
 6515                            selection.end.row -= row_delta;
 6516                            selection
 6517                        },
 6518                    ));
 6519
 6520                    // Move folds up
 6521                    unfold_ranges.push(range_to_move.clone());
 6522                    for fold in display_map.folds_in_range(
 6523                        buffer.anchor_before(range_to_move.start)
 6524                            ..buffer.anchor_after(range_to_move.end),
 6525                    ) {
 6526                        let mut start = fold.range.start.to_point(&buffer);
 6527                        let mut end = fold.range.end.to_point(&buffer);
 6528                        start.row -= row_delta;
 6529                        end.row -= row_delta;
 6530                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6531                    }
 6532                }
 6533            }
 6534
 6535            // If we didn't move line(s), preserve the existing selections
 6536            new_selections.append(&mut contiguous_row_selections);
 6537        }
 6538
 6539        self.transact(cx, |this, cx| {
 6540            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6541            this.buffer.update(cx, |buffer, cx| {
 6542                for (range, text) in edits {
 6543                    buffer.edit([(range, text)], None, cx);
 6544                }
 6545            });
 6546            this.fold_creases(refold_creases, true, cx);
 6547            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6548                s.select(new_selections);
 6549            })
 6550        });
 6551    }
 6552
 6553    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6555        let buffer = self.buffer.read(cx).snapshot(cx);
 6556
 6557        let mut edits = Vec::new();
 6558        let mut unfold_ranges = Vec::new();
 6559        let mut refold_creases = Vec::new();
 6560
 6561        let selections = self.selections.all::<Point>(cx);
 6562        let mut selections = selections.iter().peekable();
 6563        let mut contiguous_row_selections = Vec::new();
 6564        let mut new_selections = Vec::new();
 6565
 6566        while let Some(selection) = selections.next() {
 6567            // Find all the selections that span a contiguous row range
 6568            let (start_row, end_row) = consume_contiguous_rows(
 6569                &mut contiguous_row_selections,
 6570                selection,
 6571                &display_map,
 6572                &mut selections,
 6573            );
 6574
 6575            // Move the text spanned by the row range to be after the last line of the row range
 6576            if end_row.0 <= buffer.max_point().row {
 6577                let range_to_move =
 6578                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6579                let insertion_point = display_map
 6580                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6581                    .0;
 6582
 6583                // Don't move lines across excerpt boundaries
 6584                if buffer
 6585                    .excerpt_boundaries_in_range((
 6586                        Bound::Excluded(range_to_move.start),
 6587                        Bound::Included(insertion_point),
 6588                    ))
 6589                    .next()
 6590                    .is_none()
 6591                {
 6592                    let mut text = String::from("\n");
 6593                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6594                    text.pop(); // Drop trailing newline
 6595                    edits.push((
 6596                        buffer.anchor_after(range_to_move.start)
 6597                            ..buffer.anchor_before(range_to_move.end),
 6598                        String::new(),
 6599                    ));
 6600                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6601                    edits.push((insertion_anchor..insertion_anchor, text));
 6602
 6603                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6604
 6605                    // Move selections down
 6606                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6607                        |mut selection| {
 6608                            selection.start.row += row_delta;
 6609                            selection.end.row += row_delta;
 6610                            selection
 6611                        },
 6612                    ));
 6613
 6614                    // Move folds down
 6615                    unfold_ranges.push(range_to_move.clone());
 6616                    for fold in display_map.folds_in_range(
 6617                        buffer.anchor_before(range_to_move.start)
 6618                            ..buffer.anchor_after(range_to_move.end),
 6619                    ) {
 6620                        let mut start = fold.range.start.to_point(&buffer);
 6621                        let mut end = fold.range.end.to_point(&buffer);
 6622                        start.row += row_delta;
 6623                        end.row += row_delta;
 6624                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6625                    }
 6626                }
 6627            }
 6628
 6629            // If we didn't move line(s), preserve the existing selections
 6630            new_selections.append(&mut contiguous_row_selections);
 6631        }
 6632
 6633        self.transact(cx, |this, cx| {
 6634            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6635            this.buffer.update(cx, |buffer, cx| {
 6636                for (range, text) in edits {
 6637                    buffer.edit([(range, text)], None, cx);
 6638                }
 6639            });
 6640            this.fold_creases(refold_creases, true, cx);
 6641            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6642        });
 6643    }
 6644
 6645    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6646        let text_layout_details = &self.text_layout_details(cx);
 6647        self.transact(cx, |this, cx| {
 6648            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6649                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6650                let line_mode = s.line_mode;
 6651                s.move_with(|display_map, selection| {
 6652                    if !selection.is_empty() || line_mode {
 6653                        return;
 6654                    }
 6655
 6656                    let mut head = selection.head();
 6657                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6658                    if head.column() == display_map.line_len(head.row()) {
 6659                        transpose_offset = display_map
 6660                            .buffer_snapshot
 6661                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6662                    }
 6663
 6664                    if transpose_offset == 0 {
 6665                        return;
 6666                    }
 6667
 6668                    *head.column_mut() += 1;
 6669                    head = display_map.clip_point(head, Bias::Right);
 6670                    let goal = SelectionGoal::HorizontalPosition(
 6671                        display_map
 6672                            .x_for_display_point(head, text_layout_details)
 6673                            .into(),
 6674                    );
 6675                    selection.collapse_to(head, goal);
 6676
 6677                    let transpose_start = display_map
 6678                        .buffer_snapshot
 6679                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6680                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6681                        let transpose_end = display_map
 6682                            .buffer_snapshot
 6683                            .clip_offset(transpose_offset + 1, Bias::Right);
 6684                        if let Some(ch) =
 6685                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6686                        {
 6687                            edits.push((transpose_start..transpose_offset, String::new()));
 6688                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6689                        }
 6690                    }
 6691                });
 6692                edits
 6693            });
 6694            this.buffer
 6695                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6696            let selections = this.selections.all::<usize>(cx);
 6697            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6698                s.select(selections);
 6699            });
 6700        });
 6701    }
 6702
 6703    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6704        self.rewrap_impl(IsVimMode::No, cx)
 6705    }
 6706
 6707    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6708        let buffer = self.buffer.read(cx).snapshot(cx);
 6709        let selections = self.selections.all::<Point>(cx);
 6710        let mut selections = selections.iter().peekable();
 6711
 6712        let mut edits = Vec::new();
 6713        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6714
 6715        while let Some(selection) = selections.next() {
 6716            let mut start_row = selection.start.row;
 6717            let mut end_row = selection.end.row;
 6718
 6719            // Skip selections that overlap with a range that has already been rewrapped.
 6720            let selection_range = start_row..end_row;
 6721            if rewrapped_row_ranges
 6722                .iter()
 6723                .any(|range| range.overlaps(&selection_range))
 6724            {
 6725                continue;
 6726            }
 6727
 6728            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6729
 6730            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6731                match language_scope.language_name().0.as_ref() {
 6732                    "Markdown" | "Plain Text" => {
 6733                        should_rewrap = true;
 6734                    }
 6735                    _ => {}
 6736                }
 6737            }
 6738
 6739            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6740
 6741            // Since not all lines in the selection may be at the same indent
 6742            // level, choose the indent size that is the most common between all
 6743            // of the lines.
 6744            //
 6745            // If there is a tie, we use the deepest indent.
 6746            let (indent_size, indent_end) = {
 6747                let mut indent_size_occurrences = HashMap::default();
 6748                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6749
 6750                for row in start_row..=end_row {
 6751                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6752                    rows_by_indent_size.entry(indent).or_default().push(row);
 6753                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6754                }
 6755
 6756                let indent_size = indent_size_occurrences
 6757                    .into_iter()
 6758                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6759                    .map(|(indent, _)| indent)
 6760                    .unwrap_or_default();
 6761                let row = rows_by_indent_size[&indent_size][0];
 6762                let indent_end = Point::new(row, indent_size.len);
 6763
 6764                (indent_size, indent_end)
 6765            };
 6766
 6767            let mut line_prefix = indent_size.chars().collect::<String>();
 6768
 6769            if let Some(comment_prefix) =
 6770                buffer
 6771                    .language_scope_at(selection.head())
 6772                    .and_then(|language| {
 6773                        language
 6774                            .line_comment_prefixes()
 6775                            .iter()
 6776                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6777                            .cloned()
 6778                    })
 6779            {
 6780                line_prefix.push_str(&comment_prefix);
 6781                should_rewrap = true;
 6782            }
 6783
 6784            if !should_rewrap {
 6785                continue;
 6786            }
 6787
 6788            if selection.is_empty() {
 6789                'expand_upwards: while start_row > 0 {
 6790                    let prev_row = start_row - 1;
 6791                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6792                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6793                    {
 6794                        start_row = prev_row;
 6795                    } else {
 6796                        break 'expand_upwards;
 6797                    }
 6798                }
 6799
 6800                'expand_downwards: while end_row < buffer.max_point().row {
 6801                    let next_row = end_row + 1;
 6802                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6803                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6804                    {
 6805                        end_row = next_row;
 6806                    } else {
 6807                        break 'expand_downwards;
 6808                    }
 6809                }
 6810            }
 6811
 6812            let start = Point::new(start_row, 0);
 6813            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6814            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6815            let Some(lines_without_prefixes) = selection_text
 6816                .lines()
 6817                .map(|line| {
 6818                    line.strip_prefix(&line_prefix)
 6819                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6820                        .ok_or_else(|| {
 6821                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6822                        })
 6823                })
 6824                .collect::<Result<Vec<_>, _>>()
 6825                .log_err()
 6826            else {
 6827                continue;
 6828            };
 6829
 6830            let wrap_column = buffer
 6831                .settings_at(Point::new(start_row, 0), cx)
 6832                .preferred_line_length as usize;
 6833            let wrapped_text = wrap_with_prefix(
 6834                line_prefix,
 6835                lines_without_prefixes.join(" "),
 6836                wrap_column,
 6837                tab_size,
 6838            );
 6839
 6840            // TODO: should always use char-based diff while still supporting cursor behavior that
 6841            // matches vim.
 6842            let diff = match is_vim_mode {
 6843                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6844                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6845            };
 6846            let mut offset = start.to_offset(&buffer);
 6847            let mut moved_since_edit = true;
 6848
 6849            for change in diff.iter_all_changes() {
 6850                let value = change.value();
 6851                match change.tag() {
 6852                    ChangeTag::Equal => {
 6853                        offset += value.len();
 6854                        moved_since_edit = true;
 6855                    }
 6856                    ChangeTag::Delete => {
 6857                        let start = buffer.anchor_after(offset);
 6858                        let end = buffer.anchor_before(offset + value.len());
 6859
 6860                        if moved_since_edit {
 6861                            edits.push((start..end, String::new()));
 6862                        } else {
 6863                            edits.last_mut().unwrap().0.end = end;
 6864                        }
 6865
 6866                        offset += value.len();
 6867                        moved_since_edit = false;
 6868                    }
 6869                    ChangeTag::Insert => {
 6870                        if moved_since_edit {
 6871                            let anchor = buffer.anchor_after(offset);
 6872                            edits.push((anchor..anchor, value.to_string()));
 6873                        } else {
 6874                            edits.last_mut().unwrap().1.push_str(value);
 6875                        }
 6876
 6877                        moved_since_edit = false;
 6878                    }
 6879                }
 6880            }
 6881
 6882            rewrapped_row_ranges.push(start_row..=end_row);
 6883        }
 6884
 6885        self.buffer
 6886            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6887    }
 6888
 6889    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6890        let mut text = String::new();
 6891        let buffer = self.buffer.read(cx).snapshot(cx);
 6892        let mut selections = self.selections.all::<Point>(cx);
 6893        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6894        {
 6895            let max_point = buffer.max_point();
 6896            let mut is_first = true;
 6897            for selection in &mut selections {
 6898                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6899                if is_entire_line {
 6900                    selection.start = Point::new(selection.start.row, 0);
 6901                    if !selection.is_empty() && selection.end.column == 0 {
 6902                        selection.end = cmp::min(max_point, selection.end);
 6903                    } else {
 6904                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6905                    }
 6906                    selection.goal = SelectionGoal::None;
 6907                }
 6908                if is_first {
 6909                    is_first = false;
 6910                } else {
 6911                    text += "\n";
 6912                }
 6913                let mut len = 0;
 6914                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6915                    text.push_str(chunk);
 6916                    len += chunk.len();
 6917                }
 6918                clipboard_selections.push(ClipboardSelection {
 6919                    len,
 6920                    is_entire_line,
 6921                    first_line_indent: buffer
 6922                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6923                        .len,
 6924                });
 6925            }
 6926        }
 6927
 6928        self.transact(cx, |this, cx| {
 6929            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6930                s.select(selections);
 6931            });
 6932            this.insert("", cx);
 6933        });
 6934        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6935    }
 6936
 6937    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6938        let item = self.cut_common(cx);
 6939        cx.write_to_clipboard(item);
 6940    }
 6941
 6942    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6943        self.change_selections(None, cx, |s| {
 6944            s.move_with(|snapshot, sel| {
 6945                if sel.is_empty() {
 6946                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6947                }
 6948            });
 6949        });
 6950        let item = self.cut_common(cx);
 6951        cx.set_global(KillRing(item))
 6952    }
 6953
 6954    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6955        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6956            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6957                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6958            } else {
 6959                return;
 6960            }
 6961        } else {
 6962            return;
 6963        };
 6964        self.do_paste(&text, metadata, false, cx);
 6965    }
 6966
 6967    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6968        let selections = self.selections.all::<Point>(cx);
 6969        let buffer = self.buffer.read(cx).read(cx);
 6970        let mut text = String::new();
 6971
 6972        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6973        {
 6974            let max_point = buffer.max_point();
 6975            let mut is_first = true;
 6976            for selection in selections.iter() {
 6977                let mut start = selection.start;
 6978                let mut end = selection.end;
 6979                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6980                if is_entire_line {
 6981                    start = Point::new(start.row, 0);
 6982                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6983                }
 6984                if is_first {
 6985                    is_first = false;
 6986                } else {
 6987                    text += "\n";
 6988                }
 6989                let mut len = 0;
 6990                for chunk in buffer.text_for_range(start..end) {
 6991                    text.push_str(chunk);
 6992                    len += chunk.len();
 6993                }
 6994                clipboard_selections.push(ClipboardSelection {
 6995                    len,
 6996                    is_entire_line,
 6997                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6998                });
 6999            }
 7000        }
 7001
 7002        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7003            text,
 7004            clipboard_selections,
 7005        ));
 7006    }
 7007
 7008    pub fn do_paste(
 7009        &mut self,
 7010        text: &String,
 7011        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7012        handle_entire_lines: bool,
 7013        cx: &mut ViewContext<Self>,
 7014    ) {
 7015        if self.read_only(cx) {
 7016            return;
 7017        }
 7018
 7019        let clipboard_text = Cow::Borrowed(text);
 7020
 7021        self.transact(cx, |this, cx| {
 7022            if let Some(mut clipboard_selections) = clipboard_selections {
 7023                let old_selections = this.selections.all::<usize>(cx);
 7024                let all_selections_were_entire_line =
 7025                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7026                let first_selection_indent_column =
 7027                    clipboard_selections.first().map(|s| s.first_line_indent);
 7028                if clipboard_selections.len() != old_selections.len() {
 7029                    clipboard_selections.drain(..);
 7030                }
 7031                let cursor_offset = this.selections.last::<usize>(cx).head();
 7032                let mut auto_indent_on_paste = true;
 7033
 7034                this.buffer.update(cx, |buffer, cx| {
 7035                    let snapshot = buffer.read(cx);
 7036                    auto_indent_on_paste =
 7037                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7038
 7039                    let mut start_offset = 0;
 7040                    let mut edits = Vec::new();
 7041                    let mut original_indent_columns = Vec::new();
 7042                    for (ix, selection) in old_selections.iter().enumerate() {
 7043                        let to_insert;
 7044                        let entire_line;
 7045                        let original_indent_column;
 7046                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7047                            let end_offset = start_offset + clipboard_selection.len;
 7048                            to_insert = &clipboard_text[start_offset..end_offset];
 7049                            entire_line = clipboard_selection.is_entire_line;
 7050                            start_offset = end_offset + 1;
 7051                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7052                        } else {
 7053                            to_insert = clipboard_text.as_str();
 7054                            entire_line = all_selections_were_entire_line;
 7055                            original_indent_column = first_selection_indent_column
 7056                        }
 7057
 7058                        // If the corresponding selection was empty when this slice of the
 7059                        // clipboard text was written, then the entire line containing the
 7060                        // selection was copied. If this selection is also currently empty,
 7061                        // then paste the line before the current line of the buffer.
 7062                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7063                            let column = selection.start.to_point(&snapshot).column as usize;
 7064                            let line_start = selection.start - column;
 7065                            line_start..line_start
 7066                        } else {
 7067                            selection.range()
 7068                        };
 7069
 7070                        edits.push((range, to_insert));
 7071                        original_indent_columns.extend(original_indent_column);
 7072                    }
 7073                    drop(snapshot);
 7074
 7075                    buffer.edit(
 7076                        edits,
 7077                        if auto_indent_on_paste {
 7078                            Some(AutoindentMode::Block {
 7079                                original_indent_columns,
 7080                            })
 7081                        } else {
 7082                            None
 7083                        },
 7084                        cx,
 7085                    );
 7086                });
 7087
 7088                let selections = this.selections.all::<usize>(cx);
 7089                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7090            } else {
 7091                this.insert(&clipboard_text, cx);
 7092            }
 7093        });
 7094    }
 7095
 7096    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7097        if let Some(item) = cx.read_from_clipboard() {
 7098            let entries = item.entries();
 7099
 7100            match entries.first() {
 7101                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7102                // of all the pasted entries.
 7103                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7104                    .do_paste(
 7105                        clipboard_string.text(),
 7106                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7107                        true,
 7108                        cx,
 7109                    ),
 7110                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7111            }
 7112        }
 7113    }
 7114
 7115    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7116        if self.read_only(cx) {
 7117            return;
 7118        }
 7119
 7120        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7121            if let Some((selections, _)) =
 7122                self.selection_history.transaction(transaction_id).cloned()
 7123            {
 7124                self.change_selections(None, cx, |s| {
 7125                    s.select_anchors(selections.to_vec());
 7126                });
 7127            }
 7128            self.request_autoscroll(Autoscroll::fit(), cx);
 7129            self.unmark_text(cx);
 7130            self.refresh_inline_completion(true, false, cx);
 7131            cx.emit(EditorEvent::Edited { transaction_id });
 7132            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7133        }
 7134    }
 7135
 7136    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7137        if self.read_only(cx) {
 7138            return;
 7139        }
 7140
 7141        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7142            if let Some((_, Some(selections))) =
 7143                self.selection_history.transaction(transaction_id).cloned()
 7144            {
 7145                self.change_selections(None, cx, |s| {
 7146                    s.select_anchors(selections.to_vec());
 7147                });
 7148            }
 7149            self.request_autoscroll(Autoscroll::fit(), cx);
 7150            self.unmark_text(cx);
 7151            self.refresh_inline_completion(true, false, cx);
 7152            cx.emit(EditorEvent::Edited { transaction_id });
 7153        }
 7154    }
 7155
 7156    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7157        self.buffer
 7158            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7159    }
 7160
 7161    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7162        self.buffer
 7163            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7164    }
 7165
 7166    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7167        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7168            let line_mode = s.line_mode;
 7169            s.move_with(|map, selection| {
 7170                let cursor = if selection.is_empty() && !line_mode {
 7171                    movement::left(map, selection.start)
 7172                } else {
 7173                    selection.start
 7174                };
 7175                selection.collapse_to(cursor, SelectionGoal::None);
 7176            });
 7177        })
 7178    }
 7179
 7180    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7181        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7182            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7183        })
 7184    }
 7185
 7186    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7187        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7188            let line_mode = s.line_mode;
 7189            s.move_with(|map, selection| {
 7190                let cursor = if selection.is_empty() && !line_mode {
 7191                    movement::right(map, selection.end)
 7192                } else {
 7193                    selection.end
 7194                };
 7195                selection.collapse_to(cursor, SelectionGoal::None)
 7196            });
 7197        })
 7198    }
 7199
 7200    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7201        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7202            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7203        })
 7204    }
 7205
 7206    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7207        if self.take_rename(true, cx).is_some() {
 7208            return;
 7209        }
 7210
 7211        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7212            cx.propagate();
 7213            return;
 7214        }
 7215
 7216        let text_layout_details = &self.text_layout_details(cx);
 7217        let selection_count = self.selections.count();
 7218        let first_selection = self.selections.first_anchor();
 7219
 7220        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7221            let line_mode = s.line_mode;
 7222            s.move_with(|map, selection| {
 7223                if !selection.is_empty() && !line_mode {
 7224                    selection.goal = SelectionGoal::None;
 7225                }
 7226                let (cursor, goal) = movement::up(
 7227                    map,
 7228                    selection.start,
 7229                    selection.goal,
 7230                    false,
 7231                    text_layout_details,
 7232                );
 7233                selection.collapse_to(cursor, goal);
 7234            });
 7235        });
 7236
 7237        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7238        {
 7239            cx.propagate();
 7240        }
 7241    }
 7242
 7243    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7244        if self.take_rename(true, cx).is_some() {
 7245            return;
 7246        }
 7247
 7248        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7249            cx.propagate();
 7250            return;
 7251        }
 7252
 7253        let text_layout_details = &self.text_layout_details(cx);
 7254
 7255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256            let line_mode = s.line_mode;
 7257            s.move_with(|map, selection| {
 7258                if !selection.is_empty() && !line_mode {
 7259                    selection.goal = SelectionGoal::None;
 7260                }
 7261                let (cursor, goal) = movement::up_by_rows(
 7262                    map,
 7263                    selection.start,
 7264                    action.lines,
 7265                    selection.goal,
 7266                    false,
 7267                    text_layout_details,
 7268                );
 7269                selection.collapse_to(cursor, goal);
 7270            });
 7271        })
 7272    }
 7273
 7274    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7275        if self.take_rename(true, cx).is_some() {
 7276            return;
 7277        }
 7278
 7279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7280            cx.propagate();
 7281            return;
 7282        }
 7283
 7284        let text_layout_details = &self.text_layout_details(cx);
 7285
 7286        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7287            let line_mode = s.line_mode;
 7288            s.move_with(|map, selection| {
 7289                if !selection.is_empty() && !line_mode {
 7290                    selection.goal = SelectionGoal::None;
 7291                }
 7292                let (cursor, goal) = movement::down_by_rows(
 7293                    map,
 7294                    selection.start,
 7295                    action.lines,
 7296                    selection.goal,
 7297                    false,
 7298                    text_layout_details,
 7299                );
 7300                selection.collapse_to(cursor, goal);
 7301            });
 7302        })
 7303    }
 7304
 7305    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7306        let text_layout_details = &self.text_layout_details(cx);
 7307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7308            s.move_heads_with(|map, head, goal| {
 7309                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7310            })
 7311        })
 7312    }
 7313
 7314    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7315        let text_layout_details = &self.text_layout_details(cx);
 7316        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7317            s.move_heads_with(|map, head, goal| {
 7318                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7319            })
 7320        })
 7321    }
 7322
 7323    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7324        let Some(row_count) = self.visible_row_count() else {
 7325            return;
 7326        };
 7327
 7328        let text_layout_details = &self.text_layout_details(cx);
 7329
 7330        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7331            s.move_heads_with(|map, head, goal| {
 7332                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7333            })
 7334        })
 7335    }
 7336
 7337    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7338        if self.take_rename(true, cx).is_some() {
 7339            return;
 7340        }
 7341
 7342        if self
 7343            .context_menu
 7344            .borrow_mut()
 7345            .as_mut()
 7346            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7347            .unwrap_or(false)
 7348        {
 7349            return;
 7350        }
 7351
 7352        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7353            cx.propagate();
 7354            return;
 7355        }
 7356
 7357        let Some(row_count) = self.visible_row_count() else {
 7358            return;
 7359        };
 7360
 7361        let autoscroll = if action.center_cursor {
 7362            Autoscroll::center()
 7363        } else {
 7364            Autoscroll::fit()
 7365        };
 7366
 7367        let text_layout_details = &self.text_layout_details(cx);
 7368
 7369        self.change_selections(Some(autoscroll), cx, |s| {
 7370            let line_mode = s.line_mode;
 7371            s.move_with(|map, selection| {
 7372                if !selection.is_empty() && !line_mode {
 7373                    selection.goal = SelectionGoal::None;
 7374                }
 7375                let (cursor, goal) = movement::up_by_rows(
 7376                    map,
 7377                    selection.end,
 7378                    row_count,
 7379                    selection.goal,
 7380                    false,
 7381                    text_layout_details,
 7382                );
 7383                selection.collapse_to(cursor, goal);
 7384            });
 7385        });
 7386    }
 7387
 7388    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7389        let text_layout_details = &self.text_layout_details(cx);
 7390        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7391            s.move_heads_with(|map, head, goal| {
 7392                movement::up(map, head, goal, false, text_layout_details)
 7393            })
 7394        })
 7395    }
 7396
 7397    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7398        self.take_rename(true, cx);
 7399
 7400        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7401            cx.propagate();
 7402            return;
 7403        }
 7404
 7405        let text_layout_details = &self.text_layout_details(cx);
 7406        let selection_count = self.selections.count();
 7407        let first_selection = self.selections.first_anchor();
 7408
 7409        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7410            let line_mode = s.line_mode;
 7411            s.move_with(|map, selection| {
 7412                if !selection.is_empty() && !line_mode {
 7413                    selection.goal = SelectionGoal::None;
 7414                }
 7415                let (cursor, goal) = movement::down(
 7416                    map,
 7417                    selection.end,
 7418                    selection.goal,
 7419                    false,
 7420                    text_layout_details,
 7421                );
 7422                selection.collapse_to(cursor, goal);
 7423            });
 7424        });
 7425
 7426        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7427        {
 7428            cx.propagate();
 7429        }
 7430    }
 7431
 7432    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7433        let Some(row_count) = self.visible_row_count() else {
 7434            return;
 7435        };
 7436
 7437        let text_layout_details = &self.text_layout_details(cx);
 7438
 7439        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7440            s.move_heads_with(|map, head, goal| {
 7441                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7442            })
 7443        })
 7444    }
 7445
 7446    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7447        if self.take_rename(true, cx).is_some() {
 7448            return;
 7449        }
 7450
 7451        if self
 7452            .context_menu
 7453            .borrow_mut()
 7454            .as_mut()
 7455            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7456            .unwrap_or(false)
 7457        {
 7458            return;
 7459        }
 7460
 7461        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7462            cx.propagate();
 7463            return;
 7464        }
 7465
 7466        let Some(row_count) = self.visible_row_count() else {
 7467            return;
 7468        };
 7469
 7470        let autoscroll = if action.center_cursor {
 7471            Autoscroll::center()
 7472        } else {
 7473            Autoscroll::fit()
 7474        };
 7475
 7476        let text_layout_details = &self.text_layout_details(cx);
 7477        self.change_selections(Some(autoscroll), cx, |s| {
 7478            let line_mode = s.line_mode;
 7479            s.move_with(|map, selection| {
 7480                if !selection.is_empty() && !line_mode {
 7481                    selection.goal = SelectionGoal::None;
 7482                }
 7483                let (cursor, goal) = movement::down_by_rows(
 7484                    map,
 7485                    selection.end,
 7486                    row_count,
 7487                    selection.goal,
 7488                    false,
 7489                    text_layout_details,
 7490                );
 7491                selection.collapse_to(cursor, goal);
 7492            });
 7493        });
 7494    }
 7495
 7496    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7497        let text_layout_details = &self.text_layout_details(cx);
 7498        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7499            s.move_heads_with(|map, head, goal| {
 7500                movement::down(map, head, goal, false, text_layout_details)
 7501            })
 7502        });
 7503    }
 7504
 7505    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7506        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7507            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7508        }
 7509    }
 7510
 7511    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7512        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7513            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7514        }
 7515    }
 7516
 7517    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7518        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7519            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7520        }
 7521    }
 7522
 7523    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7524        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7525            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7526        }
 7527    }
 7528
 7529    pub fn move_to_previous_word_start(
 7530        &mut self,
 7531        _: &MoveToPreviousWordStart,
 7532        cx: &mut ViewContext<Self>,
 7533    ) {
 7534        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7535            s.move_cursors_with(|map, head, _| {
 7536                (
 7537                    movement::previous_word_start(map, head),
 7538                    SelectionGoal::None,
 7539                )
 7540            });
 7541        })
 7542    }
 7543
 7544    pub fn move_to_previous_subword_start(
 7545        &mut self,
 7546        _: &MoveToPreviousSubwordStart,
 7547        cx: &mut ViewContext<Self>,
 7548    ) {
 7549        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7550            s.move_cursors_with(|map, head, _| {
 7551                (
 7552                    movement::previous_subword_start(map, head),
 7553                    SelectionGoal::None,
 7554                )
 7555            });
 7556        })
 7557    }
 7558
 7559    pub fn select_to_previous_word_start(
 7560        &mut self,
 7561        _: &SelectToPreviousWordStart,
 7562        cx: &mut ViewContext<Self>,
 7563    ) {
 7564        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7565            s.move_heads_with(|map, head, _| {
 7566                (
 7567                    movement::previous_word_start(map, head),
 7568                    SelectionGoal::None,
 7569                )
 7570            });
 7571        })
 7572    }
 7573
 7574    pub fn select_to_previous_subword_start(
 7575        &mut self,
 7576        _: &SelectToPreviousSubwordStart,
 7577        cx: &mut ViewContext<Self>,
 7578    ) {
 7579        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7580            s.move_heads_with(|map, head, _| {
 7581                (
 7582                    movement::previous_subword_start(map, head),
 7583                    SelectionGoal::None,
 7584                )
 7585            });
 7586        })
 7587    }
 7588
 7589    pub fn delete_to_previous_word_start(
 7590        &mut self,
 7591        action: &DeleteToPreviousWordStart,
 7592        cx: &mut ViewContext<Self>,
 7593    ) {
 7594        self.transact(cx, |this, cx| {
 7595            this.select_autoclose_pair(cx);
 7596            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7597                let line_mode = s.line_mode;
 7598                s.move_with(|map, selection| {
 7599                    if selection.is_empty() && !line_mode {
 7600                        let cursor = if action.ignore_newlines {
 7601                            movement::previous_word_start(map, selection.head())
 7602                        } else {
 7603                            movement::previous_word_start_or_newline(map, selection.head())
 7604                        };
 7605                        selection.set_head(cursor, SelectionGoal::None);
 7606                    }
 7607                });
 7608            });
 7609            this.insert("", cx);
 7610        });
 7611    }
 7612
 7613    pub fn delete_to_previous_subword_start(
 7614        &mut self,
 7615        _: &DeleteToPreviousSubwordStart,
 7616        cx: &mut ViewContext<Self>,
 7617    ) {
 7618        self.transact(cx, |this, cx| {
 7619            this.select_autoclose_pair(cx);
 7620            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7621                let line_mode = s.line_mode;
 7622                s.move_with(|map, selection| {
 7623                    if selection.is_empty() && !line_mode {
 7624                        let cursor = movement::previous_subword_start(map, selection.head());
 7625                        selection.set_head(cursor, SelectionGoal::None);
 7626                    }
 7627                });
 7628            });
 7629            this.insert("", cx);
 7630        });
 7631    }
 7632
 7633    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7634        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7635            s.move_cursors_with(|map, head, _| {
 7636                (movement::next_word_end(map, head), SelectionGoal::None)
 7637            });
 7638        })
 7639    }
 7640
 7641    pub fn move_to_next_subword_end(
 7642        &mut self,
 7643        _: &MoveToNextSubwordEnd,
 7644        cx: &mut ViewContext<Self>,
 7645    ) {
 7646        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7647            s.move_cursors_with(|map, head, _| {
 7648                (movement::next_subword_end(map, head), SelectionGoal::None)
 7649            });
 7650        })
 7651    }
 7652
 7653    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7654        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7655            s.move_heads_with(|map, head, _| {
 7656                (movement::next_word_end(map, head), SelectionGoal::None)
 7657            });
 7658        })
 7659    }
 7660
 7661    pub fn select_to_next_subword_end(
 7662        &mut self,
 7663        _: &SelectToNextSubwordEnd,
 7664        cx: &mut ViewContext<Self>,
 7665    ) {
 7666        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7667            s.move_heads_with(|map, head, _| {
 7668                (movement::next_subword_end(map, head), SelectionGoal::None)
 7669            });
 7670        })
 7671    }
 7672
 7673    pub fn delete_to_next_word_end(
 7674        &mut self,
 7675        action: &DeleteToNextWordEnd,
 7676        cx: &mut ViewContext<Self>,
 7677    ) {
 7678        self.transact(cx, |this, cx| {
 7679            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680                let line_mode = s.line_mode;
 7681                s.move_with(|map, selection| {
 7682                    if selection.is_empty() && !line_mode {
 7683                        let cursor = if action.ignore_newlines {
 7684                            movement::next_word_end(map, selection.head())
 7685                        } else {
 7686                            movement::next_word_end_or_newline(map, selection.head())
 7687                        };
 7688                        selection.set_head(cursor, SelectionGoal::None);
 7689                    }
 7690                });
 7691            });
 7692            this.insert("", cx);
 7693        });
 7694    }
 7695
 7696    pub fn delete_to_next_subword_end(
 7697        &mut self,
 7698        _: &DeleteToNextSubwordEnd,
 7699        cx: &mut ViewContext<Self>,
 7700    ) {
 7701        self.transact(cx, |this, cx| {
 7702            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703                s.move_with(|map, selection| {
 7704                    if selection.is_empty() {
 7705                        let cursor = movement::next_subword_end(map, selection.head());
 7706                        selection.set_head(cursor, SelectionGoal::None);
 7707                    }
 7708                });
 7709            });
 7710            this.insert("", cx);
 7711        });
 7712    }
 7713
 7714    pub fn move_to_beginning_of_line(
 7715        &mut self,
 7716        action: &MoveToBeginningOfLine,
 7717        cx: &mut ViewContext<Self>,
 7718    ) {
 7719        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7720            s.move_cursors_with(|map, head, _| {
 7721                (
 7722                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7723                    SelectionGoal::None,
 7724                )
 7725            });
 7726        })
 7727    }
 7728
 7729    pub fn select_to_beginning_of_line(
 7730        &mut self,
 7731        action: &SelectToBeginningOfLine,
 7732        cx: &mut ViewContext<Self>,
 7733    ) {
 7734        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7735            s.move_heads_with(|map, head, _| {
 7736                (
 7737                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7738                    SelectionGoal::None,
 7739                )
 7740            });
 7741        });
 7742    }
 7743
 7744    pub fn delete_to_beginning_of_line(
 7745        &mut self,
 7746        _: &DeleteToBeginningOfLine,
 7747        cx: &mut ViewContext<Self>,
 7748    ) {
 7749        self.transact(cx, |this, cx| {
 7750            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7751                s.move_with(|_, selection| {
 7752                    selection.reversed = true;
 7753                });
 7754            });
 7755
 7756            this.select_to_beginning_of_line(
 7757                &SelectToBeginningOfLine {
 7758                    stop_at_soft_wraps: false,
 7759                },
 7760                cx,
 7761            );
 7762            this.backspace(&Backspace, cx);
 7763        });
 7764    }
 7765
 7766    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7767        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7768            s.move_cursors_with(|map, head, _| {
 7769                (
 7770                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7771                    SelectionGoal::None,
 7772                )
 7773            });
 7774        })
 7775    }
 7776
 7777    pub fn select_to_end_of_line(
 7778        &mut self,
 7779        action: &SelectToEndOfLine,
 7780        cx: &mut ViewContext<Self>,
 7781    ) {
 7782        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7783            s.move_heads_with(|map, head, _| {
 7784                (
 7785                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7786                    SelectionGoal::None,
 7787                )
 7788            });
 7789        })
 7790    }
 7791
 7792    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7793        self.transact(cx, |this, cx| {
 7794            this.select_to_end_of_line(
 7795                &SelectToEndOfLine {
 7796                    stop_at_soft_wraps: false,
 7797                },
 7798                cx,
 7799            );
 7800            this.delete(&Delete, cx);
 7801        });
 7802    }
 7803
 7804    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7805        self.transact(cx, |this, cx| {
 7806            this.select_to_end_of_line(
 7807                &SelectToEndOfLine {
 7808                    stop_at_soft_wraps: false,
 7809                },
 7810                cx,
 7811            );
 7812            this.cut(&Cut, cx);
 7813        });
 7814    }
 7815
 7816    pub fn move_to_start_of_paragraph(
 7817        &mut self,
 7818        _: &MoveToStartOfParagraph,
 7819        cx: &mut ViewContext<Self>,
 7820    ) {
 7821        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7822            cx.propagate();
 7823            return;
 7824        }
 7825
 7826        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7827            s.move_with(|map, selection| {
 7828                selection.collapse_to(
 7829                    movement::start_of_paragraph(map, selection.head(), 1),
 7830                    SelectionGoal::None,
 7831                )
 7832            });
 7833        })
 7834    }
 7835
 7836    pub fn move_to_end_of_paragraph(
 7837        &mut self,
 7838        _: &MoveToEndOfParagraph,
 7839        cx: &mut ViewContext<Self>,
 7840    ) {
 7841        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7842            cx.propagate();
 7843            return;
 7844        }
 7845
 7846        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7847            s.move_with(|map, selection| {
 7848                selection.collapse_to(
 7849                    movement::end_of_paragraph(map, selection.head(), 1),
 7850                    SelectionGoal::None,
 7851                )
 7852            });
 7853        })
 7854    }
 7855
 7856    pub fn select_to_start_of_paragraph(
 7857        &mut self,
 7858        _: &SelectToStartOfParagraph,
 7859        cx: &mut ViewContext<Self>,
 7860    ) {
 7861        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7862            cx.propagate();
 7863            return;
 7864        }
 7865
 7866        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7867            s.move_heads_with(|map, head, _| {
 7868                (
 7869                    movement::start_of_paragraph(map, head, 1),
 7870                    SelectionGoal::None,
 7871                )
 7872            });
 7873        })
 7874    }
 7875
 7876    pub fn select_to_end_of_paragraph(
 7877        &mut self,
 7878        _: &SelectToEndOfParagraph,
 7879        cx: &mut ViewContext<Self>,
 7880    ) {
 7881        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7882            cx.propagate();
 7883            return;
 7884        }
 7885
 7886        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7887            s.move_heads_with(|map, head, _| {
 7888                (
 7889                    movement::end_of_paragraph(map, head, 1),
 7890                    SelectionGoal::None,
 7891                )
 7892            });
 7893        })
 7894    }
 7895
 7896    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7897        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7898            cx.propagate();
 7899            return;
 7900        }
 7901
 7902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7903            s.select_ranges(vec![0..0]);
 7904        });
 7905    }
 7906
 7907    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7908        let mut selection = self.selections.last::<Point>(cx);
 7909        selection.set_head(Point::zero(), SelectionGoal::None);
 7910
 7911        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7912            s.select(vec![selection]);
 7913        });
 7914    }
 7915
 7916    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7917        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7918            cx.propagate();
 7919            return;
 7920        }
 7921
 7922        let cursor = self.buffer.read(cx).read(cx).len();
 7923        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7924            s.select_ranges(vec![cursor..cursor])
 7925        });
 7926    }
 7927
 7928    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7929        self.nav_history = nav_history;
 7930    }
 7931
 7932    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7933        self.nav_history.as_ref()
 7934    }
 7935
 7936    fn push_to_nav_history(
 7937        &mut self,
 7938        cursor_anchor: Anchor,
 7939        new_position: Option<Point>,
 7940        cx: &mut ViewContext<Self>,
 7941    ) {
 7942        if let Some(nav_history) = self.nav_history.as_mut() {
 7943            let buffer = self.buffer.read(cx).read(cx);
 7944            let cursor_position = cursor_anchor.to_point(&buffer);
 7945            let scroll_state = self.scroll_manager.anchor();
 7946            let scroll_top_row = scroll_state.top_row(&buffer);
 7947            drop(buffer);
 7948
 7949            if let Some(new_position) = new_position {
 7950                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7951                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7952                    return;
 7953                }
 7954            }
 7955
 7956            nav_history.push(
 7957                Some(NavigationData {
 7958                    cursor_anchor,
 7959                    cursor_position,
 7960                    scroll_anchor: scroll_state,
 7961                    scroll_top_row,
 7962                }),
 7963                cx,
 7964            );
 7965        }
 7966    }
 7967
 7968    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7969        let buffer = self.buffer.read(cx).snapshot(cx);
 7970        let mut selection = self.selections.first::<usize>(cx);
 7971        selection.set_head(buffer.len(), SelectionGoal::None);
 7972        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7973            s.select(vec![selection]);
 7974        });
 7975    }
 7976
 7977    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7978        let end = self.buffer.read(cx).read(cx).len();
 7979        self.change_selections(None, cx, |s| {
 7980            s.select_ranges(vec![0..end]);
 7981        });
 7982    }
 7983
 7984    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7985        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7986        let mut selections = self.selections.all::<Point>(cx);
 7987        let max_point = display_map.buffer_snapshot.max_point();
 7988        for selection in &mut selections {
 7989            let rows = selection.spanned_rows(true, &display_map);
 7990            selection.start = Point::new(rows.start.0, 0);
 7991            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7992            selection.reversed = false;
 7993        }
 7994        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7995            s.select(selections);
 7996        });
 7997    }
 7998
 7999    pub fn split_selection_into_lines(
 8000        &mut self,
 8001        _: &SplitSelectionIntoLines,
 8002        cx: &mut ViewContext<Self>,
 8003    ) {
 8004        let mut to_unfold = Vec::new();
 8005        let mut new_selection_ranges = Vec::new();
 8006        {
 8007            let selections = self.selections.all::<Point>(cx);
 8008            let buffer = self.buffer.read(cx).read(cx);
 8009            for selection in selections {
 8010                for row in selection.start.row..selection.end.row {
 8011                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8012                    new_selection_ranges.push(cursor..cursor);
 8013                }
 8014                new_selection_ranges.push(selection.end..selection.end);
 8015                to_unfold.push(selection.start..selection.end);
 8016            }
 8017        }
 8018        self.unfold_ranges(&to_unfold, true, true, cx);
 8019        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8020            s.select_ranges(new_selection_ranges);
 8021        });
 8022    }
 8023
 8024    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 8025        self.add_selection(true, cx);
 8026    }
 8027
 8028    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 8029        self.add_selection(false, cx);
 8030    }
 8031
 8032    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 8033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8034        let mut selections = self.selections.all::<Point>(cx);
 8035        let text_layout_details = self.text_layout_details(cx);
 8036        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8037            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8038            let range = oldest_selection.display_range(&display_map).sorted();
 8039
 8040            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8041            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8042            let positions = start_x.min(end_x)..start_x.max(end_x);
 8043
 8044            selections.clear();
 8045            let mut stack = Vec::new();
 8046            for row in range.start.row().0..=range.end.row().0 {
 8047                if let Some(selection) = self.selections.build_columnar_selection(
 8048                    &display_map,
 8049                    DisplayRow(row),
 8050                    &positions,
 8051                    oldest_selection.reversed,
 8052                    &text_layout_details,
 8053                ) {
 8054                    stack.push(selection.id);
 8055                    selections.push(selection);
 8056                }
 8057            }
 8058
 8059            if above {
 8060                stack.reverse();
 8061            }
 8062
 8063            AddSelectionsState { above, stack }
 8064        });
 8065
 8066        let last_added_selection = *state.stack.last().unwrap();
 8067        let mut new_selections = Vec::new();
 8068        if above == state.above {
 8069            let end_row = if above {
 8070                DisplayRow(0)
 8071            } else {
 8072                display_map.max_point().row()
 8073            };
 8074
 8075            'outer: for selection in selections {
 8076                if selection.id == last_added_selection {
 8077                    let range = selection.display_range(&display_map).sorted();
 8078                    debug_assert_eq!(range.start.row(), range.end.row());
 8079                    let mut row = range.start.row();
 8080                    let positions =
 8081                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8082                            px(start)..px(end)
 8083                        } else {
 8084                            let start_x =
 8085                                display_map.x_for_display_point(range.start, &text_layout_details);
 8086                            let end_x =
 8087                                display_map.x_for_display_point(range.end, &text_layout_details);
 8088                            start_x.min(end_x)..start_x.max(end_x)
 8089                        };
 8090
 8091                    while row != end_row {
 8092                        if above {
 8093                            row.0 -= 1;
 8094                        } else {
 8095                            row.0 += 1;
 8096                        }
 8097
 8098                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8099                            &display_map,
 8100                            row,
 8101                            &positions,
 8102                            selection.reversed,
 8103                            &text_layout_details,
 8104                        ) {
 8105                            state.stack.push(new_selection.id);
 8106                            if above {
 8107                                new_selections.push(new_selection);
 8108                                new_selections.push(selection);
 8109                            } else {
 8110                                new_selections.push(selection);
 8111                                new_selections.push(new_selection);
 8112                            }
 8113
 8114                            continue 'outer;
 8115                        }
 8116                    }
 8117                }
 8118
 8119                new_selections.push(selection);
 8120            }
 8121        } else {
 8122            new_selections = selections;
 8123            new_selections.retain(|s| s.id != last_added_selection);
 8124            state.stack.pop();
 8125        }
 8126
 8127        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8128            s.select(new_selections);
 8129        });
 8130        if state.stack.len() > 1 {
 8131            self.add_selections_state = Some(state);
 8132        }
 8133    }
 8134
 8135    pub fn select_next_match_internal(
 8136        &mut self,
 8137        display_map: &DisplaySnapshot,
 8138        replace_newest: bool,
 8139        autoscroll: Option<Autoscroll>,
 8140        cx: &mut ViewContext<Self>,
 8141    ) -> Result<()> {
 8142        fn select_next_match_ranges(
 8143            this: &mut Editor,
 8144            range: Range<usize>,
 8145            replace_newest: bool,
 8146            auto_scroll: Option<Autoscroll>,
 8147            cx: &mut ViewContext<Editor>,
 8148        ) {
 8149            this.unfold_ranges(&[range.clone()], false, true, cx);
 8150            this.change_selections(auto_scroll, cx, |s| {
 8151                if replace_newest {
 8152                    s.delete(s.newest_anchor().id);
 8153                }
 8154                s.insert_range(range.clone());
 8155            });
 8156        }
 8157
 8158        let buffer = &display_map.buffer_snapshot;
 8159        let mut selections = self.selections.all::<usize>(cx);
 8160        if let Some(mut select_next_state) = self.select_next_state.take() {
 8161            let query = &select_next_state.query;
 8162            if !select_next_state.done {
 8163                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8164                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8165                let mut next_selected_range = None;
 8166
 8167                let bytes_after_last_selection =
 8168                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8169                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8170                let query_matches = query
 8171                    .stream_find_iter(bytes_after_last_selection)
 8172                    .map(|result| (last_selection.end, result))
 8173                    .chain(
 8174                        query
 8175                            .stream_find_iter(bytes_before_first_selection)
 8176                            .map(|result| (0, result)),
 8177                    );
 8178
 8179                for (start_offset, query_match) in query_matches {
 8180                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8181                    let offset_range =
 8182                        start_offset + query_match.start()..start_offset + query_match.end();
 8183                    let display_range = offset_range.start.to_display_point(display_map)
 8184                        ..offset_range.end.to_display_point(display_map);
 8185
 8186                    if !select_next_state.wordwise
 8187                        || (!movement::is_inside_word(display_map, display_range.start)
 8188                            && !movement::is_inside_word(display_map, display_range.end))
 8189                    {
 8190                        // TODO: This is n^2, because we might check all the selections
 8191                        if !selections
 8192                            .iter()
 8193                            .any(|selection| selection.range().overlaps(&offset_range))
 8194                        {
 8195                            next_selected_range = Some(offset_range);
 8196                            break;
 8197                        }
 8198                    }
 8199                }
 8200
 8201                if let Some(next_selected_range) = next_selected_range {
 8202                    select_next_match_ranges(
 8203                        self,
 8204                        next_selected_range,
 8205                        replace_newest,
 8206                        autoscroll,
 8207                        cx,
 8208                    );
 8209                } else {
 8210                    select_next_state.done = true;
 8211                }
 8212            }
 8213
 8214            self.select_next_state = Some(select_next_state);
 8215        } else {
 8216            let mut only_carets = true;
 8217            let mut same_text_selected = true;
 8218            let mut selected_text = None;
 8219
 8220            let mut selections_iter = selections.iter().peekable();
 8221            while let Some(selection) = selections_iter.next() {
 8222                if selection.start != selection.end {
 8223                    only_carets = false;
 8224                }
 8225
 8226                if same_text_selected {
 8227                    if selected_text.is_none() {
 8228                        selected_text =
 8229                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8230                    }
 8231
 8232                    if let Some(next_selection) = selections_iter.peek() {
 8233                        if next_selection.range().len() == selection.range().len() {
 8234                            let next_selected_text = buffer
 8235                                .text_for_range(next_selection.range())
 8236                                .collect::<String>();
 8237                            if Some(next_selected_text) != selected_text {
 8238                                same_text_selected = false;
 8239                                selected_text = None;
 8240                            }
 8241                        } else {
 8242                            same_text_selected = false;
 8243                            selected_text = None;
 8244                        }
 8245                    }
 8246                }
 8247            }
 8248
 8249            if only_carets {
 8250                for selection in &mut selections {
 8251                    let word_range = movement::surrounding_word(
 8252                        display_map,
 8253                        selection.start.to_display_point(display_map),
 8254                    );
 8255                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8256                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8257                    selection.goal = SelectionGoal::None;
 8258                    selection.reversed = false;
 8259                    select_next_match_ranges(
 8260                        self,
 8261                        selection.start..selection.end,
 8262                        replace_newest,
 8263                        autoscroll,
 8264                        cx,
 8265                    );
 8266                }
 8267
 8268                if selections.len() == 1 {
 8269                    let selection = selections
 8270                        .last()
 8271                        .expect("ensured that there's only one selection");
 8272                    let query = buffer
 8273                        .text_for_range(selection.start..selection.end)
 8274                        .collect::<String>();
 8275                    let is_empty = query.is_empty();
 8276                    let select_state = SelectNextState {
 8277                        query: AhoCorasick::new(&[query])?,
 8278                        wordwise: true,
 8279                        done: is_empty,
 8280                    };
 8281                    self.select_next_state = Some(select_state);
 8282                } else {
 8283                    self.select_next_state = None;
 8284                }
 8285            } else if let Some(selected_text) = selected_text {
 8286                self.select_next_state = Some(SelectNextState {
 8287                    query: AhoCorasick::new(&[selected_text])?,
 8288                    wordwise: false,
 8289                    done: false,
 8290                });
 8291                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8292            }
 8293        }
 8294        Ok(())
 8295    }
 8296
 8297    pub fn select_all_matches(
 8298        &mut self,
 8299        _action: &SelectAllMatches,
 8300        cx: &mut ViewContext<Self>,
 8301    ) -> Result<()> {
 8302        self.push_to_selection_history();
 8303        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8304
 8305        self.select_next_match_internal(&display_map, false, None, cx)?;
 8306        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8307            return Ok(());
 8308        };
 8309        if select_next_state.done {
 8310            return Ok(());
 8311        }
 8312
 8313        let mut new_selections = self.selections.all::<usize>(cx);
 8314
 8315        let buffer = &display_map.buffer_snapshot;
 8316        let query_matches = select_next_state
 8317            .query
 8318            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8319
 8320        for query_match in query_matches {
 8321            let query_match = query_match.unwrap(); // can only fail due to I/O
 8322            let offset_range = query_match.start()..query_match.end();
 8323            let display_range = offset_range.start.to_display_point(&display_map)
 8324                ..offset_range.end.to_display_point(&display_map);
 8325
 8326            if !select_next_state.wordwise
 8327                || (!movement::is_inside_word(&display_map, display_range.start)
 8328                    && !movement::is_inside_word(&display_map, display_range.end))
 8329            {
 8330                self.selections.change_with(cx, |selections| {
 8331                    new_selections.push(Selection {
 8332                        id: selections.new_selection_id(),
 8333                        start: offset_range.start,
 8334                        end: offset_range.end,
 8335                        reversed: false,
 8336                        goal: SelectionGoal::None,
 8337                    });
 8338                });
 8339            }
 8340        }
 8341
 8342        new_selections.sort_by_key(|selection| selection.start);
 8343        let mut ix = 0;
 8344        while ix + 1 < new_selections.len() {
 8345            let current_selection = &new_selections[ix];
 8346            let next_selection = &new_selections[ix + 1];
 8347            if current_selection.range().overlaps(&next_selection.range()) {
 8348                if current_selection.id < next_selection.id {
 8349                    new_selections.remove(ix + 1);
 8350                } else {
 8351                    new_selections.remove(ix);
 8352                }
 8353            } else {
 8354                ix += 1;
 8355            }
 8356        }
 8357
 8358        select_next_state.done = true;
 8359        self.unfold_ranges(
 8360            &new_selections
 8361                .iter()
 8362                .map(|selection| selection.range())
 8363                .collect::<Vec<_>>(),
 8364            false,
 8365            false,
 8366            cx,
 8367        );
 8368        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8369            selections.select(new_selections)
 8370        });
 8371
 8372        Ok(())
 8373    }
 8374
 8375    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8376        self.push_to_selection_history();
 8377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8378        self.select_next_match_internal(
 8379            &display_map,
 8380            action.replace_newest,
 8381            Some(Autoscroll::newest()),
 8382            cx,
 8383        )?;
 8384        Ok(())
 8385    }
 8386
 8387    pub fn select_previous(
 8388        &mut self,
 8389        action: &SelectPrevious,
 8390        cx: &mut ViewContext<Self>,
 8391    ) -> Result<()> {
 8392        self.push_to_selection_history();
 8393        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8394        let buffer = &display_map.buffer_snapshot;
 8395        let mut selections = self.selections.all::<usize>(cx);
 8396        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8397            let query = &select_prev_state.query;
 8398            if !select_prev_state.done {
 8399                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8400                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8401                let mut next_selected_range = None;
 8402                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8403                let bytes_before_last_selection =
 8404                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8405                let bytes_after_first_selection =
 8406                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8407                let query_matches = query
 8408                    .stream_find_iter(bytes_before_last_selection)
 8409                    .map(|result| (last_selection.start, result))
 8410                    .chain(
 8411                        query
 8412                            .stream_find_iter(bytes_after_first_selection)
 8413                            .map(|result| (buffer.len(), result)),
 8414                    );
 8415                for (end_offset, query_match) in query_matches {
 8416                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8417                    let offset_range =
 8418                        end_offset - query_match.end()..end_offset - query_match.start();
 8419                    let display_range = offset_range.start.to_display_point(&display_map)
 8420                        ..offset_range.end.to_display_point(&display_map);
 8421
 8422                    if !select_prev_state.wordwise
 8423                        || (!movement::is_inside_word(&display_map, display_range.start)
 8424                            && !movement::is_inside_word(&display_map, display_range.end))
 8425                    {
 8426                        next_selected_range = Some(offset_range);
 8427                        break;
 8428                    }
 8429                }
 8430
 8431                if let Some(next_selected_range) = next_selected_range {
 8432                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8433                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8434                        if action.replace_newest {
 8435                            s.delete(s.newest_anchor().id);
 8436                        }
 8437                        s.insert_range(next_selected_range);
 8438                    });
 8439                } else {
 8440                    select_prev_state.done = true;
 8441                }
 8442            }
 8443
 8444            self.select_prev_state = Some(select_prev_state);
 8445        } else {
 8446            let mut only_carets = true;
 8447            let mut same_text_selected = true;
 8448            let mut selected_text = None;
 8449
 8450            let mut selections_iter = selections.iter().peekable();
 8451            while let Some(selection) = selections_iter.next() {
 8452                if selection.start != selection.end {
 8453                    only_carets = false;
 8454                }
 8455
 8456                if same_text_selected {
 8457                    if selected_text.is_none() {
 8458                        selected_text =
 8459                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8460                    }
 8461
 8462                    if let Some(next_selection) = selections_iter.peek() {
 8463                        if next_selection.range().len() == selection.range().len() {
 8464                            let next_selected_text = buffer
 8465                                .text_for_range(next_selection.range())
 8466                                .collect::<String>();
 8467                            if Some(next_selected_text) != selected_text {
 8468                                same_text_selected = false;
 8469                                selected_text = None;
 8470                            }
 8471                        } else {
 8472                            same_text_selected = false;
 8473                            selected_text = None;
 8474                        }
 8475                    }
 8476                }
 8477            }
 8478
 8479            if only_carets {
 8480                for selection in &mut selections {
 8481                    let word_range = movement::surrounding_word(
 8482                        &display_map,
 8483                        selection.start.to_display_point(&display_map),
 8484                    );
 8485                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8486                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8487                    selection.goal = SelectionGoal::None;
 8488                    selection.reversed = false;
 8489                }
 8490                if selections.len() == 1 {
 8491                    let selection = selections
 8492                        .last()
 8493                        .expect("ensured that there's only one selection");
 8494                    let query = buffer
 8495                        .text_for_range(selection.start..selection.end)
 8496                        .collect::<String>();
 8497                    let is_empty = query.is_empty();
 8498                    let select_state = SelectNextState {
 8499                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8500                        wordwise: true,
 8501                        done: is_empty,
 8502                    };
 8503                    self.select_prev_state = Some(select_state);
 8504                } else {
 8505                    self.select_prev_state = None;
 8506                }
 8507
 8508                self.unfold_ranges(
 8509                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8510                    false,
 8511                    true,
 8512                    cx,
 8513                );
 8514                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8515                    s.select(selections);
 8516                });
 8517            } else if let Some(selected_text) = selected_text {
 8518                self.select_prev_state = Some(SelectNextState {
 8519                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8520                    wordwise: false,
 8521                    done: false,
 8522                });
 8523                self.select_previous(action, cx)?;
 8524            }
 8525        }
 8526        Ok(())
 8527    }
 8528
 8529    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8530        if self.read_only(cx) {
 8531            return;
 8532        }
 8533        let text_layout_details = &self.text_layout_details(cx);
 8534        self.transact(cx, |this, cx| {
 8535            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8536            let mut edits = Vec::new();
 8537            let mut selection_edit_ranges = Vec::new();
 8538            let mut last_toggled_row = None;
 8539            let snapshot = this.buffer.read(cx).read(cx);
 8540            let empty_str: Arc<str> = Arc::default();
 8541            let mut suffixes_inserted = Vec::new();
 8542            let ignore_indent = action.ignore_indent;
 8543
 8544            fn comment_prefix_range(
 8545                snapshot: &MultiBufferSnapshot,
 8546                row: MultiBufferRow,
 8547                comment_prefix: &str,
 8548                comment_prefix_whitespace: &str,
 8549                ignore_indent: bool,
 8550            ) -> Range<Point> {
 8551                let indent_size = if ignore_indent {
 8552                    0
 8553                } else {
 8554                    snapshot.indent_size_for_line(row).len
 8555                };
 8556
 8557                let start = Point::new(row.0, indent_size);
 8558
 8559                let mut line_bytes = snapshot
 8560                    .bytes_in_range(start..snapshot.max_point())
 8561                    .flatten()
 8562                    .copied();
 8563
 8564                // If this line currently begins with the line comment prefix, then record
 8565                // the range containing the prefix.
 8566                if line_bytes
 8567                    .by_ref()
 8568                    .take(comment_prefix.len())
 8569                    .eq(comment_prefix.bytes())
 8570                {
 8571                    // Include any whitespace that matches the comment prefix.
 8572                    let matching_whitespace_len = line_bytes
 8573                        .zip(comment_prefix_whitespace.bytes())
 8574                        .take_while(|(a, b)| a == b)
 8575                        .count() as u32;
 8576                    let end = Point::new(
 8577                        start.row,
 8578                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8579                    );
 8580                    start..end
 8581                } else {
 8582                    start..start
 8583                }
 8584            }
 8585
 8586            fn comment_suffix_range(
 8587                snapshot: &MultiBufferSnapshot,
 8588                row: MultiBufferRow,
 8589                comment_suffix: &str,
 8590                comment_suffix_has_leading_space: bool,
 8591            ) -> Range<Point> {
 8592                let end = Point::new(row.0, snapshot.line_len(row));
 8593                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8594
 8595                let mut line_end_bytes = snapshot
 8596                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8597                    .flatten()
 8598                    .copied();
 8599
 8600                let leading_space_len = if suffix_start_column > 0
 8601                    && line_end_bytes.next() == Some(b' ')
 8602                    && comment_suffix_has_leading_space
 8603                {
 8604                    1
 8605                } else {
 8606                    0
 8607                };
 8608
 8609                // If this line currently begins with the line comment prefix, then record
 8610                // the range containing the prefix.
 8611                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8612                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8613                    start..end
 8614                } else {
 8615                    end..end
 8616                }
 8617            }
 8618
 8619            // TODO: Handle selections that cross excerpts
 8620            for selection in &mut selections {
 8621                let start_column = snapshot
 8622                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8623                    .len;
 8624                let language = if let Some(language) =
 8625                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8626                {
 8627                    language
 8628                } else {
 8629                    continue;
 8630                };
 8631
 8632                selection_edit_ranges.clear();
 8633
 8634                // If multiple selections contain a given row, avoid processing that
 8635                // row more than once.
 8636                let mut start_row = MultiBufferRow(selection.start.row);
 8637                if last_toggled_row == Some(start_row) {
 8638                    start_row = start_row.next_row();
 8639                }
 8640                let end_row =
 8641                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8642                        MultiBufferRow(selection.end.row - 1)
 8643                    } else {
 8644                        MultiBufferRow(selection.end.row)
 8645                    };
 8646                last_toggled_row = Some(end_row);
 8647
 8648                if start_row > end_row {
 8649                    continue;
 8650                }
 8651
 8652                // If the language has line comments, toggle those.
 8653                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8654
 8655                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8656                if ignore_indent {
 8657                    full_comment_prefixes = full_comment_prefixes
 8658                        .into_iter()
 8659                        .map(|s| Arc::from(s.trim_end()))
 8660                        .collect();
 8661                }
 8662
 8663                if !full_comment_prefixes.is_empty() {
 8664                    let first_prefix = full_comment_prefixes
 8665                        .first()
 8666                        .expect("prefixes is non-empty");
 8667                    let prefix_trimmed_lengths = full_comment_prefixes
 8668                        .iter()
 8669                        .map(|p| p.trim_end_matches(' ').len())
 8670                        .collect::<SmallVec<[usize; 4]>>();
 8671
 8672                    let mut all_selection_lines_are_comments = true;
 8673
 8674                    for row in start_row.0..=end_row.0 {
 8675                        let row = MultiBufferRow(row);
 8676                        if start_row < end_row && snapshot.is_line_blank(row) {
 8677                            continue;
 8678                        }
 8679
 8680                        let prefix_range = full_comment_prefixes
 8681                            .iter()
 8682                            .zip(prefix_trimmed_lengths.iter().copied())
 8683                            .map(|(prefix, trimmed_prefix_len)| {
 8684                                comment_prefix_range(
 8685                                    snapshot.deref(),
 8686                                    row,
 8687                                    &prefix[..trimmed_prefix_len],
 8688                                    &prefix[trimmed_prefix_len..],
 8689                                    ignore_indent,
 8690                                )
 8691                            })
 8692                            .max_by_key(|range| range.end.column - range.start.column)
 8693                            .expect("prefixes is non-empty");
 8694
 8695                        if prefix_range.is_empty() {
 8696                            all_selection_lines_are_comments = false;
 8697                        }
 8698
 8699                        selection_edit_ranges.push(prefix_range);
 8700                    }
 8701
 8702                    if all_selection_lines_are_comments {
 8703                        edits.extend(
 8704                            selection_edit_ranges
 8705                                .iter()
 8706                                .cloned()
 8707                                .map(|range| (range, empty_str.clone())),
 8708                        );
 8709                    } else {
 8710                        let min_column = selection_edit_ranges
 8711                            .iter()
 8712                            .map(|range| range.start.column)
 8713                            .min()
 8714                            .unwrap_or(0);
 8715                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8716                            let position = Point::new(range.start.row, min_column);
 8717                            (position..position, first_prefix.clone())
 8718                        }));
 8719                    }
 8720                } else if let Some((full_comment_prefix, comment_suffix)) =
 8721                    language.block_comment_delimiters()
 8722                {
 8723                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8724                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8725                    let prefix_range = comment_prefix_range(
 8726                        snapshot.deref(),
 8727                        start_row,
 8728                        comment_prefix,
 8729                        comment_prefix_whitespace,
 8730                        ignore_indent,
 8731                    );
 8732                    let suffix_range = comment_suffix_range(
 8733                        snapshot.deref(),
 8734                        end_row,
 8735                        comment_suffix.trim_start_matches(' '),
 8736                        comment_suffix.starts_with(' '),
 8737                    );
 8738
 8739                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8740                        edits.push((
 8741                            prefix_range.start..prefix_range.start,
 8742                            full_comment_prefix.clone(),
 8743                        ));
 8744                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8745                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8746                    } else {
 8747                        edits.push((prefix_range, empty_str.clone()));
 8748                        edits.push((suffix_range, empty_str.clone()));
 8749                    }
 8750                } else {
 8751                    continue;
 8752                }
 8753            }
 8754
 8755            drop(snapshot);
 8756            this.buffer.update(cx, |buffer, cx| {
 8757                buffer.edit(edits, None, cx);
 8758            });
 8759
 8760            // Adjust selections so that they end before any comment suffixes that
 8761            // were inserted.
 8762            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8763            let mut selections = this.selections.all::<Point>(cx);
 8764            let snapshot = this.buffer.read(cx).read(cx);
 8765            for selection in &mut selections {
 8766                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8767                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8768                        Ordering::Less => {
 8769                            suffixes_inserted.next();
 8770                            continue;
 8771                        }
 8772                        Ordering::Greater => break,
 8773                        Ordering::Equal => {
 8774                            if selection.end.column == snapshot.line_len(row) {
 8775                                if selection.is_empty() {
 8776                                    selection.start.column -= suffix_len as u32;
 8777                                }
 8778                                selection.end.column -= suffix_len as u32;
 8779                            }
 8780                            break;
 8781                        }
 8782                    }
 8783                }
 8784            }
 8785
 8786            drop(snapshot);
 8787            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8788
 8789            let selections = this.selections.all::<Point>(cx);
 8790            let selections_on_single_row = selections.windows(2).all(|selections| {
 8791                selections[0].start.row == selections[1].start.row
 8792                    && selections[0].end.row == selections[1].end.row
 8793                    && selections[0].start.row == selections[0].end.row
 8794            });
 8795            let selections_selecting = selections
 8796                .iter()
 8797                .any(|selection| selection.start != selection.end);
 8798            let advance_downwards = action.advance_downwards
 8799                && selections_on_single_row
 8800                && !selections_selecting
 8801                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8802
 8803            if advance_downwards {
 8804                let snapshot = this.buffer.read(cx).snapshot(cx);
 8805
 8806                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8807                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8808                        let mut point = display_point.to_point(display_snapshot);
 8809                        point.row += 1;
 8810                        point = snapshot.clip_point(point, Bias::Left);
 8811                        let display_point = point.to_display_point(display_snapshot);
 8812                        let goal = SelectionGoal::HorizontalPosition(
 8813                            display_snapshot
 8814                                .x_for_display_point(display_point, text_layout_details)
 8815                                .into(),
 8816                        );
 8817                        (display_point, goal)
 8818                    })
 8819                });
 8820            }
 8821        });
 8822    }
 8823
 8824    pub fn select_enclosing_symbol(
 8825        &mut self,
 8826        _: &SelectEnclosingSymbol,
 8827        cx: &mut ViewContext<Self>,
 8828    ) {
 8829        let buffer = self.buffer.read(cx).snapshot(cx);
 8830        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8831
 8832        fn update_selection(
 8833            selection: &Selection<usize>,
 8834            buffer_snap: &MultiBufferSnapshot,
 8835        ) -> Option<Selection<usize>> {
 8836            let cursor = selection.head();
 8837            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8838            for symbol in symbols.iter().rev() {
 8839                let start = symbol.range.start.to_offset(buffer_snap);
 8840                let end = symbol.range.end.to_offset(buffer_snap);
 8841                let new_range = start..end;
 8842                if start < selection.start || end > selection.end {
 8843                    return Some(Selection {
 8844                        id: selection.id,
 8845                        start: new_range.start,
 8846                        end: new_range.end,
 8847                        goal: SelectionGoal::None,
 8848                        reversed: selection.reversed,
 8849                    });
 8850                }
 8851            }
 8852            None
 8853        }
 8854
 8855        let mut selected_larger_symbol = false;
 8856        let new_selections = old_selections
 8857            .iter()
 8858            .map(|selection| match update_selection(selection, &buffer) {
 8859                Some(new_selection) => {
 8860                    if new_selection.range() != selection.range() {
 8861                        selected_larger_symbol = true;
 8862                    }
 8863                    new_selection
 8864                }
 8865                None => selection.clone(),
 8866            })
 8867            .collect::<Vec<_>>();
 8868
 8869        if selected_larger_symbol {
 8870            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8871                s.select(new_selections);
 8872            });
 8873        }
 8874    }
 8875
 8876    pub fn select_larger_syntax_node(
 8877        &mut self,
 8878        _: &SelectLargerSyntaxNode,
 8879        cx: &mut ViewContext<Self>,
 8880    ) {
 8881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8882        let buffer = self.buffer.read(cx).snapshot(cx);
 8883        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8884
 8885        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8886        let mut selected_larger_node = false;
 8887        let new_selections = old_selections
 8888            .iter()
 8889            .map(|selection| {
 8890                let old_range = selection.start..selection.end;
 8891                let mut new_range = old_range.clone();
 8892                let mut new_node = None;
 8893                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8894                {
 8895                    new_node = Some(node);
 8896                    new_range = containing_range;
 8897                    if !display_map.intersects_fold(new_range.start)
 8898                        && !display_map.intersects_fold(new_range.end)
 8899                    {
 8900                        break;
 8901                    }
 8902                }
 8903
 8904                if let Some(node) = new_node {
 8905                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8906                    // nodes. Parent and grandparent are also logged because this operation will not
 8907                    // visit nodes that have the same range as their parent.
 8908                    log::info!("Node: {node:?}");
 8909                    let parent = node.parent();
 8910                    log::info!("Parent: {parent:?}");
 8911                    let grandparent = parent.and_then(|x| x.parent());
 8912                    log::info!("Grandparent: {grandparent:?}");
 8913                }
 8914
 8915                selected_larger_node |= new_range != old_range;
 8916                Selection {
 8917                    id: selection.id,
 8918                    start: new_range.start,
 8919                    end: new_range.end,
 8920                    goal: SelectionGoal::None,
 8921                    reversed: selection.reversed,
 8922                }
 8923            })
 8924            .collect::<Vec<_>>();
 8925
 8926        if selected_larger_node {
 8927            stack.push(old_selections);
 8928            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8929                s.select(new_selections);
 8930            });
 8931        }
 8932        self.select_larger_syntax_node_stack = stack;
 8933    }
 8934
 8935    pub fn select_smaller_syntax_node(
 8936        &mut self,
 8937        _: &SelectSmallerSyntaxNode,
 8938        cx: &mut ViewContext<Self>,
 8939    ) {
 8940        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8941        if let Some(selections) = stack.pop() {
 8942            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8943                s.select(selections.to_vec());
 8944            });
 8945        }
 8946        self.select_larger_syntax_node_stack = stack;
 8947    }
 8948
 8949    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8950        if !EditorSettings::get_global(cx).gutter.runnables {
 8951            self.clear_tasks();
 8952            return Task::ready(());
 8953        }
 8954        let project = self.project.as_ref().map(Model::downgrade);
 8955        cx.spawn(|this, mut cx| async move {
 8956            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8957            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8958                return;
 8959            };
 8960            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8961                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8962            }) else {
 8963                return;
 8964            };
 8965
 8966            let hide_runnables = project
 8967                .update(&mut cx, |project, cx| {
 8968                    // Do not display any test indicators in non-dev server remote projects.
 8969                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8970                })
 8971                .unwrap_or(true);
 8972            if hide_runnables {
 8973                return;
 8974            }
 8975            let new_rows =
 8976                cx.background_executor()
 8977                    .spawn({
 8978                        let snapshot = display_snapshot.clone();
 8979                        async move {
 8980                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8981                        }
 8982                    })
 8983                    .await;
 8984            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8985
 8986            this.update(&mut cx, |this, _| {
 8987                this.clear_tasks();
 8988                for (key, value) in rows {
 8989                    this.insert_tasks(key, value);
 8990                }
 8991            })
 8992            .ok();
 8993        })
 8994    }
 8995    fn fetch_runnable_ranges(
 8996        snapshot: &DisplaySnapshot,
 8997        range: Range<Anchor>,
 8998    ) -> Vec<language::RunnableRange> {
 8999        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9000    }
 9001
 9002    fn runnable_rows(
 9003        project: Model<Project>,
 9004        snapshot: DisplaySnapshot,
 9005        runnable_ranges: Vec<RunnableRange>,
 9006        mut cx: AsyncWindowContext,
 9007    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9008        runnable_ranges
 9009            .into_iter()
 9010            .filter_map(|mut runnable| {
 9011                let tasks = cx
 9012                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9013                    .ok()?;
 9014                if tasks.is_empty() {
 9015                    return None;
 9016                }
 9017
 9018                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9019
 9020                let row = snapshot
 9021                    .buffer_snapshot
 9022                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9023                    .1
 9024                    .start
 9025                    .row;
 9026
 9027                let context_range =
 9028                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9029                Some((
 9030                    (runnable.buffer_id, row),
 9031                    RunnableTasks {
 9032                        templates: tasks,
 9033                        offset: MultiBufferOffset(runnable.run_range.start),
 9034                        context_range,
 9035                        column: point.column,
 9036                        extra_variables: runnable.extra_captures,
 9037                    },
 9038                ))
 9039            })
 9040            .collect()
 9041    }
 9042
 9043    fn templates_with_tags(
 9044        project: &Model<Project>,
 9045        runnable: &mut Runnable,
 9046        cx: &WindowContext,
 9047    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9048        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9049            let (worktree_id, file) = project
 9050                .buffer_for_id(runnable.buffer, cx)
 9051                .and_then(|buffer| buffer.read(cx).file())
 9052                .map(|file| (file.worktree_id(cx), file.clone()))
 9053                .unzip();
 9054
 9055            (
 9056                project.task_store().read(cx).task_inventory().cloned(),
 9057                worktree_id,
 9058                file,
 9059            )
 9060        });
 9061
 9062        let tags = mem::take(&mut runnable.tags);
 9063        let mut tags: Vec<_> = tags
 9064            .into_iter()
 9065            .flat_map(|tag| {
 9066                let tag = tag.0.clone();
 9067                inventory
 9068                    .as_ref()
 9069                    .into_iter()
 9070                    .flat_map(|inventory| {
 9071                        inventory.read(cx).list_tasks(
 9072                            file.clone(),
 9073                            Some(runnable.language.clone()),
 9074                            worktree_id,
 9075                            cx,
 9076                        )
 9077                    })
 9078                    .filter(move |(_, template)| {
 9079                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9080                    })
 9081            })
 9082            .sorted_by_key(|(kind, _)| kind.to_owned())
 9083            .collect();
 9084        if let Some((leading_tag_source, _)) = tags.first() {
 9085            // Strongest source wins; if we have worktree tag binding, prefer that to
 9086            // global and language bindings;
 9087            // if we have a global binding, prefer that to language binding.
 9088            let first_mismatch = tags
 9089                .iter()
 9090                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9091            if let Some(index) = first_mismatch {
 9092                tags.truncate(index);
 9093            }
 9094        }
 9095
 9096        tags
 9097    }
 9098
 9099    pub fn move_to_enclosing_bracket(
 9100        &mut self,
 9101        _: &MoveToEnclosingBracket,
 9102        cx: &mut ViewContext<Self>,
 9103    ) {
 9104        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9105            s.move_offsets_with(|snapshot, selection| {
 9106                let Some(enclosing_bracket_ranges) =
 9107                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9108                else {
 9109                    return;
 9110                };
 9111
 9112                let mut best_length = usize::MAX;
 9113                let mut best_inside = false;
 9114                let mut best_in_bracket_range = false;
 9115                let mut best_destination = None;
 9116                for (open, close) in enclosing_bracket_ranges {
 9117                    let close = close.to_inclusive();
 9118                    let length = close.end() - open.start;
 9119                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9120                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9121                        || close.contains(&selection.head());
 9122
 9123                    // If best is next to a bracket and current isn't, skip
 9124                    if !in_bracket_range && best_in_bracket_range {
 9125                        continue;
 9126                    }
 9127
 9128                    // Prefer smaller lengths unless best is inside and current isn't
 9129                    if length > best_length && (best_inside || !inside) {
 9130                        continue;
 9131                    }
 9132
 9133                    best_length = length;
 9134                    best_inside = inside;
 9135                    best_in_bracket_range = in_bracket_range;
 9136                    best_destination = Some(
 9137                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9138                            if inside {
 9139                                open.end
 9140                            } else {
 9141                                open.start
 9142                            }
 9143                        } else if inside {
 9144                            *close.start()
 9145                        } else {
 9146                            *close.end()
 9147                        },
 9148                    );
 9149                }
 9150
 9151                if let Some(destination) = best_destination {
 9152                    selection.collapse_to(destination, SelectionGoal::None);
 9153                }
 9154            })
 9155        });
 9156    }
 9157
 9158    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9159        self.end_selection(cx);
 9160        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9161        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9162            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9163            self.select_next_state = entry.select_next_state;
 9164            self.select_prev_state = entry.select_prev_state;
 9165            self.add_selections_state = entry.add_selections_state;
 9166            self.request_autoscroll(Autoscroll::newest(), cx);
 9167        }
 9168        self.selection_history.mode = SelectionHistoryMode::Normal;
 9169    }
 9170
 9171    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9172        self.end_selection(cx);
 9173        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9174        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9175            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9176            self.select_next_state = entry.select_next_state;
 9177            self.select_prev_state = entry.select_prev_state;
 9178            self.add_selections_state = entry.add_selections_state;
 9179            self.request_autoscroll(Autoscroll::newest(), cx);
 9180        }
 9181        self.selection_history.mode = SelectionHistoryMode::Normal;
 9182    }
 9183
 9184    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9185        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9186    }
 9187
 9188    pub fn expand_excerpts_down(
 9189        &mut self,
 9190        action: &ExpandExcerptsDown,
 9191        cx: &mut ViewContext<Self>,
 9192    ) {
 9193        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9194    }
 9195
 9196    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9197        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9198    }
 9199
 9200    pub fn expand_excerpts_for_direction(
 9201        &mut self,
 9202        lines: u32,
 9203        direction: ExpandExcerptDirection,
 9204        cx: &mut ViewContext<Self>,
 9205    ) {
 9206        let selections = self.selections.disjoint_anchors();
 9207
 9208        let lines = if lines == 0 {
 9209            EditorSettings::get_global(cx).expand_excerpt_lines
 9210        } else {
 9211            lines
 9212        };
 9213
 9214        self.buffer.update(cx, |buffer, cx| {
 9215            let snapshot = buffer.snapshot(cx);
 9216            let mut excerpt_ids = selections
 9217                .iter()
 9218                .flat_map(|selection| {
 9219                    snapshot
 9220                        .excerpts_for_range(selection.range())
 9221                        .map(|excerpt| excerpt.id())
 9222                })
 9223                .collect::<Vec<_>>();
 9224            excerpt_ids.sort();
 9225            excerpt_ids.dedup();
 9226            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9227        })
 9228    }
 9229
 9230    pub fn expand_excerpt(
 9231        &mut self,
 9232        excerpt: ExcerptId,
 9233        direction: ExpandExcerptDirection,
 9234        cx: &mut ViewContext<Self>,
 9235    ) {
 9236        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9237        self.buffer.update(cx, |buffer, cx| {
 9238            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9239        })
 9240    }
 9241
 9242    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9243        self.go_to_diagnostic_impl(Direction::Next, cx)
 9244    }
 9245
 9246    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9247        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9248    }
 9249
 9250    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9251        let buffer = self.buffer.read(cx).snapshot(cx);
 9252        let selection = self.selections.newest::<usize>(cx);
 9253
 9254        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9255        if direction == Direction::Next {
 9256            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9257                self.activate_diagnostics(popover.group_id(), cx);
 9258                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9259                    let primary_range_start = active_diagnostics.primary_range.start;
 9260                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9261                        let mut new_selection = s.newest_anchor().clone();
 9262                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9263                        s.select_anchors(vec![new_selection.clone()]);
 9264                    });
 9265                }
 9266                return;
 9267            }
 9268        }
 9269
 9270        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9271            active_diagnostics
 9272                .primary_range
 9273                .to_offset(&buffer)
 9274                .to_inclusive()
 9275        });
 9276        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9277            if active_primary_range.contains(&selection.head()) {
 9278                *active_primary_range.start()
 9279            } else {
 9280                selection.head()
 9281            }
 9282        } else {
 9283            selection.head()
 9284        };
 9285        let snapshot = self.snapshot(cx);
 9286        loop {
 9287            let diagnostics = if direction == Direction::Prev {
 9288                buffer.diagnostics_in_range(0..search_start, true)
 9289            } else {
 9290                buffer.diagnostics_in_range(search_start..buffer.len(), false)
 9291            }
 9292            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9293            let search_start_anchor = buffer.anchor_after(search_start);
 9294            let group = diagnostics
 9295                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9296                // be sorted in a stable way
 9297                // skip until we are at current active diagnostic, if it exists
 9298                .skip_while(|entry| {
 9299                    let is_in_range = match direction {
 9300                        Direction::Prev => {
 9301                            entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
 9302                        }
 9303                        Direction::Next => {
 9304                            entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
 9305                        }
 9306                    };
 9307                    is_in_range
 9308                        && self
 9309                            .active_diagnostics
 9310                            .as_ref()
 9311                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9312                })
 9313                .find_map(|entry| {
 9314                    if entry.diagnostic.is_primary
 9315                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9316                        && !(entry.range.start == entry.range.end)
 9317                        // if we match with the active diagnostic, skip it
 9318                        && Some(entry.diagnostic.group_id)
 9319                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9320                    {
 9321                        Some((entry.range, entry.diagnostic.group_id))
 9322                    } else {
 9323                        None
 9324                    }
 9325                });
 9326
 9327            if let Some((primary_range, group_id)) = group {
 9328                self.activate_diagnostics(group_id, cx);
 9329                let primary_range = primary_range.to_offset(&buffer);
 9330                if self.active_diagnostics.is_some() {
 9331                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9332                        s.select(vec![Selection {
 9333                            id: selection.id,
 9334                            start: primary_range.start,
 9335                            end: primary_range.start,
 9336                            reversed: false,
 9337                            goal: SelectionGoal::None,
 9338                        }]);
 9339                    });
 9340                }
 9341                break;
 9342            } else {
 9343                // Cycle around to the start of the buffer, potentially moving back to the start of
 9344                // the currently active diagnostic.
 9345                active_primary_range.take();
 9346                if direction == Direction::Prev {
 9347                    if search_start == buffer.len() {
 9348                        break;
 9349                    } else {
 9350                        search_start = buffer.len();
 9351                    }
 9352                } else if search_start == 0 {
 9353                    break;
 9354                } else {
 9355                    search_start = 0;
 9356                }
 9357            }
 9358        }
 9359    }
 9360
 9361    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9362        let snapshot = self.snapshot(cx);
 9363        let selection = self.selections.newest::<Point>(cx);
 9364        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9365    }
 9366
 9367    fn go_to_hunk_after_position(
 9368        &mut self,
 9369        snapshot: &EditorSnapshot,
 9370        position: Point,
 9371        cx: &mut ViewContext<Editor>,
 9372    ) -> Option<MultiBufferDiffHunk> {
 9373        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9374            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9375                snapshot,
 9376                position,
 9377                ix > 0,
 9378                snapshot.diff_map.diff_hunks_in_range(
 9379                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9380                    &snapshot.buffer_snapshot,
 9381                ),
 9382                cx,
 9383            ) {
 9384                return Some(hunk);
 9385            }
 9386        }
 9387        None
 9388    }
 9389
 9390    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9391        let snapshot = self.snapshot(cx);
 9392        let selection = self.selections.newest::<Point>(cx);
 9393        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9394    }
 9395
 9396    fn go_to_hunk_before_position(
 9397        &mut self,
 9398        snapshot: &EditorSnapshot,
 9399        position: Point,
 9400        cx: &mut ViewContext<Editor>,
 9401    ) -> Option<MultiBufferDiffHunk> {
 9402        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9403            .into_iter()
 9404            .enumerate()
 9405        {
 9406            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9407                snapshot,
 9408                position,
 9409                ix > 0,
 9410                snapshot
 9411                    .diff_map
 9412                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9413                cx,
 9414            ) {
 9415                return Some(hunk);
 9416            }
 9417        }
 9418        None
 9419    }
 9420
 9421    fn go_to_next_hunk_in_direction(
 9422        &mut self,
 9423        snapshot: &DisplaySnapshot,
 9424        initial_point: Point,
 9425        is_wrapped: bool,
 9426        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9427        cx: &mut ViewContext<Editor>,
 9428    ) -> Option<MultiBufferDiffHunk> {
 9429        let display_point = initial_point.to_display_point(snapshot);
 9430        let mut hunks = hunks
 9431            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9432            .filter(|(display_hunk, _)| {
 9433                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9434            })
 9435            .dedup();
 9436
 9437        if let Some((display_hunk, hunk)) = hunks.next() {
 9438            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9439                let row = display_hunk.start_display_row();
 9440                let point = DisplayPoint::new(row, 0);
 9441                s.select_display_ranges([point..point]);
 9442            });
 9443
 9444            Some(hunk)
 9445        } else {
 9446            None
 9447        }
 9448    }
 9449
 9450    pub fn go_to_definition(
 9451        &mut self,
 9452        _: &GoToDefinition,
 9453        cx: &mut ViewContext<Self>,
 9454    ) -> Task<Result<Navigated>> {
 9455        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9456        cx.spawn(|editor, mut cx| async move {
 9457            if definition.await? == Navigated::Yes {
 9458                return Ok(Navigated::Yes);
 9459            }
 9460            match editor.update(&mut cx, |editor, cx| {
 9461                editor.find_all_references(&FindAllReferences, cx)
 9462            })? {
 9463                Some(references) => references.await,
 9464                None => Ok(Navigated::No),
 9465            }
 9466        })
 9467    }
 9468
 9469    pub fn go_to_declaration(
 9470        &mut self,
 9471        _: &GoToDeclaration,
 9472        cx: &mut ViewContext<Self>,
 9473    ) -> Task<Result<Navigated>> {
 9474        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9475    }
 9476
 9477    pub fn go_to_declaration_split(
 9478        &mut self,
 9479        _: &GoToDeclaration,
 9480        cx: &mut ViewContext<Self>,
 9481    ) -> Task<Result<Navigated>> {
 9482        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9483    }
 9484
 9485    pub fn go_to_implementation(
 9486        &mut self,
 9487        _: &GoToImplementation,
 9488        cx: &mut ViewContext<Self>,
 9489    ) -> Task<Result<Navigated>> {
 9490        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9491    }
 9492
 9493    pub fn go_to_implementation_split(
 9494        &mut self,
 9495        _: &GoToImplementationSplit,
 9496        cx: &mut ViewContext<Self>,
 9497    ) -> Task<Result<Navigated>> {
 9498        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9499    }
 9500
 9501    pub fn go_to_type_definition(
 9502        &mut self,
 9503        _: &GoToTypeDefinition,
 9504        cx: &mut ViewContext<Self>,
 9505    ) -> Task<Result<Navigated>> {
 9506        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9507    }
 9508
 9509    pub fn go_to_definition_split(
 9510        &mut self,
 9511        _: &GoToDefinitionSplit,
 9512        cx: &mut ViewContext<Self>,
 9513    ) -> Task<Result<Navigated>> {
 9514        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9515    }
 9516
 9517    pub fn go_to_type_definition_split(
 9518        &mut self,
 9519        _: &GoToTypeDefinitionSplit,
 9520        cx: &mut ViewContext<Self>,
 9521    ) -> Task<Result<Navigated>> {
 9522        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9523    }
 9524
 9525    fn go_to_definition_of_kind(
 9526        &mut self,
 9527        kind: GotoDefinitionKind,
 9528        split: bool,
 9529        cx: &mut ViewContext<Self>,
 9530    ) -> Task<Result<Navigated>> {
 9531        let Some(provider) = self.semantics_provider.clone() else {
 9532            return Task::ready(Ok(Navigated::No));
 9533        };
 9534        let head = self.selections.newest::<usize>(cx).head();
 9535        let buffer = self.buffer.read(cx);
 9536        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9537            text_anchor
 9538        } else {
 9539            return Task::ready(Ok(Navigated::No));
 9540        };
 9541
 9542        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9543            return Task::ready(Ok(Navigated::No));
 9544        };
 9545
 9546        cx.spawn(|editor, mut cx| async move {
 9547            let definitions = definitions.await?;
 9548            let navigated = editor
 9549                .update(&mut cx, |editor, cx| {
 9550                    editor.navigate_to_hover_links(
 9551                        Some(kind),
 9552                        definitions
 9553                            .into_iter()
 9554                            .filter(|location| {
 9555                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9556                            })
 9557                            .map(HoverLink::Text)
 9558                            .collect::<Vec<_>>(),
 9559                        split,
 9560                        cx,
 9561                    )
 9562                })?
 9563                .await?;
 9564            anyhow::Ok(navigated)
 9565        })
 9566    }
 9567
 9568    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9569        let selection = self.selections.newest_anchor();
 9570        let head = selection.head();
 9571        let tail = selection.tail();
 9572
 9573        let Some((buffer, start_position)) =
 9574            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9575        else {
 9576            return;
 9577        };
 9578
 9579        let end_position = if head != tail {
 9580            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9581                return;
 9582            };
 9583            Some(pos)
 9584        } else {
 9585            None
 9586        };
 9587
 9588        let url_finder = cx.spawn(|editor, mut cx| async move {
 9589            let url = if let Some(end_pos) = end_position {
 9590                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9591            } else {
 9592                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9593            };
 9594
 9595            if let Some(url) = url {
 9596                editor.update(&mut cx, |_, cx| {
 9597                    cx.open_url(&url);
 9598                })
 9599            } else {
 9600                Ok(())
 9601            }
 9602        });
 9603
 9604        url_finder.detach();
 9605    }
 9606
 9607    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9608        let Some(workspace) = self.workspace() else {
 9609            return;
 9610        };
 9611
 9612        let position = self.selections.newest_anchor().head();
 9613
 9614        let Some((buffer, buffer_position)) =
 9615            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9616        else {
 9617            return;
 9618        };
 9619
 9620        let project = self.project.clone();
 9621
 9622        cx.spawn(|_, mut cx| async move {
 9623            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9624
 9625            if let Some((_, path)) = result {
 9626                workspace
 9627                    .update(&mut cx, |workspace, cx| {
 9628                        workspace.open_resolved_path(path, cx)
 9629                    })?
 9630                    .await?;
 9631            }
 9632            anyhow::Ok(())
 9633        })
 9634        .detach();
 9635    }
 9636
 9637    pub(crate) fn navigate_to_hover_links(
 9638        &mut self,
 9639        kind: Option<GotoDefinitionKind>,
 9640        mut definitions: Vec<HoverLink>,
 9641        split: bool,
 9642        cx: &mut ViewContext<Editor>,
 9643    ) -> Task<Result<Navigated>> {
 9644        // If there is one definition, just open it directly
 9645        if definitions.len() == 1 {
 9646            let definition = definitions.pop().unwrap();
 9647
 9648            enum TargetTaskResult {
 9649                Location(Option<Location>),
 9650                AlreadyNavigated,
 9651            }
 9652
 9653            let target_task = match definition {
 9654                HoverLink::Text(link) => {
 9655                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9656                }
 9657                HoverLink::InlayHint(lsp_location, server_id) => {
 9658                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9659                    cx.background_executor().spawn(async move {
 9660                        let location = computation.await?;
 9661                        Ok(TargetTaskResult::Location(location))
 9662                    })
 9663                }
 9664                HoverLink::Url(url) => {
 9665                    cx.open_url(&url);
 9666                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9667                }
 9668                HoverLink::File(path) => {
 9669                    if let Some(workspace) = self.workspace() {
 9670                        cx.spawn(|_, mut cx| async move {
 9671                            workspace
 9672                                .update(&mut cx, |workspace, cx| {
 9673                                    workspace.open_resolved_path(path, cx)
 9674                                })?
 9675                                .await
 9676                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9677                        })
 9678                    } else {
 9679                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9680                    }
 9681                }
 9682            };
 9683            cx.spawn(|editor, mut cx| async move {
 9684                let target = match target_task.await.context("target resolution task")? {
 9685                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9686                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9687                    TargetTaskResult::Location(Some(target)) => target,
 9688                };
 9689
 9690                editor.update(&mut cx, |editor, cx| {
 9691                    let Some(workspace) = editor.workspace() else {
 9692                        return Navigated::No;
 9693                    };
 9694                    let pane = workspace.read(cx).active_pane().clone();
 9695
 9696                    let range = target.range.to_offset(target.buffer.read(cx));
 9697                    let range = editor.range_for_match(&range);
 9698
 9699                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9700                        let buffer = target.buffer.read(cx);
 9701                        let range = check_multiline_range(buffer, range);
 9702                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9703                            s.select_ranges([range]);
 9704                        });
 9705                    } else {
 9706                        cx.window_context().defer(move |cx| {
 9707                            let target_editor: View<Self> =
 9708                                workspace.update(cx, |workspace, cx| {
 9709                                    let pane = if split {
 9710                                        workspace.adjacent_pane(cx)
 9711                                    } else {
 9712                                        workspace.active_pane().clone()
 9713                                    };
 9714
 9715                                    workspace.open_project_item(
 9716                                        pane,
 9717                                        target.buffer.clone(),
 9718                                        true,
 9719                                        true,
 9720                                        cx,
 9721                                    )
 9722                                });
 9723                            target_editor.update(cx, |target_editor, cx| {
 9724                                // When selecting a definition in a different buffer, disable the nav history
 9725                                // to avoid creating a history entry at the previous cursor location.
 9726                                pane.update(cx, |pane, _| pane.disable_history());
 9727                                let buffer = target.buffer.read(cx);
 9728                                let range = check_multiline_range(buffer, range);
 9729                                target_editor.change_selections(
 9730                                    Some(Autoscroll::focused()),
 9731                                    cx,
 9732                                    |s| {
 9733                                        s.select_ranges([range]);
 9734                                    },
 9735                                );
 9736                                pane.update(cx, |pane, _| pane.enable_history());
 9737                            });
 9738                        });
 9739                    }
 9740                    Navigated::Yes
 9741                })
 9742            })
 9743        } else if !definitions.is_empty() {
 9744            cx.spawn(|editor, mut cx| async move {
 9745                let (title, location_tasks, workspace) = editor
 9746                    .update(&mut cx, |editor, cx| {
 9747                        let tab_kind = match kind {
 9748                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9749                            _ => "Definitions",
 9750                        };
 9751                        let title = definitions
 9752                            .iter()
 9753                            .find_map(|definition| match definition {
 9754                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9755                                    let buffer = origin.buffer.read(cx);
 9756                                    format!(
 9757                                        "{} for {}",
 9758                                        tab_kind,
 9759                                        buffer
 9760                                            .text_for_range(origin.range.clone())
 9761                                            .collect::<String>()
 9762                                    )
 9763                                }),
 9764                                HoverLink::InlayHint(_, _) => None,
 9765                                HoverLink::Url(_) => None,
 9766                                HoverLink::File(_) => None,
 9767                            })
 9768                            .unwrap_or(tab_kind.to_string());
 9769                        let location_tasks = definitions
 9770                            .into_iter()
 9771                            .map(|definition| match definition {
 9772                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9773                                HoverLink::InlayHint(lsp_location, server_id) => {
 9774                                    editor.compute_target_location(lsp_location, server_id, cx)
 9775                                }
 9776                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9777                                HoverLink::File(_) => Task::ready(Ok(None)),
 9778                            })
 9779                            .collect::<Vec<_>>();
 9780                        (title, location_tasks, editor.workspace().clone())
 9781                    })
 9782                    .context("location tasks preparation")?;
 9783
 9784                let locations = future::join_all(location_tasks)
 9785                    .await
 9786                    .into_iter()
 9787                    .filter_map(|location| location.transpose())
 9788                    .collect::<Result<_>>()
 9789                    .context("location tasks")?;
 9790
 9791                let Some(workspace) = workspace else {
 9792                    return Ok(Navigated::No);
 9793                };
 9794                let opened = workspace
 9795                    .update(&mut cx, |workspace, cx| {
 9796                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9797                    })
 9798                    .ok();
 9799
 9800                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9801            })
 9802        } else {
 9803            Task::ready(Ok(Navigated::No))
 9804        }
 9805    }
 9806
 9807    fn compute_target_location(
 9808        &self,
 9809        lsp_location: lsp::Location,
 9810        server_id: LanguageServerId,
 9811        cx: &mut ViewContext<Self>,
 9812    ) -> Task<anyhow::Result<Option<Location>>> {
 9813        let Some(project) = self.project.clone() else {
 9814            return Task::ready(Ok(None));
 9815        };
 9816
 9817        cx.spawn(move |editor, mut cx| async move {
 9818            let location_task = editor.update(&mut cx, |_, cx| {
 9819                project.update(cx, |project, cx| {
 9820                    let language_server_name = project
 9821                        .language_server_statuses(cx)
 9822                        .find(|(id, _)| server_id == *id)
 9823                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9824                    language_server_name.map(|language_server_name| {
 9825                        project.open_local_buffer_via_lsp(
 9826                            lsp_location.uri.clone(),
 9827                            server_id,
 9828                            language_server_name,
 9829                            cx,
 9830                        )
 9831                    })
 9832                })
 9833            })?;
 9834            let location = match location_task {
 9835                Some(task) => Some({
 9836                    let target_buffer_handle = task.await.context("open local buffer")?;
 9837                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9838                        let target_start = target_buffer
 9839                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9840                        let target_end = target_buffer
 9841                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9842                        target_buffer.anchor_after(target_start)
 9843                            ..target_buffer.anchor_before(target_end)
 9844                    })?;
 9845                    Location {
 9846                        buffer: target_buffer_handle,
 9847                        range,
 9848                    }
 9849                }),
 9850                None => None,
 9851            };
 9852            Ok(location)
 9853        })
 9854    }
 9855
 9856    pub fn find_all_references(
 9857        &mut self,
 9858        _: &FindAllReferences,
 9859        cx: &mut ViewContext<Self>,
 9860    ) -> Option<Task<Result<Navigated>>> {
 9861        let selection = self.selections.newest::<usize>(cx);
 9862        let multi_buffer = self.buffer.read(cx);
 9863        let head = selection.head();
 9864
 9865        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9866        let head_anchor = multi_buffer_snapshot.anchor_at(
 9867            head,
 9868            if head < selection.tail() {
 9869                Bias::Right
 9870            } else {
 9871                Bias::Left
 9872            },
 9873        );
 9874
 9875        match self
 9876            .find_all_references_task_sources
 9877            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9878        {
 9879            Ok(_) => {
 9880                log::info!(
 9881                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9882                );
 9883                return None;
 9884            }
 9885            Err(i) => {
 9886                self.find_all_references_task_sources.insert(i, head_anchor);
 9887            }
 9888        }
 9889
 9890        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9891        let workspace = self.workspace()?;
 9892        let project = workspace.read(cx).project().clone();
 9893        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9894        Some(cx.spawn(|editor, mut cx| async move {
 9895            let _cleanup = defer({
 9896                let mut cx = cx.clone();
 9897                move || {
 9898                    let _ = editor.update(&mut cx, |editor, _| {
 9899                        if let Ok(i) =
 9900                            editor
 9901                                .find_all_references_task_sources
 9902                                .binary_search_by(|anchor| {
 9903                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9904                                })
 9905                        {
 9906                            editor.find_all_references_task_sources.remove(i);
 9907                        }
 9908                    });
 9909                }
 9910            });
 9911
 9912            let locations = references.await?;
 9913            if locations.is_empty() {
 9914                return anyhow::Ok(Navigated::No);
 9915            }
 9916
 9917            workspace.update(&mut cx, |workspace, cx| {
 9918                let title = locations
 9919                    .first()
 9920                    .as_ref()
 9921                    .map(|location| {
 9922                        let buffer = location.buffer.read(cx);
 9923                        format!(
 9924                            "References to `{}`",
 9925                            buffer
 9926                                .text_for_range(location.range.clone())
 9927                                .collect::<String>()
 9928                        )
 9929                    })
 9930                    .unwrap();
 9931                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9932                Navigated::Yes
 9933            })
 9934        }))
 9935    }
 9936
 9937    /// Opens a multibuffer with the given project locations in it
 9938    pub fn open_locations_in_multibuffer(
 9939        workspace: &mut Workspace,
 9940        mut locations: Vec<Location>,
 9941        title: String,
 9942        split: bool,
 9943        cx: &mut ViewContext<Workspace>,
 9944    ) {
 9945        // If there are multiple definitions, open them in a multibuffer
 9946        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9947        let mut locations = locations.into_iter().peekable();
 9948        let mut ranges_to_highlight = Vec::new();
 9949        let capability = workspace.project().read(cx).capability();
 9950
 9951        let excerpt_buffer = cx.new_model(|cx| {
 9952            let mut multibuffer = MultiBuffer::new(capability);
 9953            while let Some(location) = locations.next() {
 9954                let buffer = location.buffer.read(cx);
 9955                let mut ranges_for_buffer = Vec::new();
 9956                let range = location.range.to_offset(buffer);
 9957                ranges_for_buffer.push(range.clone());
 9958
 9959                while let Some(next_location) = locations.peek() {
 9960                    if next_location.buffer == location.buffer {
 9961                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9962                        locations.next();
 9963                    } else {
 9964                        break;
 9965                    }
 9966                }
 9967
 9968                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9969                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9970                    location.buffer.clone(),
 9971                    ranges_for_buffer,
 9972                    DEFAULT_MULTIBUFFER_CONTEXT,
 9973                    cx,
 9974                ))
 9975            }
 9976
 9977            multibuffer.with_title(title)
 9978        });
 9979
 9980        let editor = cx.new_view(|cx| {
 9981            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9982        });
 9983        editor.update(cx, |editor, cx| {
 9984            if let Some(first_range) = ranges_to_highlight.first() {
 9985                editor.change_selections(None, cx, |selections| {
 9986                    selections.clear_disjoint();
 9987                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9988                });
 9989            }
 9990            editor.highlight_background::<Self>(
 9991                &ranges_to_highlight,
 9992                |theme| theme.editor_highlighted_line_background,
 9993                cx,
 9994            );
 9995            editor.register_buffers_with_language_servers(cx);
 9996        });
 9997
 9998        let item = Box::new(editor);
 9999        let item_id = item.item_id();
10000
10001        if split {
10002            workspace.split_item(SplitDirection::Right, item.clone(), cx);
10003        } else {
10004            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10005                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10006                    pane.close_current_preview_item(cx)
10007                } else {
10008                    None
10009                }
10010            });
10011            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10012        }
10013        workspace.active_pane().update(cx, |pane, cx| {
10014            pane.set_preview_item_id(Some(item_id), cx);
10015        });
10016    }
10017
10018    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10019        use language::ToOffset as _;
10020
10021        let provider = self.semantics_provider.clone()?;
10022        let selection = self.selections.newest_anchor().clone();
10023        let (cursor_buffer, cursor_buffer_position) = self
10024            .buffer
10025            .read(cx)
10026            .text_anchor_for_position(selection.head(), cx)?;
10027        let (tail_buffer, cursor_buffer_position_end) = self
10028            .buffer
10029            .read(cx)
10030            .text_anchor_for_position(selection.tail(), cx)?;
10031        if tail_buffer != cursor_buffer {
10032            return None;
10033        }
10034
10035        let snapshot = cursor_buffer.read(cx).snapshot();
10036        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10037        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10038        let prepare_rename = provider
10039            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10040            .unwrap_or_else(|| Task::ready(Ok(None)));
10041        drop(snapshot);
10042
10043        Some(cx.spawn(|this, mut cx| async move {
10044            let rename_range = if let Some(range) = prepare_rename.await? {
10045                Some(range)
10046            } else {
10047                this.update(&mut cx, |this, cx| {
10048                    let buffer = this.buffer.read(cx).snapshot(cx);
10049                    let mut buffer_highlights = this
10050                        .document_highlights_for_position(selection.head(), &buffer)
10051                        .filter(|highlight| {
10052                            highlight.start.excerpt_id == selection.head().excerpt_id
10053                                && highlight.end.excerpt_id == selection.head().excerpt_id
10054                        });
10055                    buffer_highlights
10056                        .next()
10057                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10058                })?
10059            };
10060            if let Some(rename_range) = rename_range {
10061                this.update(&mut cx, |this, cx| {
10062                    let snapshot = cursor_buffer.read(cx).snapshot();
10063                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10064                    let cursor_offset_in_rename_range =
10065                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10066                    let cursor_offset_in_rename_range_end =
10067                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10068
10069                    this.take_rename(false, cx);
10070                    let buffer = this.buffer.read(cx).read(cx);
10071                    let cursor_offset = selection.head().to_offset(&buffer);
10072                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10073                    let rename_end = rename_start + rename_buffer_range.len();
10074                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10075                    let mut old_highlight_id = None;
10076                    let old_name: Arc<str> = buffer
10077                        .chunks(rename_start..rename_end, true)
10078                        .map(|chunk| {
10079                            if old_highlight_id.is_none() {
10080                                old_highlight_id = chunk.syntax_highlight_id;
10081                            }
10082                            chunk.text
10083                        })
10084                        .collect::<String>()
10085                        .into();
10086
10087                    drop(buffer);
10088
10089                    // Position the selection in the rename editor so that it matches the current selection.
10090                    this.show_local_selections = false;
10091                    let rename_editor = cx.new_view(|cx| {
10092                        let mut editor = Editor::single_line(cx);
10093                        editor.buffer.update(cx, |buffer, cx| {
10094                            buffer.edit([(0..0, old_name.clone())], None, cx)
10095                        });
10096                        let rename_selection_range = match cursor_offset_in_rename_range
10097                            .cmp(&cursor_offset_in_rename_range_end)
10098                        {
10099                            Ordering::Equal => {
10100                                editor.select_all(&SelectAll, cx);
10101                                return editor;
10102                            }
10103                            Ordering::Less => {
10104                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10105                            }
10106                            Ordering::Greater => {
10107                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10108                            }
10109                        };
10110                        if rename_selection_range.end > old_name.len() {
10111                            editor.select_all(&SelectAll, cx);
10112                        } else {
10113                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10114                                s.select_ranges([rename_selection_range]);
10115                            });
10116                        }
10117                        editor
10118                    });
10119                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10120                        if e == &EditorEvent::Focused {
10121                            cx.emit(EditorEvent::FocusedIn)
10122                        }
10123                    })
10124                    .detach();
10125
10126                    let write_highlights =
10127                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10128                    let read_highlights =
10129                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10130                    let ranges = write_highlights
10131                        .iter()
10132                        .flat_map(|(_, ranges)| ranges.iter())
10133                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10134                        .cloned()
10135                        .collect();
10136
10137                    this.highlight_text::<Rename>(
10138                        ranges,
10139                        HighlightStyle {
10140                            fade_out: Some(0.6),
10141                            ..Default::default()
10142                        },
10143                        cx,
10144                    );
10145                    let rename_focus_handle = rename_editor.focus_handle(cx);
10146                    cx.focus(&rename_focus_handle);
10147                    let block_id = this.insert_blocks(
10148                        [BlockProperties {
10149                            style: BlockStyle::Flex,
10150                            placement: BlockPlacement::Below(range.start),
10151                            height: 1,
10152                            render: Arc::new({
10153                                let rename_editor = rename_editor.clone();
10154                                move |cx: &mut BlockContext| {
10155                                    let mut text_style = cx.editor_style.text.clone();
10156                                    if let Some(highlight_style) = old_highlight_id
10157                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10158                                    {
10159                                        text_style = text_style.highlight(highlight_style);
10160                                    }
10161                                    div()
10162                                        .block_mouse_down()
10163                                        .pl(cx.anchor_x)
10164                                        .child(EditorElement::new(
10165                                            &rename_editor,
10166                                            EditorStyle {
10167                                                background: cx.theme().system().transparent,
10168                                                local_player: cx.editor_style.local_player,
10169                                                text: text_style,
10170                                                scrollbar_width: cx.editor_style.scrollbar_width,
10171                                                syntax: cx.editor_style.syntax.clone(),
10172                                                status: cx.editor_style.status.clone(),
10173                                                inlay_hints_style: HighlightStyle {
10174                                                    font_weight: Some(FontWeight::BOLD),
10175                                                    ..make_inlay_hints_style(cx)
10176                                                },
10177                                                inline_completion_styles: make_suggestion_styles(
10178                                                    cx,
10179                                                ),
10180                                                ..EditorStyle::default()
10181                                            },
10182                                        ))
10183                                        .into_any_element()
10184                                }
10185                            }),
10186                            priority: 0,
10187                        }],
10188                        Some(Autoscroll::fit()),
10189                        cx,
10190                    )[0];
10191                    this.pending_rename = Some(RenameState {
10192                        range,
10193                        old_name,
10194                        editor: rename_editor,
10195                        block_id,
10196                    });
10197                })?;
10198            }
10199
10200            Ok(())
10201        }))
10202    }
10203
10204    pub fn confirm_rename(
10205        &mut self,
10206        _: &ConfirmRename,
10207        cx: &mut ViewContext<Self>,
10208    ) -> Option<Task<Result<()>>> {
10209        let rename = self.take_rename(false, cx)?;
10210        let workspace = self.workspace()?.downgrade();
10211        let (buffer, start) = self
10212            .buffer
10213            .read(cx)
10214            .text_anchor_for_position(rename.range.start, cx)?;
10215        let (end_buffer, _) = self
10216            .buffer
10217            .read(cx)
10218            .text_anchor_for_position(rename.range.end, cx)?;
10219        if buffer != end_buffer {
10220            return None;
10221        }
10222
10223        let old_name = rename.old_name;
10224        let new_name = rename.editor.read(cx).text(cx);
10225
10226        let rename = self.semantics_provider.as_ref()?.perform_rename(
10227            &buffer,
10228            start,
10229            new_name.clone(),
10230            cx,
10231        )?;
10232
10233        Some(cx.spawn(|editor, mut cx| async move {
10234            let project_transaction = rename.await?;
10235            Self::open_project_transaction(
10236                &editor,
10237                workspace,
10238                project_transaction,
10239                format!("Rename: {}{}", old_name, new_name),
10240                cx.clone(),
10241            )
10242            .await?;
10243
10244            editor.update(&mut cx, |editor, cx| {
10245                editor.refresh_document_highlights(cx);
10246            })?;
10247            Ok(())
10248        }))
10249    }
10250
10251    fn take_rename(
10252        &mut self,
10253        moving_cursor: bool,
10254        cx: &mut ViewContext<Self>,
10255    ) -> Option<RenameState> {
10256        let rename = self.pending_rename.take()?;
10257        if rename.editor.focus_handle(cx).is_focused(cx) {
10258            cx.focus(&self.focus_handle);
10259        }
10260
10261        self.remove_blocks(
10262            [rename.block_id].into_iter().collect(),
10263            Some(Autoscroll::fit()),
10264            cx,
10265        );
10266        self.clear_highlights::<Rename>(cx);
10267        self.show_local_selections = true;
10268
10269        if moving_cursor {
10270            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10271                editor.selections.newest::<usize>(cx).head()
10272            });
10273
10274            // Update the selection to match the position of the selection inside
10275            // the rename editor.
10276            let snapshot = self.buffer.read(cx).read(cx);
10277            let rename_range = rename.range.to_offset(&snapshot);
10278            let cursor_in_editor = snapshot
10279                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10280                .min(rename_range.end);
10281            drop(snapshot);
10282
10283            self.change_selections(None, cx, |s| {
10284                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10285            });
10286        } else {
10287            self.refresh_document_highlights(cx);
10288        }
10289
10290        Some(rename)
10291    }
10292
10293    pub fn pending_rename(&self) -> Option<&RenameState> {
10294        self.pending_rename.as_ref()
10295    }
10296
10297    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10298        let project = match &self.project {
10299            Some(project) => project.clone(),
10300            None => return None,
10301        };
10302
10303        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10304    }
10305
10306    fn format_selections(
10307        &mut self,
10308        _: &FormatSelections,
10309        cx: &mut ViewContext<Self>,
10310    ) -> Option<Task<Result<()>>> {
10311        let project = match &self.project {
10312            Some(project) => project.clone(),
10313            None => return None,
10314        };
10315
10316        let ranges = self
10317            .selections
10318            .all_adjusted(cx)
10319            .into_iter()
10320            .map(|selection| selection.range())
10321            .collect_vec();
10322
10323        Some(self.perform_format(
10324            project,
10325            FormatTrigger::Manual,
10326            FormatTarget::Ranges(ranges),
10327            cx,
10328        ))
10329    }
10330
10331    fn perform_format(
10332        &mut self,
10333        project: Model<Project>,
10334        trigger: FormatTrigger,
10335        target: FormatTarget,
10336        cx: &mut ViewContext<Self>,
10337    ) -> Task<Result<()>> {
10338        let buffer = self.buffer.clone();
10339        let (buffers, target) = match target {
10340            FormatTarget::Buffers => {
10341                let mut buffers = buffer.read(cx).all_buffers();
10342                if trigger == FormatTrigger::Save {
10343                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10344                }
10345                (buffers, LspFormatTarget::Buffers)
10346            }
10347            FormatTarget::Ranges(selection_ranges) => {
10348                let multi_buffer = buffer.read(cx);
10349                let snapshot = multi_buffer.read(cx);
10350                let mut buffers = HashSet::default();
10351                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10352                    BTreeMap::new();
10353                for selection_range in selection_ranges {
10354                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10355                    {
10356                        let buffer_id = excerpt.buffer_id();
10357                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10358                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10359                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10360                        buffer_id_to_ranges
10361                            .entry(buffer_id)
10362                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10363                            .or_insert_with(|| vec![start..end]);
10364                    }
10365                }
10366                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10367            }
10368        };
10369
10370        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10371        let format = project.update(cx, |project, cx| {
10372            project.format(buffers, target, true, trigger, cx)
10373        });
10374
10375        cx.spawn(|_, mut cx| async move {
10376            let transaction = futures::select_biased! {
10377                () = timeout => {
10378                    log::warn!("timed out waiting for formatting");
10379                    None
10380                }
10381                transaction = format.log_err().fuse() => transaction,
10382            };
10383
10384            buffer
10385                .update(&mut cx, |buffer, cx| {
10386                    if let Some(transaction) = transaction {
10387                        if !buffer.is_singleton() {
10388                            buffer.push_transaction(&transaction.0, cx);
10389                        }
10390                    }
10391
10392                    cx.notify();
10393                })
10394                .ok();
10395
10396            Ok(())
10397        })
10398    }
10399
10400    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10401        if let Some(project) = self.project.clone() {
10402            self.buffer.update(cx, |multi_buffer, cx| {
10403                project.update(cx, |project, cx| {
10404                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10405                });
10406            })
10407        }
10408    }
10409
10410    fn cancel_language_server_work(
10411        &mut self,
10412        _: &actions::CancelLanguageServerWork,
10413        cx: &mut ViewContext<Self>,
10414    ) {
10415        if let Some(project) = self.project.clone() {
10416            self.buffer.update(cx, |multi_buffer, cx| {
10417                project.update(cx, |project, cx| {
10418                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10419                });
10420            })
10421        }
10422    }
10423
10424    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10425        cx.show_character_palette();
10426    }
10427
10428    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10429        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10430            let buffer = self.buffer.read(cx).snapshot(cx);
10431            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10432            let is_valid = buffer
10433                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10434                .any(|entry| {
10435                    let range = entry.range.to_offset(&buffer);
10436                    entry.diagnostic.is_primary
10437                        && !range.is_empty()
10438                        && range.start == primary_range_start
10439                        && entry.diagnostic.message == active_diagnostics.primary_message
10440                });
10441
10442            if is_valid != active_diagnostics.is_valid {
10443                active_diagnostics.is_valid = is_valid;
10444                let mut new_styles = HashMap::default();
10445                for (block_id, diagnostic) in &active_diagnostics.blocks {
10446                    new_styles.insert(
10447                        *block_id,
10448                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10449                    );
10450                }
10451                self.display_map.update(cx, |display_map, _cx| {
10452                    display_map.replace_blocks(new_styles)
10453                });
10454            }
10455        }
10456    }
10457
10458    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10459        self.dismiss_diagnostics(cx);
10460        let snapshot = self.snapshot(cx);
10461        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10462            let buffer = self.buffer.read(cx).snapshot(cx);
10463
10464            let mut primary_range = None;
10465            let mut primary_message = None;
10466            let mut group_end = Point::zero();
10467            let diagnostic_group = buffer
10468                .diagnostic_group(group_id)
10469                .filter_map(|entry| {
10470                    let start = entry.range.start.to_point(&buffer);
10471                    let end = entry.range.end.to_point(&buffer);
10472                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10473                        && (start.row == end.row
10474                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10475                    {
10476                        return None;
10477                    }
10478                    if end > group_end {
10479                        group_end = end;
10480                    }
10481                    if entry.diagnostic.is_primary {
10482                        primary_range = Some(entry.range.clone());
10483                        primary_message = Some(entry.diagnostic.message.clone());
10484                    }
10485                    Some(entry)
10486                })
10487                .collect::<Vec<_>>();
10488            let primary_range = primary_range?;
10489            let primary_message = primary_message?;
10490
10491            let blocks = display_map
10492                .insert_blocks(
10493                    diagnostic_group.iter().map(|entry| {
10494                        let diagnostic = entry.diagnostic.clone();
10495                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10496                        BlockProperties {
10497                            style: BlockStyle::Fixed,
10498                            placement: BlockPlacement::Below(
10499                                buffer.anchor_after(entry.range.start),
10500                            ),
10501                            height: message_height,
10502                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10503                            priority: 0,
10504                        }
10505                    }),
10506                    cx,
10507                )
10508                .into_iter()
10509                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10510                .collect();
10511
10512            Some(ActiveDiagnosticGroup {
10513                primary_range,
10514                primary_message,
10515                group_id,
10516                blocks,
10517                is_valid: true,
10518            })
10519        });
10520    }
10521
10522    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10523        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10524            self.display_map.update(cx, |display_map, cx| {
10525                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10526            });
10527            cx.notify();
10528        }
10529    }
10530
10531    pub fn set_selections_from_remote(
10532        &mut self,
10533        selections: Vec<Selection<Anchor>>,
10534        pending_selection: Option<Selection<Anchor>>,
10535        cx: &mut ViewContext<Self>,
10536    ) {
10537        let old_cursor_position = self.selections.newest_anchor().head();
10538        self.selections.change_with(cx, |s| {
10539            s.select_anchors(selections);
10540            if let Some(pending_selection) = pending_selection {
10541                s.set_pending(pending_selection, SelectMode::Character);
10542            } else {
10543                s.clear_pending();
10544            }
10545        });
10546        self.selections_did_change(false, &old_cursor_position, true, cx);
10547    }
10548
10549    fn push_to_selection_history(&mut self) {
10550        self.selection_history.push(SelectionHistoryEntry {
10551            selections: self.selections.disjoint_anchors(),
10552            select_next_state: self.select_next_state.clone(),
10553            select_prev_state: self.select_prev_state.clone(),
10554            add_selections_state: self.add_selections_state.clone(),
10555        });
10556    }
10557
10558    pub fn transact(
10559        &mut self,
10560        cx: &mut ViewContext<Self>,
10561        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10562    ) -> Option<TransactionId> {
10563        self.start_transaction_at(Instant::now(), cx);
10564        update(self, cx);
10565        self.end_transaction_at(Instant::now(), cx)
10566    }
10567
10568    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10569        self.end_selection(cx);
10570        if let Some(tx_id) = self
10571            .buffer
10572            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10573        {
10574            self.selection_history
10575                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10576            cx.emit(EditorEvent::TransactionBegun {
10577                transaction_id: tx_id,
10578            })
10579        }
10580    }
10581
10582    pub fn end_transaction_at(
10583        &mut self,
10584        now: Instant,
10585        cx: &mut ViewContext<Self>,
10586    ) -> Option<TransactionId> {
10587        if let Some(transaction_id) = self
10588            .buffer
10589            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10590        {
10591            if let Some((_, end_selections)) =
10592                self.selection_history.transaction_mut(transaction_id)
10593            {
10594                *end_selections = Some(self.selections.disjoint_anchors());
10595            } else {
10596                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10597            }
10598
10599            cx.emit(EditorEvent::Edited { transaction_id });
10600            Some(transaction_id)
10601        } else {
10602            None
10603        }
10604    }
10605
10606    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10607        if self.is_singleton(cx) {
10608            let selection = self.selections.newest::<Point>(cx);
10609
10610            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10611            let range = if selection.is_empty() {
10612                let point = selection.head().to_display_point(&display_map);
10613                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10614                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10615                    .to_point(&display_map);
10616                start..end
10617            } else {
10618                selection.range()
10619            };
10620            if display_map.folds_in_range(range).next().is_some() {
10621                self.unfold_lines(&Default::default(), cx)
10622            } else {
10623                self.fold(&Default::default(), cx)
10624            }
10625        } else {
10626            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10627            let mut toggled_buffers = HashSet::default();
10628            for (_, buffer_snapshot, _) in
10629                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10630            {
10631                let buffer_id = buffer_snapshot.remote_id();
10632                if toggled_buffers.insert(buffer_id) {
10633                    if self.buffer_folded(buffer_id, cx) {
10634                        self.unfold_buffer(buffer_id, cx);
10635                    } else {
10636                        self.fold_buffer(buffer_id, cx);
10637                    }
10638                }
10639            }
10640        }
10641    }
10642
10643    pub fn toggle_fold_recursive(
10644        &mut self,
10645        _: &actions::ToggleFoldRecursive,
10646        cx: &mut ViewContext<Self>,
10647    ) {
10648        let selection = self.selections.newest::<Point>(cx);
10649
10650        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10651        let range = if selection.is_empty() {
10652            let point = selection.head().to_display_point(&display_map);
10653            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10654            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10655                .to_point(&display_map);
10656            start..end
10657        } else {
10658            selection.range()
10659        };
10660        if display_map.folds_in_range(range).next().is_some() {
10661            self.unfold_recursive(&Default::default(), cx)
10662        } else {
10663            self.fold_recursive(&Default::default(), cx)
10664        }
10665    }
10666
10667    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10668        if self.is_singleton(cx) {
10669            let mut to_fold = Vec::new();
10670            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10671            let selections = self.selections.all_adjusted(cx);
10672
10673            for selection in selections {
10674                let range = selection.range().sorted();
10675                let buffer_start_row = range.start.row;
10676
10677                if range.start.row != range.end.row {
10678                    let mut found = false;
10679                    let mut row = range.start.row;
10680                    while row <= range.end.row {
10681                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10682                        {
10683                            found = true;
10684                            row = crease.range().end.row + 1;
10685                            to_fold.push(crease);
10686                        } else {
10687                            row += 1
10688                        }
10689                    }
10690                    if found {
10691                        continue;
10692                    }
10693                }
10694
10695                for row in (0..=range.start.row).rev() {
10696                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10697                        if crease.range().end.row >= buffer_start_row {
10698                            to_fold.push(crease);
10699                            if row <= range.start.row {
10700                                break;
10701                            }
10702                        }
10703                    }
10704                }
10705            }
10706
10707            self.fold_creases(to_fold, true, cx);
10708        } else {
10709            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10710            let mut folded_buffers = HashSet::default();
10711            for (_, buffer_snapshot, _) in
10712                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10713            {
10714                let buffer_id = buffer_snapshot.remote_id();
10715                if folded_buffers.insert(buffer_id) {
10716                    self.fold_buffer(buffer_id, cx);
10717                }
10718            }
10719        }
10720    }
10721
10722    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10723        if !self.buffer.read(cx).is_singleton() {
10724            return;
10725        }
10726
10727        let fold_at_level = fold_at.level;
10728        let snapshot = self.buffer.read(cx).snapshot(cx);
10729        let mut to_fold = Vec::new();
10730        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10731
10732        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10733            while start_row < end_row {
10734                match self
10735                    .snapshot(cx)
10736                    .crease_for_buffer_row(MultiBufferRow(start_row))
10737                {
10738                    Some(crease) => {
10739                        let nested_start_row = crease.range().start.row + 1;
10740                        let nested_end_row = crease.range().end.row;
10741
10742                        if current_level < fold_at_level {
10743                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10744                        } else if current_level == fold_at_level {
10745                            to_fold.push(crease);
10746                        }
10747
10748                        start_row = nested_end_row + 1;
10749                    }
10750                    None => start_row += 1,
10751                }
10752            }
10753        }
10754
10755        self.fold_creases(to_fold, true, cx);
10756    }
10757
10758    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10759        if self.buffer.read(cx).is_singleton() {
10760            let mut fold_ranges = Vec::new();
10761            let snapshot = self.buffer.read(cx).snapshot(cx);
10762
10763            for row in 0..snapshot.max_row().0 {
10764                if let Some(foldable_range) =
10765                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10766                {
10767                    fold_ranges.push(foldable_range);
10768                }
10769            }
10770
10771            self.fold_creases(fold_ranges, true, cx);
10772        } else {
10773            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10774                editor
10775                    .update(&mut cx, |editor, cx| {
10776                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10777                            editor.fold_buffer(buffer_id, cx);
10778                        }
10779                    })
10780                    .ok();
10781            });
10782        }
10783    }
10784
10785    pub fn fold_function_bodies(
10786        &mut self,
10787        _: &actions::FoldFunctionBodies,
10788        cx: &mut ViewContext<Self>,
10789    ) {
10790        let snapshot = self.buffer.read(cx).snapshot(cx);
10791        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10792            return;
10793        };
10794        let creases = buffer
10795            .function_body_fold_ranges(0..buffer.len())
10796            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10797            .collect();
10798
10799        self.fold_creases(creases, true, cx);
10800    }
10801
10802    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10803        let mut to_fold = Vec::new();
10804        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10805        let selections = self.selections.all_adjusted(cx);
10806
10807        for selection in selections {
10808            let range = selection.range().sorted();
10809            let buffer_start_row = range.start.row;
10810
10811            if range.start.row != range.end.row {
10812                let mut found = false;
10813                for row in range.start.row..=range.end.row {
10814                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10815                        found = true;
10816                        to_fold.push(crease);
10817                    }
10818                }
10819                if found {
10820                    continue;
10821                }
10822            }
10823
10824            for row in (0..=range.start.row).rev() {
10825                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10826                    if crease.range().end.row >= buffer_start_row {
10827                        to_fold.push(crease);
10828                    } else {
10829                        break;
10830                    }
10831                }
10832            }
10833        }
10834
10835        self.fold_creases(to_fold, true, cx);
10836    }
10837
10838    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10839        let buffer_row = fold_at.buffer_row;
10840        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10841
10842        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10843            let autoscroll = self
10844                .selections
10845                .all::<Point>(cx)
10846                .iter()
10847                .any(|selection| crease.range().overlaps(&selection.range()));
10848
10849            self.fold_creases(vec![crease], autoscroll, cx);
10850        }
10851    }
10852
10853    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10854        if self.is_singleton(cx) {
10855            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10856            let buffer = &display_map.buffer_snapshot;
10857            let selections = self.selections.all::<Point>(cx);
10858            let ranges = selections
10859                .iter()
10860                .map(|s| {
10861                    let range = s.display_range(&display_map).sorted();
10862                    let mut start = range.start.to_point(&display_map);
10863                    let mut end = range.end.to_point(&display_map);
10864                    start.column = 0;
10865                    end.column = buffer.line_len(MultiBufferRow(end.row));
10866                    start..end
10867                })
10868                .collect::<Vec<_>>();
10869
10870            self.unfold_ranges(&ranges, true, true, cx);
10871        } else {
10872            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10873            let mut unfolded_buffers = HashSet::default();
10874            for (_, buffer_snapshot, _) in
10875                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10876            {
10877                let buffer_id = buffer_snapshot.remote_id();
10878                if unfolded_buffers.insert(buffer_id) {
10879                    self.unfold_buffer(buffer_id, cx);
10880                }
10881            }
10882        }
10883    }
10884
10885    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10887        let selections = self.selections.all::<Point>(cx);
10888        let ranges = selections
10889            .iter()
10890            .map(|s| {
10891                let mut range = s.display_range(&display_map).sorted();
10892                *range.start.column_mut() = 0;
10893                *range.end.column_mut() = display_map.line_len(range.end.row());
10894                let start = range.start.to_point(&display_map);
10895                let end = range.end.to_point(&display_map);
10896                start..end
10897            })
10898            .collect::<Vec<_>>();
10899
10900        self.unfold_ranges(&ranges, true, true, cx);
10901    }
10902
10903    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10904        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10905
10906        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10907            ..Point::new(
10908                unfold_at.buffer_row.0,
10909                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10910            );
10911
10912        let autoscroll = self
10913            .selections
10914            .all::<Point>(cx)
10915            .iter()
10916            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10917
10918        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10919    }
10920
10921    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10922        if self.buffer.read(cx).is_singleton() {
10923            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10924            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10925        } else {
10926            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10927                editor
10928                    .update(&mut cx, |editor, cx| {
10929                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10930                            editor.unfold_buffer(buffer_id, cx);
10931                        }
10932                    })
10933                    .ok();
10934            });
10935        }
10936    }
10937
10938    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10939        let selections = self.selections.all::<Point>(cx);
10940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10941        let line_mode = self.selections.line_mode;
10942        let ranges = selections
10943            .into_iter()
10944            .map(|s| {
10945                if line_mode {
10946                    let start = Point::new(s.start.row, 0);
10947                    let end = Point::new(
10948                        s.end.row,
10949                        display_map
10950                            .buffer_snapshot
10951                            .line_len(MultiBufferRow(s.end.row)),
10952                    );
10953                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10954                } else {
10955                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10956                }
10957            })
10958            .collect::<Vec<_>>();
10959        self.fold_creases(ranges, true, cx);
10960    }
10961
10962    pub fn fold_ranges<T: ToOffset + Clone>(
10963        &mut self,
10964        ranges: Vec<Range<T>>,
10965        auto_scroll: bool,
10966        cx: &mut ViewContext<Self>,
10967    ) {
10968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10969        let ranges = ranges
10970            .into_iter()
10971            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10972            .collect::<Vec<_>>();
10973        self.fold_creases(ranges, auto_scroll, cx);
10974    }
10975
10976    pub fn fold_creases<T: ToOffset + Clone>(
10977        &mut self,
10978        creases: Vec<Crease<T>>,
10979        auto_scroll: bool,
10980        cx: &mut ViewContext<Self>,
10981    ) {
10982        if creases.is_empty() {
10983            return;
10984        }
10985
10986        let mut buffers_affected = HashSet::default();
10987        let multi_buffer = self.buffer().read(cx);
10988        for crease in &creases {
10989            if let Some((_, buffer, _)) =
10990                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10991            {
10992                buffers_affected.insert(buffer.read(cx).remote_id());
10993            };
10994        }
10995
10996        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10997
10998        if auto_scroll {
10999            self.request_autoscroll(Autoscroll::fit(), cx);
11000        }
11001
11002        for buffer_id in buffers_affected {
11003            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11004        }
11005
11006        cx.notify();
11007
11008        if let Some(active_diagnostics) = self.active_diagnostics.take() {
11009            // Clear diagnostics block when folding a range that contains it.
11010            let snapshot = self.snapshot(cx);
11011            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11012                drop(snapshot);
11013                self.active_diagnostics = Some(active_diagnostics);
11014                self.dismiss_diagnostics(cx);
11015            } else {
11016                self.active_diagnostics = Some(active_diagnostics);
11017            }
11018        }
11019
11020        self.scrollbar_marker_state.dirty = true;
11021    }
11022
11023    /// Removes any folds whose ranges intersect any of the given ranges.
11024    pub fn unfold_ranges<T: ToOffset + Clone>(
11025        &mut self,
11026        ranges: &[Range<T>],
11027        inclusive: bool,
11028        auto_scroll: bool,
11029        cx: &mut ViewContext<Self>,
11030    ) {
11031        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11032            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11033        });
11034    }
11035
11036    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11037        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11038            return;
11039        }
11040        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11041            return;
11042        };
11043        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11044        self.display_map
11045            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11046        cx.emit(EditorEvent::BufferFoldToggled {
11047            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11048            folded: true,
11049        });
11050        cx.notify();
11051    }
11052
11053    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11054        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11055            return;
11056        }
11057        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11058            return;
11059        };
11060        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11061        self.display_map.update(cx, |display_map, cx| {
11062            display_map.unfold_buffer(buffer_id, cx);
11063        });
11064        cx.emit(EditorEvent::BufferFoldToggled {
11065            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11066            folded: false,
11067        });
11068        cx.notify();
11069    }
11070
11071    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11072        self.display_map.read(cx).buffer_folded(buffer)
11073    }
11074
11075    /// Removes any folds with the given ranges.
11076    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11077        &mut self,
11078        ranges: &[Range<T>],
11079        type_id: TypeId,
11080        auto_scroll: bool,
11081        cx: &mut ViewContext<Self>,
11082    ) {
11083        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11084            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11085        });
11086    }
11087
11088    fn remove_folds_with<T: ToOffset + Clone>(
11089        &mut self,
11090        ranges: &[Range<T>],
11091        auto_scroll: bool,
11092        cx: &mut ViewContext<Self>,
11093        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11094    ) {
11095        if ranges.is_empty() {
11096            return;
11097        }
11098
11099        let mut buffers_affected = HashSet::default();
11100        let multi_buffer = self.buffer().read(cx);
11101        for range in ranges {
11102            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11103                buffers_affected.insert(buffer.read(cx).remote_id());
11104            };
11105        }
11106
11107        self.display_map.update(cx, update);
11108
11109        if auto_scroll {
11110            self.request_autoscroll(Autoscroll::fit(), cx);
11111        }
11112
11113        for buffer_id in buffers_affected {
11114            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11115        }
11116
11117        cx.notify();
11118        self.scrollbar_marker_state.dirty = true;
11119        self.active_indent_guides_state.dirty = true;
11120    }
11121
11122    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11123        self.display_map.read(cx).fold_placeholder.clone()
11124    }
11125
11126    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11127        if hovered != self.gutter_hovered {
11128            self.gutter_hovered = hovered;
11129            cx.notify();
11130        }
11131    }
11132
11133    pub fn insert_blocks(
11134        &mut self,
11135        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11136        autoscroll: Option<Autoscroll>,
11137        cx: &mut ViewContext<Self>,
11138    ) -> Vec<CustomBlockId> {
11139        let blocks = self
11140            .display_map
11141            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11142        if let Some(autoscroll) = autoscroll {
11143            self.request_autoscroll(autoscroll, cx);
11144        }
11145        cx.notify();
11146        blocks
11147    }
11148
11149    pub fn resize_blocks(
11150        &mut self,
11151        heights: HashMap<CustomBlockId, u32>,
11152        autoscroll: Option<Autoscroll>,
11153        cx: &mut ViewContext<Self>,
11154    ) {
11155        self.display_map
11156            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11157        if let Some(autoscroll) = autoscroll {
11158            self.request_autoscroll(autoscroll, cx);
11159        }
11160        cx.notify();
11161    }
11162
11163    pub fn replace_blocks(
11164        &mut self,
11165        renderers: HashMap<CustomBlockId, RenderBlock>,
11166        autoscroll: Option<Autoscroll>,
11167        cx: &mut ViewContext<Self>,
11168    ) {
11169        self.display_map
11170            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11171        if let Some(autoscroll) = autoscroll {
11172            self.request_autoscroll(autoscroll, cx);
11173        }
11174        cx.notify();
11175    }
11176
11177    pub fn remove_blocks(
11178        &mut self,
11179        block_ids: HashSet<CustomBlockId>,
11180        autoscroll: Option<Autoscroll>,
11181        cx: &mut ViewContext<Self>,
11182    ) {
11183        self.display_map.update(cx, |display_map, cx| {
11184            display_map.remove_blocks(block_ids, cx)
11185        });
11186        if let Some(autoscroll) = autoscroll {
11187            self.request_autoscroll(autoscroll, cx);
11188        }
11189        cx.notify();
11190    }
11191
11192    pub fn row_for_block(
11193        &self,
11194        block_id: CustomBlockId,
11195        cx: &mut ViewContext<Self>,
11196    ) -> Option<DisplayRow> {
11197        self.display_map
11198            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11199    }
11200
11201    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11202        self.focused_block = Some(focused_block);
11203    }
11204
11205    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11206        self.focused_block.take()
11207    }
11208
11209    pub fn insert_creases(
11210        &mut self,
11211        creases: impl IntoIterator<Item = Crease<Anchor>>,
11212        cx: &mut ViewContext<Self>,
11213    ) -> Vec<CreaseId> {
11214        self.display_map
11215            .update(cx, |map, cx| map.insert_creases(creases, cx))
11216    }
11217
11218    pub fn remove_creases(
11219        &mut self,
11220        ids: impl IntoIterator<Item = CreaseId>,
11221        cx: &mut ViewContext<Self>,
11222    ) {
11223        self.display_map
11224            .update(cx, |map, cx| map.remove_creases(ids, cx));
11225    }
11226
11227    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11228        self.display_map
11229            .update(cx, |map, cx| map.snapshot(cx))
11230            .longest_row()
11231    }
11232
11233    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11234        self.display_map
11235            .update(cx, |map, cx| map.snapshot(cx))
11236            .max_point()
11237    }
11238
11239    pub fn text(&self, cx: &AppContext) -> String {
11240        self.buffer.read(cx).read(cx).text()
11241    }
11242
11243    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11244        let text = self.text(cx);
11245        let text = text.trim();
11246
11247        if text.is_empty() {
11248            return None;
11249        }
11250
11251        Some(text.to_string())
11252    }
11253
11254    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11255        self.transact(cx, |this, cx| {
11256            this.buffer
11257                .read(cx)
11258                .as_singleton()
11259                .expect("you can only call set_text on editors for singleton buffers")
11260                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11261        });
11262    }
11263
11264    pub fn display_text(&self, cx: &mut AppContext) -> String {
11265        self.display_map
11266            .update(cx, |map, cx| map.snapshot(cx))
11267            .text()
11268    }
11269
11270    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11271        let mut wrap_guides = smallvec::smallvec![];
11272
11273        if self.show_wrap_guides == Some(false) {
11274            return wrap_guides;
11275        }
11276
11277        let settings = self.buffer.read(cx).settings_at(0, cx);
11278        if settings.show_wrap_guides {
11279            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11280                wrap_guides.push((soft_wrap as usize, true));
11281            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11282                wrap_guides.push((soft_wrap as usize, true));
11283            }
11284            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11285        }
11286
11287        wrap_guides
11288    }
11289
11290    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11291        let settings = self.buffer.read(cx).settings_at(0, cx);
11292        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11293        match mode {
11294            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11295                SoftWrap::None
11296            }
11297            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11298            language_settings::SoftWrap::PreferredLineLength => {
11299                SoftWrap::Column(settings.preferred_line_length)
11300            }
11301            language_settings::SoftWrap::Bounded => {
11302                SoftWrap::Bounded(settings.preferred_line_length)
11303            }
11304        }
11305    }
11306
11307    pub fn set_soft_wrap_mode(
11308        &mut self,
11309        mode: language_settings::SoftWrap,
11310        cx: &mut ViewContext<Self>,
11311    ) {
11312        self.soft_wrap_mode_override = Some(mode);
11313        cx.notify();
11314    }
11315
11316    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11317        self.text_style_refinement = Some(style);
11318    }
11319
11320    /// called by the Element so we know what style we were most recently rendered with.
11321    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11322        let rem_size = cx.rem_size();
11323        self.display_map.update(cx, |map, cx| {
11324            map.set_font(
11325                style.text.font(),
11326                style.text.font_size.to_pixels(rem_size),
11327                cx,
11328            )
11329        });
11330        self.style = Some(style);
11331    }
11332
11333    pub fn style(&self) -> Option<&EditorStyle> {
11334        self.style.as_ref()
11335    }
11336
11337    // Called by the element. This method is not designed to be called outside of the editor
11338    // element's layout code because it does not notify when rewrapping is computed synchronously.
11339    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11340        self.display_map
11341            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11342    }
11343
11344    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11345        if self.soft_wrap_mode_override.is_some() {
11346            self.soft_wrap_mode_override.take();
11347        } else {
11348            let soft_wrap = match self.soft_wrap_mode(cx) {
11349                SoftWrap::GitDiff => return,
11350                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11351                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11352                    language_settings::SoftWrap::None
11353                }
11354            };
11355            self.soft_wrap_mode_override = Some(soft_wrap);
11356        }
11357        cx.notify();
11358    }
11359
11360    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11361        let Some(workspace) = self.workspace() else {
11362            return;
11363        };
11364        let fs = workspace.read(cx).app_state().fs.clone();
11365        let current_show = TabBarSettings::get_global(cx).show;
11366        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11367            setting.show = Some(!current_show);
11368        });
11369    }
11370
11371    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11372        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11373            self.buffer
11374                .read(cx)
11375                .settings_at(0, cx)
11376                .indent_guides
11377                .enabled
11378        });
11379        self.show_indent_guides = Some(!currently_enabled);
11380        cx.notify();
11381    }
11382
11383    fn should_show_indent_guides(&self) -> Option<bool> {
11384        self.show_indent_guides
11385    }
11386
11387    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11388        let mut editor_settings = EditorSettings::get_global(cx).clone();
11389        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11390        EditorSettings::override_global(editor_settings, cx);
11391    }
11392
11393    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11394        self.use_relative_line_numbers
11395            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11396    }
11397
11398    pub fn toggle_relative_line_numbers(
11399        &mut self,
11400        _: &ToggleRelativeLineNumbers,
11401        cx: &mut ViewContext<Self>,
11402    ) {
11403        let is_relative = self.should_use_relative_line_numbers(cx);
11404        self.set_relative_line_number(Some(!is_relative), cx)
11405    }
11406
11407    pub fn set_relative_line_number(
11408        &mut self,
11409        is_relative: Option<bool>,
11410        cx: &mut ViewContext<Self>,
11411    ) {
11412        self.use_relative_line_numbers = is_relative;
11413        cx.notify();
11414    }
11415
11416    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11417        self.show_gutter = show_gutter;
11418        cx.notify();
11419    }
11420
11421    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11422        self.show_scrollbars = show_scrollbars;
11423        cx.notify();
11424    }
11425
11426    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11427        self.show_line_numbers = Some(show_line_numbers);
11428        cx.notify();
11429    }
11430
11431    pub fn set_show_git_diff_gutter(
11432        &mut self,
11433        show_git_diff_gutter: bool,
11434        cx: &mut ViewContext<Self>,
11435    ) {
11436        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11437        cx.notify();
11438    }
11439
11440    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11441        self.show_code_actions = Some(show_code_actions);
11442        cx.notify();
11443    }
11444
11445    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11446        self.show_runnables = Some(show_runnables);
11447        cx.notify();
11448    }
11449
11450    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11451        if self.display_map.read(cx).masked != masked {
11452            self.display_map.update(cx, |map, _| map.masked = masked);
11453        }
11454        cx.notify()
11455    }
11456
11457    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11458        self.show_wrap_guides = Some(show_wrap_guides);
11459        cx.notify();
11460    }
11461
11462    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11463        self.show_indent_guides = Some(show_indent_guides);
11464        cx.notify();
11465    }
11466
11467    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11468        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11469            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11470                if let Some(dir) = file.abs_path(cx).parent() {
11471                    return Some(dir.to_owned());
11472                }
11473            }
11474
11475            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11476                return Some(project_path.path.to_path_buf());
11477            }
11478        }
11479
11480        None
11481    }
11482
11483    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11484        self.active_excerpt(cx)?
11485            .1
11486            .read(cx)
11487            .file()
11488            .and_then(|f| f.as_local())
11489    }
11490
11491    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11492        if let Some(target) = self.target_file(cx) {
11493            cx.reveal_path(&target.abs_path(cx));
11494        }
11495    }
11496
11497    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11498        if let Some(file) = self.target_file(cx) {
11499            if let Some(path) = file.abs_path(cx).to_str() {
11500                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11501            }
11502        }
11503    }
11504
11505    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11506        if let Some(file) = self.target_file(cx) {
11507            if let Some(path) = file.path().to_str() {
11508                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11509            }
11510        }
11511    }
11512
11513    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11514        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11515
11516        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11517            self.start_git_blame(true, cx);
11518        }
11519
11520        cx.notify();
11521    }
11522
11523    pub fn toggle_git_blame_inline(
11524        &mut self,
11525        _: &ToggleGitBlameInline,
11526        cx: &mut ViewContext<Self>,
11527    ) {
11528        self.toggle_git_blame_inline_internal(true, cx);
11529        cx.notify();
11530    }
11531
11532    pub fn git_blame_inline_enabled(&self) -> bool {
11533        self.git_blame_inline_enabled
11534    }
11535
11536    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11537        self.show_selection_menu = self
11538            .show_selection_menu
11539            .map(|show_selections_menu| !show_selections_menu)
11540            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11541
11542        cx.notify();
11543    }
11544
11545    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11546        self.show_selection_menu
11547            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11548    }
11549
11550    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11551        if let Some(project) = self.project.as_ref() {
11552            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11553                return;
11554            };
11555
11556            if buffer.read(cx).file().is_none() {
11557                return;
11558            }
11559
11560            let focused = self.focus_handle(cx).contains_focused(cx);
11561
11562            let project = project.clone();
11563            let blame =
11564                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11565            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11566            self.blame = Some(blame);
11567        }
11568    }
11569
11570    fn toggle_git_blame_inline_internal(
11571        &mut self,
11572        user_triggered: bool,
11573        cx: &mut ViewContext<Self>,
11574    ) {
11575        if self.git_blame_inline_enabled {
11576            self.git_blame_inline_enabled = false;
11577            self.show_git_blame_inline = false;
11578            self.show_git_blame_inline_delay_task.take();
11579        } else {
11580            self.git_blame_inline_enabled = true;
11581            self.start_git_blame_inline(user_triggered, cx);
11582        }
11583
11584        cx.notify();
11585    }
11586
11587    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11588        self.start_git_blame(user_triggered, cx);
11589
11590        if ProjectSettings::get_global(cx)
11591            .git
11592            .inline_blame_delay()
11593            .is_some()
11594        {
11595            self.start_inline_blame_timer(cx);
11596        } else {
11597            self.show_git_blame_inline = true
11598        }
11599    }
11600
11601    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11602        self.blame.as_ref()
11603    }
11604
11605    pub fn show_git_blame_gutter(&self) -> bool {
11606        self.show_git_blame_gutter
11607    }
11608
11609    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11610        self.show_git_blame_gutter && self.has_blame_entries(cx)
11611    }
11612
11613    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11614        self.show_git_blame_inline
11615            && self.focus_handle.is_focused(cx)
11616            && !self.newest_selection_head_on_empty_line(cx)
11617            && self.has_blame_entries(cx)
11618    }
11619
11620    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11621        self.blame()
11622            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11623    }
11624
11625    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11626        let cursor_anchor = self.selections.newest_anchor().head();
11627
11628        let snapshot = self.buffer.read(cx).snapshot(cx);
11629        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11630
11631        snapshot.line_len(buffer_row) == 0
11632    }
11633
11634    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11635        let buffer_and_selection = maybe!({
11636            let selection = self.selections.newest::<Point>(cx);
11637            let selection_range = selection.range();
11638
11639            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11640                (buffer, selection_range.start.row..selection_range.end.row)
11641            } else {
11642                let multi_buffer = self.buffer().read(cx);
11643                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11644                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11645
11646                let (excerpt, range) = if selection.reversed {
11647                    buffer_ranges.first()
11648                } else {
11649                    buffer_ranges.last()
11650                }?;
11651
11652                let snapshot = excerpt.buffer();
11653                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11654                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11655                (
11656                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11657                    selection,
11658                )
11659            };
11660
11661            Some((buffer, selection))
11662        });
11663
11664        let Some((buffer, selection)) = buffer_and_selection else {
11665            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11666        };
11667
11668        let Some(project) = self.project.as_ref() else {
11669            return Task::ready(Err(anyhow!("editor does not have project")));
11670        };
11671
11672        project.update(cx, |project, cx| {
11673            project.get_permalink_to_line(&buffer, selection, cx)
11674        })
11675    }
11676
11677    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11678        let permalink_task = self.get_permalink_to_line(cx);
11679        let workspace = self.workspace();
11680
11681        cx.spawn(|_, mut cx| async move {
11682            match permalink_task.await {
11683                Ok(permalink) => {
11684                    cx.update(|cx| {
11685                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11686                    })
11687                    .ok();
11688                }
11689                Err(err) => {
11690                    let message = format!("Failed to copy permalink: {err}");
11691
11692                    Err::<(), anyhow::Error>(err).log_err();
11693
11694                    if let Some(workspace) = workspace {
11695                        workspace
11696                            .update(&mut cx, |workspace, cx| {
11697                                struct CopyPermalinkToLine;
11698
11699                                workspace.show_toast(
11700                                    Toast::new(
11701                                        NotificationId::unique::<CopyPermalinkToLine>(),
11702                                        message,
11703                                    ),
11704                                    cx,
11705                                )
11706                            })
11707                            .ok();
11708                    }
11709                }
11710            }
11711        })
11712        .detach();
11713    }
11714
11715    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11716        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11717        if let Some(file) = self.target_file(cx) {
11718            if let Some(path) = file.path().to_str() {
11719                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11720            }
11721        }
11722    }
11723
11724    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11725        let permalink_task = self.get_permalink_to_line(cx);
11726        let workspace = self.workspace();
11727
11728        cx.spawn(|_, mut cx| async move {
11729            match permalink_task.await {
11730                Ok(permalink) => {
11731                    cx.update(|cx| {
11732                        cx.open_url(permalink.as_ref());
11733                    })
11734                    .ok();
11735                }
11736                Err(err) => {
11737                    let message = format!("Failed to open permalink: {err}");
11738
11739                    Err::<(), anyhow::Error>(err).log_err();
11740
11741                    if let Some(workspace) = workspace {
11742                        workspace
11743                            .update(&mut cx, |workspace, cx| {
11744                                struct OpenPermalinkToLine;
11745
11746                                workspace.show_toast(
11747                                    Toast::new(
11748                                        NotificationId::unique::<OpenPermalinkToLine>(),
11749                                        message,
11750                                    ),
11751                                    cx,
11752                                )
11753                            })
11754                            .ok();
11755                    }
11756                }
11757            }
11758        })
11759        .detach();
11760    }
11761
11762    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11763        self.insert_uuid(UuidVersion::V4, cx);
11764    }
11765
11766    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11767        self.insert_uuid(UuidVersion::V7, cx);
11768    }
11769
11770    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11771        self.transact(cx, |this, cx| {
11772            let edits = this
11773                .selections
11774                .all::<Point>(cx)
11775                .into_iter()
11776                .map(|selection| {
11777                    let uuid = match version {
11778                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11779                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11780                    };
11781
11782                    (selection.range(), uuid.to_string())
11783                });
11784            this.edit(edits, cx);
11785            this.refresh_inline_completion(true, false, cx);
11786        });
11787    }
11788
11789    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11790    /// last highlight added will be used.
11791    ///
11792    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11793    pub fn highlight_rows<T: 'static>(
11794        &mut self,
11795        range: Range<Anchor>,
11796        color: Hsla,
11797        should_autoscroll: bool,
11798        cx: &mut ViewContext<Self>,
11799    ) {
11800        let snapshot = self.buffer().read(cx).snapshot(cx);
11801        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11802        let ix = row_highlights.binary_search_by(|highlight| {
11803            Ordering::Equal
11804                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11805                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11806        });
11807
11808        if let Err(mut ix) = ix {
11809            let index = post_inc(&mut self.highlight_order);
11810
11811            // If this range intersects with the preceding highlight, then merge it with
11812            // the preceding highlight. Otherwise insert a new highlight.
11813            let mut merged = false;
11814            if ix > 0 {
11815                let prev_highlight = &mut row_highlights[ix - 1];
11816                if prev_highlight
11817                    .range
11818                    .end
11819                    .cmp(&range.start, &snapshot)
11820                    .is_ge()
11821                {
11822                    ix -= 1;
11823                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11824                        prev_highlight.range.end = range.end;
11825                    }
11826                    merged = true;
11827                    prev_highlight.index = index;
11828                    prev_highlight.color = color;
11829                    prev_highlight.should_autoscroll = should_autoscroll;
11830                }
11831            }
11832
11833            if !merged {
11834                row_highlights.insert(
11835                    ix,
11836                    RowHighlight {
11837                        range: range.clone(),
11838                        index,
11839                        color,
11840                        should_autoscroll,
11841                    },
11842                );
11843            }
11844
11845            // If any of the following highlights intersect with this one, merge them.
11846            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11847                let highlight = &row_highlights[ix];
11848                if next_highlight
11849                    .range
11850                    .start
11851                    .cmp(&highlight.range.end, &snapshot)
11852                    .is_le()
11853                {
11854                    if next_highlight
11855                        .range
11856                        .end
11857                        .cmp(&highlight.range.end, &snapshot)
11858                        .is_gt()
11859                    {
11860                        row_highlights[ix].range.end = next_highlight.range.end;
11861                    }
11862                    row_highlights.remove(ix + 1);
11863                } else {
11864                    break;
11865                }
11866            }
11867        }
11868    }
11869
11870    /// Remove any highlighted row ranges of the given type that intersect the
11871    /// given ranges.
11872    pub fn remove_highlighted_rows<T: 'static>(
11873        &mut self,
11874        ranges_to_remove: Vec<Range<Anchor>>,
11875        cx: &mut ViewContext<Self>,
11876    ) {
11877        let snapshot = self.buffer().read(cx).snapshot(cx);
11878        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11879        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11880        row_highlights.retain(|highlight| {
11881            while let Some(range_to_remove) = ranges_to_remove.peek() {
11882                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11883                    Ordering::Less | Ordering::Equal => {
11884                        ranges_to_remove.next();
11885                    }
11886                    Ordering::Greater => {
11887                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11888                            Ordering::Less | Ordering::Equal => {
11889                                return false;
11890                            }
11891                            Ordering::Greater => break,
11892                        }
11893                    }
11894                }
11895            }
11896
11897            true
11898        })
11899    }
11900
11901    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11902    pub fn clear_row_highlights<T: 'static>(&mut self) {
11903        self.highlighted_rows.remove(&TypeId::of::<T>());
11904    }
11905
11906    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11907    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11908        self.highlighted_rows
11909            .get(&TypeId::of::<T>())
11910            .map_or(&[] as &[_], |vec| vec.as_slice())
11911            .iter()
11912            .map(|highlight| (highlight.range.clone(), highlight.color))
11913    }
11914
11915    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11916    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11917    /// Allows to ignore certain kinds of highlights.
11918    pub fn highlighted_display_rows(
11919        &mut self,
11920        cx: &mut WindowContext,
11921    ) -> BTreeMap<DisplayRow, Hsla> {
11922        let snapshot = self.snapshot(cx);
11923        let mut used_highlight_orders = HashMap::default();
11924        self.highlighted_rows
11925            .iter()
11926            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11927            .fold(
11928                BTreeMap::<DisplayRow, Hsla>::new(),
11929                |mut unique_rows, highlight| {
11930                    let start = highlight.range.start.to_display_point(&snapshot);
11931                    let end = highlight.range.end.to_display_point(&snapshot);
11932                    let start_row = start.row().0;
11933                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11934                        && end.column() == 0
11935                    {
11936                        end.row().0.saturating_sub(1)
11937                    } else {
11938                        end.row().0
11939                    };
11940                    for row in start_row..=end_row {
11941                        let used_index =
11942                            used_highlight_orders.entry(row).or_insert(highlight.index);
11943                        if highlight.index >= *used_index {
11944                            *used_index = highlight.index;
11945                            unique_rows.insert(DisplayRow(row), highlight.color);
11946                        }
11947                    }
11948                    unique_rows
11949                },
11950            )
11951    }
11952
11953    pub fn highlighted_display_row_for_autoscroll(
11954        &self,
11955        snapshot: &DisplaySnapshot,
11956    ) -> Option<DisplayRow> {
11957        self.highlighted_rows
11958            .values()
11959            .flat_map(|highlighted_rows| highlighted_rows.iter())
11960            .filter_map(|highlight| {
11961                if highlight.should_autoscroll {
11962                    Some(highlight.range.start.to_display_point(snapshot).row())
11963                } else {
11964                    None
11965                }
11966            })
11967            .min()
11968    }
11969
11970    pub fn set_search_within_ranges(
11971        &mut self,
11972        ranges: &[Range<Anchor>],
11973        cx: &mut ViewContext<Self>,
11974    ) {
11975        self.highlight_background::<SearchWithinRange>(
11976            ranges,
11977            |colors| colors.editor_document_highlight_read_background,
11978            cx,
11979        )
11980    }
11981
11982    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11983        self.breadcrumb_header = Some(new_header);
11984    }
11985
11986    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11987        self.clear_background_highlights::<SearchWithinRange>(cx);
11988    }
11989
11990    pub fn highlight_background<T: 'static>(
11991        &mut self,
11992        ranges: &[Range<Anchor>],
11993        color_fetcher: fn(&ThemeColors) -> Hsla,
11994        cx: &mut ViewContext<Self>,
11995    ) {
11996        self.background_highlights
11997            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11998        self.scrollbar_marker_state.dirty = true;
11999        cx.notify();
12000    }
12001
12002    pub fn clear_background_highlights<T: 'static>(
12003        &mut self,
12004        cx: &mut ViewContext<Self>,
12005    ) -> Option<BackgroundHighlight> {
12006        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12007        if !text_highlights.1.is_empty() {
12008            self.scrollbar_marker_state.dirty = true;
12009            cx.notify();
12010        }
12011        Some(text_highlights)
12012    }
12013
12014    pub fn highlight_gutter<T: 'static>(
12015        &mut self,
12016        ranges: &[Range<Anchor>],
12017        color_fetcher: fn(&AppContext) -> Hsla,
12018        cx: &mut ViewContext<Self>,
12019    ) {
12020        self.gutter_highlights
12021            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12022        cx.notify();
12023    }
12024
12025    pub fn clear_gutter_highlights<T: 'static>(
12026        &mut self,
12027        cx: &mut ViewContext<Self>,
12028    ) -> Option<GutterHighlight> {
12029        cx.notify();
12030        self.gutter_highlights.remove(&TypeId::of::<T>())
12031    }
12032
12033    #[cfg(feature = "test-support")]
12034    pub fn all_text_background_highlights(
12035        &mut self,
12036        cx: &mut ViewContext<Self>,
12037    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12038        let snapshot = self.snapshot(cx);
12039        let buffer = &snapshot.buffer_snapshot;
12040        let start = buffer.anchor_before(0);
12041        let end = buffer.anchor_after(buffer.len());
12042        let theme = cx.theme().colors();
12043        self.background_highlights_in_range(start..end, &snapshot, theme)
12044    }
12045
12046    #[cfg(feature = "test-support")]
12047    pub fn search_background_highlights(
12048        &mut self,
12049        cx: &mut ViewContext<Self>,
12050    ) -> Vec<Range<Point>> {
12051        let snapshot = self.buffer().read(cx).snapshot(cx);
12052
12053        let highlights = self
12054            .background_highlights
12055            .get(&TypeId::of::<items::BufferSearchHighlights>());
12056
12057        if let Some((_color, ranges)) = highlights {
12058            ranges
12059                .iter()
12060                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12061                .collect_vec()
12062        } else {
12063            vec![]
12064        }
12065    }
12066
12067    fn document_highlights_for_position<'a>(
12068        &'a self,
12069        position: Anchor,
12070        buffer: &'a MultiBufferSnapshot,
12071    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12072        let read_highlights = self
12073            .background_highlights
12074            .get(&TypeId::of::<DocumentHighlightRead>())
12075            .map(|h| &h.1);
12076        let write_highlights = self
12077            .background_highlights
12078            .get(&TypeId::of::<DocumentHighlightWrite>())
12079            .map(|h| &h.1);
12080        let left_position = position.bias_left(buffer);
12081        let right_position = position.bias_right(buffer);
12082        read_highlights
12083            .into_iter()
12084            .chain(write_highlights)
12085            .flat_map(move |ranges| {
12086                let start_ix = match ranges.binary_search_by(|probe| {
12087                    let cmp = probe.end.cmp(&left_position, buffer);
12088                    if cmp.is_ge() {
12089                        Ordering::Greater
12090                    } else {
12091                        Ordering::Less
12092                    }
12093                }) {
12094                    Ok(i) | Err(i) => i,
12095                };
12096
12097                ranges[start_ix..]
12098                    .iter()
12099                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12100            })
12101    }
12102
12103    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12104        self.background_highlights
12105            .get(&TypeId::of::<T>())
12106            .map_or(false, |(_, highlights)| !highlights.is_empty())
12107    }
12108
12109    pub fn background_highlights_in_range(
12110        &self,
12111        search_range: Range<Anchor>,
12112        display_snapshot: &DisplaySnapshot,
12113        theme: &ThemeColors,
12114    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12115        let mut results = Vec::new();
12116        for (color_fetcher, ranges) in self.background_highlights.values() {
12117            let color = color_fetcher(theme);
12118            let start_ix = match ranges.binary_search_by(|probe| {
12119                let cmp = probe
12120                    .end
12121                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12122                if cmp.is_gt() {
12123                    Ordering::Greater
12124                } else {
12125                    Ordering::Less
12126                }
12127            }) {
12128                Ok(i) | Err(i) => i,
12129            };
12130            for range in &ranges[start_ix..] {
12131                if range
12132                    .start
12133                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12134                    .is_ge()
12135                {
12136                    break;
12137                }
12138
12139                let start = range.start.to_display_point(display_snapshot);
12140                let end = range.end.to_display_point(display_snapshot);
12141                results.push((start..end, color))
12142            }
12143        }
12144        results
12145    }
12146
12147    pub fn background_highlight_row_ranges<T: 'static>(
12148        &self,
12149        search_range: Range<Anchor>,
12150        display_snapshot: &DisplaySnapshot,
12151        count: usize,
12152    ) -> Vec<RangeInclusive<DisplayPoint>> {
12153        let mut results = Vec::new();
12154        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12155            return vec![];
12156        };
12157
12158        let start_ix = match ranges.binary_search_by(|probe| {
12159            let cmp = probe
12160                .end
12161                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12162            if cmp.is_gt() {
12163                Ordering::Greater
12164            } else {
12165                Ordering::Less
12166            }
12167        }) {
12168            Ok(i) | Err(i) => i,
12169        };
12170        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12171            if let (Some(start_display), Some(end_display)) = (start, end) {
12172                results.push(
12173                    start_display.to_display_point(display_snapshot)
12174                        ..=end_display.to_display_point(display_snapshot),
12175                );
12176            }
12177        };
12178        let mut start_row: Option<Point> = None;
12179        let mut end_row: Option<Point> = None;
12180        if ranges.len() > count {
12181            return Vec::new();
12182        }
12183        for range in &ranges[start_ix..] {
12184            if range
12185                .start
12186                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12187                .is_ge()
12188            {
12189                break;
12190            }
12191            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12192            if let Some(current_row) = &end_row {
12193                if end.row == current_row.row {
12194                    continue;
12195                }
12196            }
12197            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12198            if start_row.is_none() {
12199                assert_eq!(end_row, None);
12200                start_row = Some(start);
12201                end_row = Some(end);
12202                continue;
12203            }
12204            if let Some(current_end) = end_row.as_mut() {
12205                if start.row > current_end.row + 1 {
12206                    push_region(start_row, end_row);
12207                    start_row = Some(start);
12208                    end_row = Some(end);
12209                } else {
12210                    // Merge two hunks.
12211                    *current_end = end;
12212                }
12213            } else {
12214                unreachable!();
12215            }
12216        }
12217        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12218        push_region(start_row, end_row);
12219        results
12220    }
12221
12222    pub fn gutter_highlights_in_range(
12223        &self,
12224        search_range: Range<Anchor>,
12225        display_snapshot: &DisplaySnapshot,
12226        cx: &AppContext,
12227    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12228        let mut results = Vec::new();
12229        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12230            let color = color_fetcher(cx);
12231            let start_ix = match ranges.binary_search_by(|probe| {
12232                let cmp = probe
12233                    .end
12234                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12235                if cmp.is_gt() {
12236                    Ordering::Greater
12237                } else {
12238                    Ordering::Less
12239                }
12240            }) {
12241                Ok(i) | Err(i) => i,
12242            };
12243            for range in &ranges[start_ix..] {
12244                if range
12245                    .start
12246                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12247                    .is_ge()
12248                {
12249                    break;
12250                }
12251
12252                let start = range.start.to_display_point(display_snapshot);
12253                let end = range.end.to_display_point(display_snapshot);
12254                results.push((start..end, color))
12255            }
12256        }
12257        results
12258    }
12259
12260    /// Get the text ranges corresponding to the redaction query
12261    pub fn redacted_ranges(
12262        &self,
12263        search_range: Range<Anchor>,
12264        display_snapshot: &DisplaySnapshot,
12265        cx: &WindowContext,
12266    ) -> Vec<Range<DisplayPoint>> {
12267        display_snapshot
12268            .buffer_snapshot
12269            .redacted_ranges(search_range, |file| {
12270                if let Some(file) = file {
12271                    file.is_private()
12272                        && EditorSettings::get(
12273                            Some(SettingsLocation {
12274                                worktree_id: file.worktree_id(cx),
12275                                path: file.path().as_ref(),
12276                            }),
12277                            cx,
12278                        )
12279                        .redact_private_values
12280                } else {
12281                    false
12282                }
12283            })
12284            .map(|range| {
12285                range.start.to_display_point(display_snapshot)
12286                    ..range.end.to_display_point(display_snapshot)
12287            })
12288            .collect()
12289    }
12290
12291    pub fn highlight_text<T: 'static>(
12292        &mut self,
12293        ranges: Vec<Range<Anchor>>,
12294        style: HighlightStyle,
12295        cx: &mut ViewContext<Self>,
12296    ) {
12297        self.display_map.update(cx, |map, _| {
12298            map.highlight_text(TypeId::of::<T>(), ranges, style)
12299        });
12300        cx.notify();
12301    }
12302
12303    pub(crate) fn highlight_inlays<T: 'static>(
12304        &mut self,
12305        highlights: Vec<InlayHighlight>,
12306        style: HighlightStyle,
12307        cx: &mut ViewContext<Self>,
12308    ) {
12309        self.display_map.update(cx, |map, _| {
12310            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12311        });
12312        cx.notify();
12313    }
12314
12315    pub fn text_highlights<'a, T: 'static>(
12316        &'a self,
12317        cx: &'a AppContext,
12318    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12319        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12320    }
12321
12322    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12323        let cleared = self
12324            .display_map
12325            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12326        if cleared {
12327            cx.notify();
12328        }
12329    }
12330
12331    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12332        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12333            && self.focus_handle.is_focused(cx)
12334    }
12335
12336    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12337        self.show_cursor_when_unfocused = is_enabled;
12338        cx.notify();
12339    }
12340
12341    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12342        self.project
12343            .as_ref()
12344            .map(|project| project.read(cx).lsp_store())
12345    }
12346
12347    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12348        cx.notify();
12349    }
12350
12351    fn on_buffer_event(
12352        &mut self,
12353        multibuffer: Model<MultiBuffer>,
12354        event: &multi_buffer::Event,
12355        cx: &mut ViewContext<Self>,
12356    ) {
12357        match event {
12358            multi_buffer::Event::Edited {
12359                singleton_buffer_edited,
12360                edited_buffer: buffer_edited,
12361            } => {
12362                self.scrollbar_marker_state.dirty = true;
12363                self.active_indent_guides_state.dirty = true;
12364                self.refresh_active_diagnostics(cx);
12365                self.refresh_code_actions(cx);
12366                if self.has_active_inline_completion() {
12367                    self.update_visible_inline_completion(cx);
12368                }
12369                if let Some(buffer) = buffer_edited {
12370                    let buffer_id = buffer.read(cx).remote_id();
12371                    if !self.registered_buffers.contains_key(&buffer_id) {
12372                        if let Some(lsp_store) = self.lsp_store(cx) {
12373                            lsp_store.update(cx, |lsp_store, cx| {
12374                                self.registered_buffers.insert(
12375                                    buffer_id,
12376                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12377                                );
12378                            })
12379                        }
12380                    }
12381                }
12382                cx.emit(EditorEvent::BufferEdited);
12383                cx.emit(SearchEvent::MatchesInvalidated);
12384                if *singleton_buffer_edited {
12385                    if let Some(project) = &self.project {
12386                        let project = project.read(cx);
12387                        #[allow(clippy::mutable_key_type)]
12388                        let languages_affected = multibuffer
12389                            .read(cx)
12390                            .all_buffers()
12391                            .into_iter()
12392                            .filter_map(|buffer| {
12393                                let buffer = buffer.read(cx);
12394                                let language = buffer.language()?;
12395                                if project.is_local()
12396                                    && project
12397                                        .language_servers_for_local_buffer(buffer, cx)
12398                                        .count()
12399                                        == 0
12400                                {
12401                                    None
12402                                } else {
12403                                    Some(language)
12404                                }
12405                            })
12406                            .cloned()
12407                            .collect::<HashSet<_>>();
12408                        if !languages_affected.is_empty() {
12409                            self.refresh_inlay_hints(
12410                                InlayHintRefreshReason::BufferEdited(languages_affected),
12411                                cx,
12412                            );
12413                        }
12414                    }
12415                }
12416
12417                let Some(project) = &self.project else { return };
12418                let (telemetry, is_via_ssh) = {
12419                    let project = project.read(cx);
12420                    let telemetry = project.client().telemetry().clone();
12421                    let is_via_ssh = project.is_via_ssh();
12422                    (telemetry, is_via_ssh)
12423                };
12424                refresh_linked_ranges(self, cx);
12425                telemetry.log_edit_event("editor", is_via_ssh);
12426            }
12427            multi_buffer::Event::ExcerptsAdded {
12428                buffer,
12429                predecessor,
12430                excerpts,
12431            } => {
12432                self.tasks_update_task = Some(self.refresh_runnables(cx));
12433                let buffer_id = buffer.read(cx).remote_id();
12434                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12435                    if let Some(project) = &self.project {
12436                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12437                    }
12438                }
12439                cx.emit(EditorEvent::ExcerptsAdded {
12440                    buffer: buffer.clone(),
12441                    predecessor: *predecessor,
12442                    excerpts: excerpts.clone(),
12443                });
12444                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12445            }
12446            multi_buffer::Event::ExcerptsRemoved { ids } => {
12447                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12448                let buffer = self.buffer.read(cx);
12449                self.registered_buffers
12450                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12451                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12452            }
12453            multi_buffer::Event::ExcerptsEdited { ids } => {
12454                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12455            }
12456            multi_buffer::Event::ExcerptsExpanded { ids } => {
12457                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12458            }
12459            multi_buffer::Event::Reparsed(buffer_id) => {
12460                self.tasks_update_task = Some(self.refresh_runnables(cx));
12461
12462                cx.emit(EditorEvent::Reparsed(*buffer_id));
12463            }
12464            multi_buffer::Event::LanguageChanged(buffer_id) => {
12465                linked_editing_ranges::refresh_linked_ranges(self, cx);
12466                cx.emit(EditorEvent::Reparsed(*buffer_id));
12467                cx.notify();
12468            }
12469            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12470            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12471            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12472                cx.emit(EditorEvent::TitleChanged)
12473            }
12474            // multi_buffer::Event::DiffBaseChanged => {
12475            //     self.scrollbar_marker_state.dirty = true;
12476            //     cx.emit(EditorEvent::DiffBaseChanged);
12477            //     cx.notify();
12478            // }
12479            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12480            multi_buffer::Event::DiagnosticsUpdated => {
12481                self.refresh_active_diagnostics(cx);
12482                self.scrollbar_marker_state.dirty = true;
12483                cx.notify();
12484            }
12485            _ => {}
12486        };
12487    }
12488
12489    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12490        cx.notify();
12491    }
12492
12493    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12494        self.tasks_update_task = Some(self.refresh_runnables(cx));
12495        self.refresh_inline_completion(true, false, cx);
12496        self.refresh_inlay_hints(
12497            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12498                self.selections.newest_anchor().head(),
12499                &self.buffer.read(cx).snapshot(cx),
12500                cx,
12501            )),
12502            cx,
12503        );
12504
12505        let old_cursor_shape = self.cursor_shape;
12506
12507        {
12508            let editor_settings = EditorSettings::get_global(cx);
12509            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12510            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12511            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12512        }
12513
12514        if old_cursor_shape != self.cursor_shape {
12515            cx.emit(EditorEvent::CursorShapeChanged);
12516        }
12517
12518        let project_settings = ProjectSettings::get_global(cx);
12519        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12520
12521        if self.mode == EditorMode::Full {
12522            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12523            if self.git_blame_inline_enabled != inline_blame_enabled {
12524                self.toggle_git_blame_inline_internal(false, cx);
12525            }
12526        }
12527
12528        cx.notify();
12529    }
12530
12531    pub fn set_searchable(&mut self, searchable: bool) {
12532        self.searchable = searchable;
12533    }
12534
12535    pub fn searchable(&self) -> bool {
12536        self.searchable
12537    }
12538
12539    fn open_proposed_changes_editor(
12540        &mut self,
12541        _: &OpenProposedChangesEditor,
12542        cx: &mut ViewContext<Self>,
12543    ) {
12544        let Some(workspace) = self.workspace() else {
12545            cx.propagate();
12546            return;
12547        };
12548
12549        let selections = self.selections.all::<usize>(cx);
12550        let multi_buffer = self.buffer.read(cx);
12551        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12552        let mut new_selections_by_buffer = HashMap::default();
12553        for selection in selections {
12554            for (excerpt, range) in
12555                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12556            {
12557                let mut range = range.to_point(excerpt.buffer());
12558                range.start.column = 0;
12559                range.end.column = excerpt.buffer().line_len(range.end.row);
12560                new_selections_by_buffer
12561                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12562                    .or_insert(Vec::new())
12563                    .push(range)
12564            }
12565        }
12566
12567        let proposed_changes_buffers = new_selections_by_buffer
12568            .into_iter()
12569            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12570            .collect::<Vec<_>>();
12571        let proposed_changes_editor = cx.new_view(|cx| {
12572            ProposedChangesEditor::new(
12573                "Proposed changes",
12574                proposed_changes_buffers,
12575                self.project.clone(),
12576                cx,
12577            )
12578        });
12579
12580        cx.window_context().defer(move |cx| {
12581            workspace.update(cx, |workspace, cx| {
12582                workspace.active_pane().update(cx, |pane, cx| {
12583                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12584                });
12585            });
12586        });
12587    }
12588
12589    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12590        self.open_excerpts_common(None, true, cx)
12591    }
12592
12593    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12594        self.open_excerpts_common(None, false, cx)
12595    }
12596
12597    fn open_excerpts_common(
12598        &mut self,
12599        jump_data: Option<JumpData>,
12600        split: bool,
12601        cx: &mut ViewContext<Self>,
12602    ) {
12603        let Some(workspace) = self.workspace() else {
12604            cx.propagate();
12605            return;
12606        };
12607
12608        if self.buffer.read(cx).is_singleton() {
12609            cx.propagate();
12610            return;
12611        }
12612
12613        let mut new_selections_by_buffer = HashMap::default();
12614        match &jump_data {
12615            Some(JumpData::MultiBufferPoint {
12616                excerpt_id,
12617                position,
12618                anchor,
12619                line_offset_from_top,
12620            }) => {
12621                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12622                if let Some(buffer) = multi_buffer_snapshot
12623                    .buffer_id_for_excerpt(*excerpt_id)
12624                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12625                {
12626                    let buffer_snapshot = buffer.read(cx).snapshot();
12627                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12628                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12629                    } else {
12630                        buffer_snapshot.clip_point(*position, Bias::Left)
12631                    };
12632                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12633                    new_selections_by_buffer.insert(
12634                        buffer,
12635                        (
12636                            vec![jump_to_offset..jump_to_offset],
12637                            Some(*line_offset_from_top),
12638                        ),
12639                    );
12640                }
12641            }
12642            Some(JumpData::MultiBufferRow {
12643                row,
12644                line_offset_from_top,
12645            }) => {
12646                let point = MultiBufferPoint::new(row.0, 0);
12647                if let Some((buffer, buffer_point, _)) =
12648                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12649                {
12650                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12651                    new_selections_by_buffer
12652                        .entry(buffer)
12653                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12654                        .0
12655                        .push(buffer_offset..buffer_offset)
12656                }
12657            }
12658            None => {
12659                let selections = self.selections.all::<usize>(cx);
12660                let multi_buffer = self.buffer.read(cx);
12661                for selection in selections {
12662                    for (excerpt, mut range) in multi_buffer
12663                        .snapshot(cx)
12664                        .range_to_buffer_ranges(selection.range())
12665                    {
12666                        // When editing branch buffers, jump to the corresponding location
12667                        // in their base buffer.
12668                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12669                        let buffer = buffer_handle.read(cx);
12670                        if let Some(base_buffer) = buffer.base_buffer() {
12671                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12672                            buffer_handle = base_buffer;
12673                        }
12674
12675                        if selection.reversed {
12676                            mem::swap(&mut range.start, &mut range.end);
12677                        }
12678                        new_selections_by_buffer
12679                            .entry(buffer_handle)
12680                            .or_insert((Vec::new(), None))
12681                            .0
12682                            .push(range)
12683                    }
12684                }
12685            }
12686        }
12687
12688        if new_selections_by_buffer.is_empty() {
12689            return;
12690        }
12691
12692        // We defer the pane interaction because we ourselves are a workspace item
12693        // and activating a new item causes the pane to call a method on us reentrantly,
12694        // which panics if we're on the stack.
12695        cx.window_context().defer(move |cx| {
12696            workspace.update(cx, |workspace, cx| {
12697                let pane = if split {
12698                    workspace.adjacent_pane(cx)
12699                } else {
12700                    workspace.active_pane().clone()
12701                };
12702
12703                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12704                    let editor = buffer
12705                        .read(cx)
12706                        .file()
12707                        .is_none()
12708                        .then(|| {
12709                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12710                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12711                            // Instead, we try to activate the existing editor in the pane first.
12712                            let (editor, pane_item_index) =
12713                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12714                                    let editor = item.downcast::<Editor>()?;
12715                                    let singleton_buffer =
12716                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12717                                    if singleton_buffer == buffer {
12718                                        Some((editor, i))
12719                                    } else {
12720                                        None
12721                                    }
12722                                })?;
12723                            pane.update(cx, |pane, cx| {
12724                                pane.activate_item(pane_item_index, true, true, cx)
12725                            });
12726                            Some(editor)
12727                        })
12728                        .flatten()
12729                        .unwrap_or_else(|| {
12730                            workspace.open_project_item::<Self>(
12731                                pane.clone(),
12732                                buffer,
12733                                true,
12734                                true,
12735                                cx,
12736                            )
12737                        });
12738
12739                    editor.update(cx, |editor, cx| {
12740                        let autoscroll = match scroll_offset {
12741                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12742                            None => Autoscroll::newest(),
12743                        };
12744                        let nav_history = editor.nav_history.take();
12745                        editor.change_selections(Some(autoscroll), cx, |s| {
12746                            s.select_ranges(ranges);
12747                        });
12748                        editor.nav_history = nav_history;
12749                    });
12750                }
12751            })
12752        });
12753    }
12754
12755    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12756        let snapshot = self.buffer.read(cx).read(cx);
12757        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12758        Some(
12759            ranges
12760                .iter()
12761                .map(move |range| {
12762                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12763                })
12764                .collect(),
12765        )
12766    }
12767
12768    fn selection_replacement_ranges(
12769        &self,
12770        range: Range<OffsetUtf16>,
12771        cx: &mut AppContext,
12772    ) -> Vec<Range<OffsetUtf16>> {
12773        let selections = self.selections.all::<OffsetUtf16>(cx);
12774        let newest_selection = selections
12775            .iter()
12776            .max_by_key(|selection| selection.id)
12777            .unwrap();
12778        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12779        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12780        let snapshot = self.buffer.read(cx).read(cx);
12781        selections
12782            .into_iter()
12783            .map(|mut selection| {
12784                selection.start.0 =
12785                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12786                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12787                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12788                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12789            })
12790            .collect()
12791    }
12792
12793    fn report_editor_event(
12794        &self,
12795        event_type: &'static str,
12796        file_extension: Option<String>,
12797        cx: &AppContext,
12798    ) {
12799        if cfg!(any(test, feature = "test-support")) {
12800            return;
12801        }
12802
12803        let Some(project) = &self.project else { return };
12804
12805        // If None, we are in a file without an extension
12806        let file = self
12807            .buffer
12808            .read(cx)
12809            .as_singleton()
12810            .and_then(|b| b.read(cx).file());
12811        let file_extension = file_extension.or(file
12812            .as_ref()
12813            .and_then(|file| Path::new(file.file_name(cx)).extension())
12814            .and_then(|e| e.to_str())
12815            .map(|a| a.to_string()));
12816
12817        let vim_mode = cx
12818            .global::<SettingsStore>()
12819            .raw_user_settings()
12820            .get("vim_mode")
12821            == Some(&serde_json::Value::Bool(true));
12822
12823        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12824            == language::language_settings::InlineCompletionProvider::Copilot;
12825        let copilot_enabled_for_language = self
12826            .buffer
12827            .read(cx)
12828            .settings_at(0, cx)
12829            .show_inline_completions;
12830
12831        let project = project.read(cx);
12832        telemetry::event!(
12833            event_type,
12834            file_extension,
12835            vim_mode,
12836            copilot_enabled,
12837            copilot_enabled_for_language,
12838            is_via_ssh = project.is_via_ssh(),
12839        );
12840    }
12841
12842    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12843    /// with each line being an array of {text, highlight} objects.
12844    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12845        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12846            return;
12847        };
12848
12849        #[derive(Serialize)]
12850        struct Chunk<'a> {
12851            text: String,
12852            highlight: Option<&'a str>,
12853        }
12854
12855        let snapshot = buffer.read(cx).snapshot();
12856        let range = self
12857            .selected_text_range(false, cx)
12858            .and_then(|selection| {
12859                if selection.range.is_empty() {
12860                    None
12861                } else {
12862                    Some(selection.range)
12863                }
12864            })
12865            .unwrap_or_else(|| 0..snapshot.len());
12866
12867        let chunks = snapshot.chunks(range, true);
12868        let mut lines = Vec::new();
12869        let mut line: VecDeque<Chunk> = VecDeque::new();
12870
12871        let Some(style) = self.style.as_ref() else {
12872            return;
12873        };
12874
12875        for chunk in chunks {
12876            let highlight = chunk
12877                .syntax_highlight_id
12878                .and_then(|id| id.name(&style.syntax));
12879            let mut chunk_lines = chunk.text.split('\n').peekable();
12880            while let Some(text) = chunk_lines.next() {
12881                let mut merged_with_last_token = false;
12882                if let Some(last_token) = line.back_mut() {
12883                    if last_token.highlight == highlight {
12884                        last_token.text.push_str(text);
12885                        merged_with_last_token = true;
12886                    }
12887                }
12888
12889                if !merged_with_last_token {
12890                    line.push_back(Chunk {
12891                        text: text.into(),
12892                        highlight,
12893                    });
12894                }
12895
12896                if chunk_lines.peek().is_some() {
12897                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12898                        line.pop_front();
12899                    }
12900                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12901                        line.pop_back();
12902                    }
12903
12904                    lines.push(mem::take(&mut line));
12905                }
12906            }
12907        }
12908
12909        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12910            return;
12911        };
12912        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12913    }
12914
12915    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12916        self.request_autoscroll(Autoscroll::newest(), cx);
12917        let position = self.selections.newest_display(cx).start;
12918        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12919    }
12920
12921    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12922        &self.inlay_hint_cache
12923    }
12924
12925    pub fn replay_insert_event(
12926        &mut self,
12927        text: &str,
12928        relative_utf16_range: Option<Range<isize>>,
12929        cx: &mut ViewContext<Self>,
12930    ) {
12931        if !self.input_enabled {
12932            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12933            return;
12934        }
12935        if let Some(relative_utf16_range) = relative_utf16_range {
12936            let selections = self.selections.all::<OffsetUtf16>(cx);
12937            self.change_selections(None, cx, |s| {
12938                let new_ranges = selections.into_iter().map(|range| {
12939                    let start = OffsetUtf16(
12940                        range
12941                            .head()
12942                            .0
12943                            .saturating_add_signed(relative_utf16_range.start),
12944                    );
12945                    let end = OffsetUtf16(
12946                        range
12947                            .head()
12948                            .0
12949                            .saturating_add_signed(relative_utf16_range.end),
12950                    );
12951                    start..end
12952                });
12953                s.select_ranges(new_ranges);
12954            });
12955        }
12956
12957        self.handle_input(text, cx);
12958    }
12959
12960    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12961        let Some(provider) = self.semantics_provider.as_ref() else {
12962            return false;
12963        };
12964
12965        let mut supports = false;
12966        self.buffer().read(cx).for_each_buffer(|buffer| {
12967            supports |= provider.supports_inlay_hints(buffer, cx);
12968        });
12969        supports
12970    }
12971
12972    pub fn focus(&self, cx: &mut WindowContext) {
12973        cx.focus(&self.focus_handle)
12974    }
12975
12976    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12977        self.focus_handle.is_focused(cx)
12978    }
12979
12980    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12981        cx.emit(EditorEvent::Focused);
12982
12983        if let Some(descendant) = self
12984            .last_focused_descendant
12985            .take()
12986            .and_then(|descendant| descendant.upgrade())
12987        {
12988            cx.focus(&descendant);
12989        } else {
12990            if let Some(blame) = self.blame.as_ref() {
12991                blame.update(cx, GitBlame::focus)
12992            }
12993
12994            self.blink_manager.update(cx, BlinkManager::enable);
12995            self.show_cursor_names(cx);
12996            self.buffer.update(cx, |buffer, cx| {
12997                buffer.finalize_last_transaction(cx);
12998                if self.leader_peer_id.is_none() {
12999                    buffer.set_active_selections(
13000                        &self.selections.disjoint_anchors(),
13001                        self.selections.line_mode,
13002                        self.cursor_shape,
13003                        cx,
13004                    );
13005                }
13006            });
13007        }
13008    }
13009
13010    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13011        cx.emit(EditorEvent::FocusedIn)
13012    }
13013
13014    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13015        if event.blurred != self.focus_handle {
13016            self.last_focused_descendant = Some(event.blurred);
13017        }
13018    }
13019
13020    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13021        self.blink_manager.update(cx, BlinkManager::disable);
13022        self.buffer
13023            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13024
13025        if let Some(blame) = self.blame.as_ref() {
13026            blame.update(cx, GitBlame::blur)
13027        }
13028        if !self.hover_state.focused(cx) {
13029            hide_hover(self, cx);
13030        }
13031
13032        self.hide_context_menu(cx);
13033        cx.emit(EditorEvent::Blurred);
13034        cx.notify();
13035    }
13036
13037    pub fn register_action<A: Action>(
13038        &mut self,
13039        listener: impl Fn(&A, &mut WindowContext) + 'static,
13040    ) -> Subscription {
13041        let id = self.next_editor_action_id.post_inc();
13042        let listener = Arc::new(listener);
13043        self.editor_actions.borrow_mut().insert(
13044            id,
13045            Box::new(move |cx| {
13046                let cx = cx.window_context();
13047                let listener = listener.clone();
13048                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13049                    let action = action.downcast_ref().unwrap();
13050                    if phase == DispatchPhase::Bubble {
13051                        listener(action, cx)
13052                    }
13053                })
13054            }),
13055        );
13056
13057        let editor_actions = self.editor_actions.clone();
13058        Subscription::new(move || {
13059            editor_actions.borrow_mut().remove(&id);
13060        })
13061    }
13062
13063    pub fn file_header_size(&self) -> u32 {
13064        FILE_HEADER_HEIGHT
13065    }
13066
13067    pub fn revert(
13068        &mut self,
13069        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13070        cx: &mut ViewContext<Self>,
13071    ) {
13072        self.buffer().update(cx, |multi_buffer, cx| {
13073            for (buffer_id, changes) in revert_changes {
13074                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13075                    buffer.update(cx, |buffer, cx| {
13076                        buffer.edit(
13077                            changes.into_iter().map(|(range, text)| {
13078                                (range, text.to_string().map(Arc::<str>::from))
13079                            }),
13080                            None,
13081                            cx,
13082                        );
13083                    });
13084                }
13085            }
13086        });
13087        self.change_selections(None, cx, |selections| selections.refresh());
13088    }
13089
13090    pub fn to_pixel_point(
13091        &mut self,
13092        source: multi_buffer::Anchor,
13093        editor_snapshot: &EditorSnapshot,
13094        cx: &mut ViewContext<Self>,
13095    ) -> Option<gpui::Point<Pixels>> {
13096        let source_point = source.to_display_point(editor_snapshot);
13097        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13098    }
13099
13100    pub fn display_to_pixel_point(
13101        &self,
13102        source: DisplayPoint,
13103        editor_snapshot: &EditorSnapshot,
13104        cx: &WindowContext,
13105    ) -> Option<gpui::Point<Pixels>> {
13106        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13107        let text_layout_details = self.text_layout_details(cx);
13108        let scroll_top = text_layout_details
13109            .scroll_anchor
13110            .scroll_position(editor_snapshot)
13111            .y;
13112
13113        if source.row().as_f32() < scroll_top.floor() {
13114            return None;
13115        }
13116        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13117        let source_y = line_height * (source.row().as_f32() - scroll_top);
13118        Some(gpui::Point::new(source_x, source_y))
13119    }
13120
13121    pub fn has_active_completions_menu(&self) -> bool {
13122        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13123            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13124        })
13125    }
13126
13127    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13128        self.addons
13129            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13130    }
13131
13132    pub fn unregister_addon<T: Addon>(&mut self) {
13133        self.addons.remove(&std::any::TypeId::of::<T>());
13134    }
13135
13136    pub fn addon<T: Addon>(&self) -> Option<&T> {
13137        let type_id = std::any::TypeId::of::<T>();
13138        self.addons
13139            .get(&type_id)
13140            .and_then(|item| item.to_any().downcast_ref::<T>())
13141    }
13142
13143    pub fn add_change_set(
13144        &mut self,
13145        change_set: Model<BufferChangeSet>,
13146        cx: &mut ViewContext<Self>,
13147    ) {
13148        self.diff_map.add_change_set(change_set, cx);
13149    }
13150
13151    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13152        let text_layout_details = self.text_layout_details(cx);
13153        let style = &text_layout_details.editor_style;
13154        let font_id = cx.text_system().resolve_font(&style.text.font());
13155        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13156        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13157
13158        let em_width = cx
13159            .text_system()
13160            .typographic_bounds(font_id, font_size, 'm')
13161            .unwrap()
13162            .size
13163            .width;
13164
13165        gpui::Point::new(em_width, line_height)
13166    }
13167}
13168
13169fn get_unstaged_changes_for_buffers(
13170    project: &Model<Project>,
13171    buffers: impl IntoIterator<Item = Model<Buffer>>,
13172    cx: &mut ViewContext<Editor>,
13173) {
13174    let mut tasks = Vec::new();
13175    project.update(cx, |project, cx| {
13176        for buffer in buffers {
13177            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13178        }
13179    });
13180    cx.spawn(|this, mut cx| async move {
13181        let change_sets = futures::future::join_all(tasks).await;
13182        this.update(&mut cx, |this, cx| {
13183            for change_set in change_sets {
13184                if let Some(change_set) = change_set.log_err() {
13185                    this.diff_map.add_change_set(change_set, cx);
13186                }
13187            }
13188        })
13189        .ok();
13190    })
13191    .detach();
13192}
13193
13194fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13195    let tab_size = tab_size.get() as usize;
13196    let mut width = offset;
13197
13198    for ch in text.chars() {
13199        width += if ch == '\t' {
13200            tab_size - (width % tab_size)
13201        } else {
13202            1
13203        };
13204    }
13205
13206    width - offset
13207}
13208
13209#[cfg(test)]
13210mod tests {
13211    use super::*;
13212
13213    #[test]
13214    fn test_string_size_with_expanded_tabs() {
13215        let nz = |val| NonZeroU32::new(val).unwrap();
13216        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13217        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13218        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13219        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13220        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13221        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13222        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13223        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13224    }
13225}
13226
13227/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13228struct WordBreakingTokenizer<'a> {
13229    input: &'a str,
13230}
13231
13232impl<'a> WordBreakingTokenizer<'a> {
13233    fn new(input: &'a str) -> Self {
13234        Self { input }
13235    }
13236}
13237
13238fn is_char_ideographic(ch: char) -> bool {
13239    use unicode_script::Script::*;
13240    use unicode_script::UnicodeScript;
13241    matches!(ch.script(), Han | Tangut | Yi)
13242}
13243
13244fn is_grapheme_ideographic(text: &str) -> bool {
13245    text.chars().any(is_char_ideographic)
13246}
13247
13248fn is_grapheme_whitespace(text: &str) -> bool {
13249    text.chars().any(|x| x.is_whitespace())
13250}
13251
13252fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13253    text.chars().next().map_or(false, |ch| {
13254        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13255    })
13256}
13257
13258#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13259struct WordBreakToken<'a> {
13260    token: &'a str,
13261    grapheme_len: usize,
13262    is_whitespace: bool,
13263}
13264
13265impl<'a> Iterator for WordBreakingTokenizer<'a> {
13266    /// Yields a span, the count of graphemes in the token, and whether it was
13267    /// whitespace. Note that it also breaks at word boundaries.
13268    type Item = WordBreakToken<'a>;
13269
13270    fn next(&mut self) -> Option<Self::Item> {
13271        use unicode_segmentation::UnicodeSegmentation;
13272        if self.input.is_empty() {
13273            return None;
13274        }
13275
13276        let mut iter = self.input.graphemes(true).peekable();
13277        let mut offset = 0;
13278        let mut graphemes = 0;
13279        if let Some(first_grapheme) = iter.next() {
13280            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13281            offset += first_grapheme.len();
13282            graphemes += 1;
13283            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13284                if let Some(grapheme) = iter.peek().copied() {
13285                    if should_stay_with_preceding_ideograph(grapheme) {
13286                        offset += grapheme.len();
13287                        graphemes += 1;
13288                    }
13289                }
13290            } else {
13291                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13292                let mut next_word_bound = words.peek().copied();
13293                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13294                    next_word_bound = words.next();
13295                }
13296                while let Some(grapheme) = iter.peek().copied() {
13297                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13298                        break;
13299                    };
13300                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13301                        break;
13302                    };
13303                    offset += grapheme.len();
13304                    graphemes += 1;
13305                    iter.next();
13306                }
13307            }
13308            let token = &self.input[..offset];
13309            self.input = &self.input[offset..];
13310            if is_whitespace {
13311                Some(WordBreakToken {
13312                    token: " ",
13313                    grapheme_len: 1,
13314                    is_whitespace: true,
13315                })
13316            } else {
13317                Some(WordBreakToken {
13318                    token,
13319                    grapheme_len: graphemes,
13320                    is_whitespace: false,
13321                })
13322            }
13323        } else {
13324            None
13325        }
13326    }
13327}
13328
13329#[test]
13330fn test_word_breaking_tokenizer() {
13331    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13332        ("", &[]),
13333        ("  ", &[(" ", 1, true)]),
13334        ("Ʒ", &[("Ʒ", 1, false)]),
13335        ("Ǽ", &[("Ǽ", 1, false)]),
13336        ("", &[("", 1, false)]),
13337        ("⋑⋑", &[("⋑⋑", 2, false)]),
13338        (
13339            "原理,进而",
13340            &[
13341                ("", 1, false),
13342                ("理,", 2, false),
13343                ("", 1, false),
13344                ("", 1, false),
13345            ],
13346        ),
13347        (
13348            "hello world",
13349            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13350        ),
13351        (
13352            "hello, world",
13353            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13354        ),
13355        (
13356            "  hello world",
13357            &[
13358                (" ", 1, true),
13359                ("hello", 5, false),
13360                (" ", 1, true),
13361                ("world", 5, false),
13362            ],
13363        ),
13364        (
13365            "这是什么 \n 钢笔",
13366            &[
13367                ("", 1, false),
13368                ("", 1, false),
13369                ("", 1, false),
13370                ("", 1, false),
13371                (" ", 1, true),
13372                ("", 1, false),
13373                ("", 1, false),
13374            ],
13375        ),
13376        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13377    ];
13378
13379    for (input, result) in tests {
13380        assert_eq!(
13381            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13382            result
13383                .iter()
13384                .copied()
13385                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13386                    token,
13387                    grapheme_len,
13388                    is_whitespace,
13389                })
13390                .collect::<Vec<_>>()
13391        );
13392    }
13393}
13394
13395fn wrap_with_prefix(
13396    line_prefix: String,
13397    unwrapped_text: String,
13398    wrap_column: usize,
13399    tab_size: NonZeroU32,
13400) -> String {
13401    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13402    let mut wrapped_text = String::new();
13403    let mut current_line = line_prefix.clone();
13404
13405    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13406    let mut current_line_len = line_prefix_len;
13407    for WordBreakToken {
13408        token,
13409        grapheme_len,
13410        is_whitespace,
13411    } in tokenizer
13412    {
13413        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13414            wrapped_text.push_str(current_line.trim_end());
13415            wrapped_text.push('\n');
13416            current_line.truncate(line_prefix.len());
13417            current_line_len = line_prefix_len;
13418            if !is_whitespace {
13419                current_line.push_str(token);
13420                current_line_len += grapheme_len;
13421            }
13422        } else if !is_whitespace {
13423            current_line.push_str(token);
13424            current_line_len += grapheme_len;
13425        } else if current_line_len != line_prefix_len {
13426            current_line.push(' ');
13427            current_line_len += 1;
13428        }
13429    }
13430
13431    if !current_line.is_empty() {
13432        wrapped_text.push_str(&current_line);
13433    }
13434    wrapped_text
13435}
13436
13437#[test]
13438fn test_wrap_with_prefix() {
13439    assert_eq!(
13440        wrap_with_prefix(
13441            "# ".to_string(),
13442            "abcdefg".to_string(),
13443            4,
13444            NonZeroU32::new(4).unwrap()
13445        ),
13446        "# abcdefg"
13447    );
13448    assert_eq!(
13449        wrap_with_prefix(
13450            "".to_string(),
13451            "\thello world".to_string(),
13452            8,
13453            NonZeroU32::new(4).unwrap()
13454        ),
13455        "hello\nworld"
13456    );
13457    assert_eq!(
13458        wrap_with_prefix(
13459            "// ".to_string(),
13460            "xx \nyy zz aa bb cc".to_string(),
13461            12,
13462            NonZeroU32::new(4).unwrap()
13463        ),
13464        "// xx yy zz\n// aa bb cc"
13465    );
13466    assert_eq!(
13467        wrap_with_prefix(
13468            String::new(),
13469            "这是什么 \n 钢笔".to_string(),
13470            3,
13471            NonZeroU32::new(4).unwrap()
13472        ),
13473        "这是什\n么 钢\n"
13474    );
13475}
13476
13477fn hunks_for_selections(
13478    snapshot: &EditorSnapshot,
13479    selections: &[Selection<Point>],
13480) -> Vec<MultiBufferDiffHunk> {
13481    hunks_for_ranges(
13482        selections.iter().map(|selection| selection.range()),
13483        snapshot,
13484    )
13485}
13486
13487pub fn hunks_for_ranges(
13488    ranges: impl Iterator<Item = Range<Point>>,
13489    snapshot: &EditorSnapshot,
13490) -> Vec<MultiBufferDiffHunk> {
13491    let mut hunks = Vec::new();
13492    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13493        HashMap::default();
13494    for query_range in ranges {
13495        let query_rows =
13496            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13497        for hunk in snapshot.diff_map.diff_hunks_in_range(
13498            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13499            &snapshot.buffer_snapshot,
13500        ) {
13501            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13502            // when the caret is just above or just below the deleted hunk.
13503            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13504            let related_to_selection = if allow_adjacent {
13505                hunk.row_range.overlaps(&query_rows)
13506                    || hunk.row_range.start == query_rows.end
13507                    || hunk.row_range.end == query_rows.start
13508            } else {
13509                hunk.row_range.overlaps(&query_rows)
13510            };
13511            if related_to_selection {
13512                if !processed_buffer_rows
13513                    .entry(hunk.buffer_id)
13514                    .or_default()
13515                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13516                {
13517                    continue;
13518                }
13519                hunks.push(hunk);
13520            }
13521        }
13522    }
13523
13524    hunks
13525}
13526
13527pub trait CollaborationHub {
13528    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13529    fn user_participant_indices<'a>(
13530        &self,
13531        cx: &'a AppContext,
13532    ) -> &'a HashMap<u64, ParticipantIndex>;
13533    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13534}
13535
13536impl CollaborationHub for Model<Project> {
13537    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13538        self.read(cx).collaborators()
13539    }
13540
13541    fn user_participant_indices<'a>(
13542        &self,
13543        cx: &'a AppContext,
13544    ) -> &'a HashMap<u64, ParticipantIndex> {
13545        self.read(cx).user_store().read(cx).participant_indices()
13546    }
13547
13548    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13549        let this = self.read(cx);
13550        let user_ids = this.collaborators().values().map(|c| c.user_id);
13551        this.user_store().read_with(cx, |user_store, cx| {
13552            user_store.participant_names(user_ids, cx)
13553        })
13554    }
13555}
13556
13557pub trait SemanticsProvider {
13558    fn hover(
13559        &self,
13560        buffer: &Model<Buffer>,
13561        position: text::Anchor,
13562        cx: &mut AppContext,
13563    ) -> Option<Task<Vec<project::Hover>>>;
13564
13565    fn inlay_hints(
13566        &self,
13567        buffer_handle: Model<Buffer>,
13568        range: Range<text::Anchor>,
13569        cx: &mut AppContext,
13570    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13571
13572    fn resolve_inlay_hint(
13573        &self,
13574        hint: InlayHint,
13575        buffer_handle: Model<Buffer>,
13576        server_id: LanguageServerId,
13577        cx: &mut AppContext,
13578    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13579
13580    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13581
13582    fn document_highlights(
13583        &self,
13584        buffer: &Model<Buffer>,
13585        position: text::Anchor,
13586        cx: &mut AppContext,
13587    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13588
13589    fn definitions(
13590        &self,
13591        buffer: &Model<Buffer>,
13592        position: text::Anchor,
13593        kind: GotoDefinitionKind,
13594        cx: &mut AppContext,
13595    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13596
13597    fn range_for_rename(
13598        &self,
13599        buffer: &Model<Buffer>,
13600        position: text::Anchor,
13601        cx: &mut AppContext,
13602    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13603
13604    fn perform_rename(
13605        &self,
13606        buffer: &Model<Buffer>,
13607        position: text::Anchor,
13608        new_name: String,
13609        cx: &mut AppContext,
13610    ) -> Option<Task<Result<ProjectTransaction>>>;
13611}
13612
13613pub trait CompletionProvider {
13614    fn completions(
13615        &self,
13616        buffer: &Model<Buffer>,
13617        buffer_position: text::Anchor,
13618        trigger: CompletionContext,
13619        cx: &mut ViewContext<Editor>,
13620    ) -> Task<Result<Vec<Completion>>>;
13621
13622    fn resolve_completions(
13623        &self,
13624        buffer: Model<Buffer>,
13625        completion_indices: Vec<usize>,
13626        completions: Rc<RefCell<Box<[Completion]>>>,
13627        cx: &mut ViewContext<Editor>,
13628    ) -> Task<Result<bool>>;
13629
13630    fn apply_additional_edits_for_completion(
13631        &self,
13632        _buffer: Model<Buffer>,
13633        _completions: Rc<RefCell<Box<[Completion]>>>,
13634        _completion_index: usize,
13635        _push_to_history: bool,
13636        _cx: &mut ViewContext<Editor>,
13637    ) -> Task<Result<Option<language::Transaction>>> {
13638        Task::ready(Ok(None))
13639    }
13640
13641    fn is_completion_trigger(
13642        &self,
13643        buffer: &Model<Buffer>,
13644        position: language::Anchor,
13645        text: &str,
13646        trigger_in_words: bool,
13647        cx: &mut ViewContext<Editor>,
13648    ) -> bool;
13649
13650    fn sort_completions(&self) -> bool {
13651        true
13652    }
13653}
13654
13655pub trait CodeActionProvider {
13656    fn id(&self) -> Arc<str>;
13657
13658    fn code_actions(
13659        &self,
13660        buffer: &Model<Buffer>,
13661        range: Range<text::Anchor>,
13662        cx: &mut WindowContext,
13663    ) -> Task<Result<Vec<CodeAction>>>;
13664
13665    fn apply_code_action(
13666        &self,
13667        buffer_handle: Model<Buffer>,
13668        action: CodeAction,
13669        excerpt_id: ExcerptId,
13670        push_to_history: bool,
13671        cx: &mut WindowContext,
13672    ) -> Task<Result<ProjectTransaction>>;
13673}
13674
13675impl CodeActionProvider for Model<Project> {
13676    fn id(&self) -> Arc<str> {
13677        "project".into()
13678    }
13679
13680    fn code_actions(
13681        &self,
13682        buffer: &Model<Buffer>,
13683        range: Range<text::Anchor>,
13684        cx: &mut WindowContext,
13685    ) -> Task<Result<Vec<CodeAction>>> {
13686        self.update(cx, |project, cx| {
13687            project.code_actions(buffer, range, None, cx)
13688        })
13689    }
13690
13691    fn apply_code_action(
13692        &self,
13693        buffer_handle: Model<Buffer>,
13694        action: CodeAction,
13695        _excerpt_id: ExcerptId,
13696        push_to_history: bool,
13697        cx: &mut WindowContext,
13698    ) -> Task<Result<ProjectTransaction>> {
13699        self.update(cx, |project, cx| {
13700            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13701        })
13702    }
13703}
13704
13705fn snippet_completions(
13706    project: &Project,
13707    buffer: &Model<Buffer>,
13708    buffer_position: text::Anchor,
13709    cx: &mut AppContext,
13710) -> Task<Result<Vec<Completion>>> {
13711    let language = buffer.read(cx).language_at(buffer_position);
13712    let language_name = language.as_ref().map(|language| language.lsp_id());
13713    let snippet_store = project.snippets().read(cx);
13714    let snippets = snippet_store.snippets_for(language_name, cx);
13715
13716    if snippets.is_empty() {
13717        return Task::ready(Ok(vec![]));
13718    }
13719    let snapshot = buffer.read(cx).text_snapshot();
13720    let chars: String = snapshot
13721        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13722        .collect();
13723
13724    let scope = language.map(|language| language.default_scope());
13725    let executor = cx.background_executor().clone();
13726
13727    cx.background_executor().spawn(async move {
13728        let classifier = CharClassifier::new(scope).for_completion(true);
13729        let mut last_word = chars
13730            .chars()
13731            .take_while(|c| classifier.is_word(*c))
13732            .collect::<String>();
13733        last_word = last_word.chars().rev().collect();
13734
13735        if last_word.is_empty() {
13736            return Ok(vec![]);
13737        }
13738
13739        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13740        let to_lsp = |point: &text::Anchor| {
13741            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13742            point_to_lsp(end)
13743        };
13744        let lsp_end = to_lsp(&buffer_position);
13745
13746        let candidates = snippets
13747            .iter()
13748            .enumerate()
13749            .flat_map(|(ix, snippet)| {
13750                snippet
13751                    .prefix
13752                    .iter()
13753                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13754            })
13755            .collect::<Vec<StringMatchCandidate>>();
13756
13757        let mut matches = fuzzy::match_strings(
13758            &candidates,
13759            &last_word,
13760            last_word.chars().any(|c| c.is_uppercase()),
13761            100,
13762            &Default::default(),
13763            executor,
13764        )
13765        .await;
13766
13767        // Remove all candidates where the query's start does not match the start of any word in the candidate
13768        if let Some(query_start) = last_word.chars().next() {
13769            matches.retain(|string_match| {
13770                split_words(&string_match.string).any(|word| {
13771                    // Check that the first codepoint of the word as lowercase matches the first
13772                    // codepoint of the query as lowercase
13773                    word.chars()
13774                        .flat_map(|codepoint| codepoint.to_lowercase())
13775                        .zip(query_start.to_lowercase())
13776                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13777                })
13778            });
13779        }
13780
13781        let matched_strings = matches
13782            .into_iter()
13783            .map(|m| m.string)
13784            .collect::<HashSet<_>>();
13785
13786        let result: Vec<Completion> = snippets
13787            .into_iter()
13788            .filter_map(|snippet| {
13789                let matching_prefix = snippet
13790                    .prefix
13791                    .iter()
13792                    .find(|prefix| matched_strings.contains(*prefix))?;
13793                let start = as_offset - last_word.len();
13794                let start = snapshot.anchor_before(start);
13795                let range = start..buffer_position;
13796                let lsp_start = to_lsp(&start);
13797                let lsp_range = lsp::Range {
13798                    start: lsp_start,
13799                    end: lsp_end,
13800                };
13801                Some(Completion {
13802                    old_range: range,
13803                    new_text: snippet.body.clone(),
13804                    resolved: false,
13805                    label: CodeLabel {
13806                        text: matching_prefix.clone(),
13807                        runs: vec![],
13808                        filter_range: 0..matching_prefix.len(),
13809                    },
13810                    server_id: LanguageServerId(usize::MAX),
13811                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13812                    lsp_completion: lsp::CompletionItem {
13813                        label: snippet.prefix.first().unwrap().clone(),
13814                        kind: Some(CompletionItemKind::SNIPPET),
13815                        label_details: snippet.description.as_ref().map(|description| {
13816                            lsp::CompletionItemLabelDetails {
13817                                detail: Some(description.clone()),
13818                                description: None,
13819                            }
13820                        }),
13821                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13822                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13823                            lsp::InsertReplaceEdit {
13824                                new_text: snippet.body.clone(),
13825                                insert: lsp_range,
13826                                replace: lsp_range,
13827                            },
13828                        )),
13829                        filter_text: Some(snippet.body.clone()),
13830                        sort_text: Some(char::MAX.to_string()),
13831                        ..Default::default()
13832                    },
13833                    confirm: None,
13834                })
13835            })
13836            .collect();
13837
13838        Ok(result)
13839    })
13840}
13841
13842impl CompletionProvider for Model<Project> {
13843    fn completions(
13844        &self,
13845        buffer: &Model<Buffer>,
13846        buffer_position: text::Anchor,
13847        options: CompletionContext,
13848        cx: &mut ViewContext<Editor>,
13849    ) -> Task<Result<Vec<Completion>>> {
13850        self.update(cx, |project, cx| {
13851            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13852            let project_completions = project.completions(buffer, buffer_position, options, cx);
13853            cx.background_executor().spawn(async move {
13854                let mut completions = project_completions.await?;
13855                let snippets_completions = snippets.await?;
13856                completions.extend(snippets_completions);
13857                Ok(completions)
13858            })
13859        })
13860    }
13861
13862    fn resolve_completions(
13863        &self,
13864        buffer: Model<Buffer>,
13865        completion_indices: Vec<usize>,
13866        completions: Rc<RefCell<Box<[Completion]>>>,
13867        cx: &mut ViewContext<Editor>,
13868    ) -> Task<Result<bool>> {
13869        self.update(cx, |project, cx| {
13870            project.lsp_store().update(cx, |lsp_store, cx| {
13871                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13872            })
13873        })
13874    }
13875
13876    fn apply_additional_edits_for_completion(
13877        &self,
13878        buffer: Model<Buffer>,
13879        completions: Rc<RefCell<Box<[Completion]>>>,
13880        completion_index: usize,
13881        push_to_history: bool,
13882        cx: &mut ViewContext<Editor>,
13883    ) -> Task<Result<Option<language::Transaction>>> {
13884        self.update(cx, |project, cx| {
13885            project.lsp_store().update(cx, |lsp_store, cx| {
13886                lsp_store.apply_additional_edits_for_completion(
13887                    buffer,
13888                    completions,
13889                    completion_index,
13890                    push_to_history,
13891                    cx,
13892                )
13893            })
13894        })
13895    }
13896
13897    fn is_completion_trigger(
13898        &self,
13899        buffer: &Model<Buffer>,
13900        position: language::Anchor,
13901        text: &str,
13902        trigger_in_words: bool,
13903        cx: &mut ViewContext<Editor>,
13904    ) -> bool {
13905        let mut chars = text.chars();
13906        let char = if let Some(char) = chars.next() {
13907            char
13908        } else {
13909            return false;
13910        };
13911        if chars.next().is_some() {
13912            return false;
13913        }
13914
13915        let buffer = buffer.read(cx);
13916        let snapshot = buffer.snapshot();
13917        if !snapshot.settings_at(position, cx).show_completions_on_input {
13918            return false;
13919        }
13920        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13921        if trigger_in_words && classifier.is_word(char) {
13922            return true;
13923        }
13924
13925        buffer.completion_triggers().contains(text)
13926    }
13927}
13928
13929impl SemanticsProvider for Model<Project> {
13930    fn hover(
13931        &self,
13932        buffer: &Model<Buffer>,
13933        position: text::Anchor,
13934        cx: &mut AppContext,
13935    ) -> Option<Task<Vec<project::Hover>>> {
13936        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13937    }
13938
13939    fn document_highlights(
13940        &self,
13941        buffer: &Model<Buffer>,
13942        position: text::Anchor,
13943        cx: &mut AppContext,
13944    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13945        Some(self.update(cx, |project, cx| {
13946            project.document_highlights(buffer, position, cx)
13947        }))
13948    }
13949
13950    fn definitions(
13951        &self,
13952        buffer: &Model<Buffer>,
13953        position: text::Anchor,
13954        kind: GotoDefinitionKind,
13955        cx: &mut AppContext,
13956    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13957        Some(self.update(cx, |project, cx| match kind {
13958            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13959            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13960            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13961            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13962        }))
13963    }
13964
13965    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13966        // TODO: make this work for remote projects
13967        self.read(cx)
13968            .language_servers_for_local_buffer(buffer.read(cx), cx)
13969            .any(
13970                |(_, server)| match server.capabilities().inlay_hint_provider {
13971                    Some(lsp::OneOf::Left(enabled)) => enabled,
13972                    Some(lsp::OneOf::Right(_)) => true,
13973                    None => false,
13974                },
13975            )
13976    }
13977
13978    fn inlay_hints(
13979        &self,
13980        buffer_handle: Model<Buffer>,
13981        range: Range<text::Anchor>,
13982        cx: &mut AppContext,
13983    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13984        Some(self.update(cx, |project, cx| {
13985            project.inlay_hints(buffer_handle, range, cx)
13986        }))
13987    }
13988
13989    fn resolve_inlay_hint(
13990        &self,
13991        hint: InlayHint,
13992        buffer_handle: Model<Buffer>,
13993        server_id: LanguageServerId,
13994        cx: &mut AppContext,
13995    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13996        Some(self.update(cx, |project, cx| {
13997            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13998        }))
13999    }
14000
14001    fn range_for_rename(
14002        &self,
14003        buffer: &Model<Buffer>,
14004        position: text::Anchor,
14005        cx: &mut AppContext,
14006    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14007        Some(self.update(cx, |project, cx| {
14008            let buffer = buffer.clone();
14009            let task = project.prepare_rename(buffer.clone(), position, cx);
14010            cx.spawn(|_, mut cx| async move {
14011                Ok(match task.await? {
14012                    PrepareRenameResponse::Success(range) => Some(range),
14013                    PrepareRenameResponse::InvalidPosition => None,
14014                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14015                        // Fallback on using TreeSitter info to determine identifier range
14016                        buffer.update(&mut cx, |buffer, _| {
14017                            let snapshot = buffer.snapshot();
14018                            let (range, kind) = snapshot.surrounding_word(position);
14019                            if kind != Some(CharKind::Word) {
14020                                return None;
14021                            }
14022                            Some(
14023                                snapshot.anchor_before(range.start)
14024                                    ..snapshot.anchor_after(range.end),
14025                            )
14026                        })?
14027                    }
14028                })
14029            })
14030        }))
14031    }
14032
14033    fn perform_rename(
14034        &self,
14035        buffer: &Model<Buffer>,
14036        position: text::Anchor,
14037        new_name: String,
14038        cx: &mut AppContext,
14039    ) -> Option<Task<Result<ProjectTransaction>>> {
14040        Some(self.update(cx, |project, cx| {
14041            project.perform_rename(buffer.clone(), position, new_name, cx)
14042        }))
14043    }
14044}
14045
14046fn inlay_hint_settings(
14047    location: Anchor,
14048    snapshot: &MultiBufferSnapshot,
14049    cx: &mut ViewContext<Editor>,
14050) -> InlayHintSettings {
14051    let file = snapshot.file_at(location);
14052    let language = snapshot.language_at(location).map(|l| l.name());
14053    language_settings(language, file, cx).inlay_hints
14054}
14055
14056fn consume_contiguous_rows(
14057    contiguous_row_selections: &mut Vec<Selection<Point>>,
14058    selection: &Selection<Point>,
14059    display_map: &DisplaySnapshot,
14060    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14061) -> (MultiBufferRow, MultiBufferRow) {
14062    contiguous_row_selections.push(selection.clone());
14063    let start_row = MultiBufferRow(selection.start.row);
14064    let mut end_row = ending_row(selection, display_map);
14065
14066    while let Some(next_selection) = selections.peek() {
14067        if next_selection.start.row <= end_row.0 {
14068            end_row = ending_row(next_selection, display_map);
14069            contiguous_row_selections.push(selections.next().unwrap().clone());
14070        } else {
14071            break;
14072        }
14073    }
14074    (start_row, end_row)
14075}
14076
14077fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14078    if next_selection.end.column > 0 || next_selection.is_empty() {
14079        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14080    } else {
14081        MultiBufferRow(next_selection.end.row)
14082    }
14083}
14084
14085impl EditorSnapshot {
14086    pub fn remote_selections_in_range<'a>(
14087        &'a self,
14088        range: &'a Range<Anchor>,
14089        collaboration_hub: &dyn CollaborationHub,
14090        cx: &'a AppContext,
14091    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14092        let participant_names = collaboration_hub.user_names(cx);
14093        let participant_indices = collaboration_hub.user_participant_indices(cx);
14094        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14095        let collaborators_by_replica_id = collaborators_by_peer_id
14096            .iter()
14097            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14098            .collect::<HashMap<_, _>>();
14099        self.buffer_snapshot
14100            .selections_in_range(range, false)
14101            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14102                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14103                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14104                let user_name = participant_names.get(&collaborator.user_id).cloned();
14105                Some(RemoteSelection {
14106                    replica_id,
14107                    selection,
14108                    cursor_shape,
14109                    line_mode,
14110                    participant_index,
14111                    peer_id: collaborator.peer_id,
14112                    user_name,
14113                })
14114            })
14115    }
14116
14117    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14118        self.display_snapshot.buffer_snapshot.language_at(position)
14119    }
14120
14121    pub fn is_focused(&self) -> bool {
14122        self.is_focused
14123    }
14124
14125    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14126        self.placeholder_text.as_ref()
14127    }
14128
14129    pub fn scroll_position(&self) -> gpui::Point<f32> {
14130        self.scroll_anchor.scroll_position(&self.display_snapshot)
14131    }
14132
14133    fn gutter_dimensions(
14134        &self,
14135        font_id: FontId,
14136        font_size: Pixels,
14137        em_width: Pixels,
14138        em_advance: Pixels,
14139        max_line_number_width: Pixels,
14140        cx: &AppContext,
14141    ) -> GutterDimensions {
14142        if !self.show_gutter {
14143            return GutterDimensions::default();
14144        }
14145        let descent = cx.text_system().descent(font_id, font_size);
14146
14147        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14148            matches!(
14149                ProjectSettings::get_global(cx).git.git_gutter,
14150                Some(GitGutterSetting::TrackedFiles)
14151            )
14152        });
14153        let gutter_settings = EditorSettings::get_global(cx).gutter;
14154        let show_line_numbers = self
14155            .show_line_numbers
14156            .unwrap_or(gutter_settings.line_numbers);
14157        let line_gutter_width = if show_line_numbers {
14158            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14159            let min_width_for_number_on_gutter = em_advance * 4.0;
14160            max_line_number_width.max(min_width_for_number_on_gutter)
14161        } else {
14162            0.0.into()
14163        };
14164
14165        let show_code_actions = self
14166            .show_code_actions
14167            .unwrap_or(gutter_settings.code_actions);
14168
14169        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14170
14171        let git_blame_entries_width =
14172            self.git_blame_gutter_max_author_length
14173                .map(|max_author_length| {
14174                    // Length of the author name, but also space for the commit hash,
14175                    // the spacing and the timestamp.
14176                    let max_char_count = max_author_length
14177                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14178                        + 7 // length of commit sha
14179                        + 14 // length of max relative timestamp ("60 minutes ago")
14180                        + 4; // gaps and margins
14181
14182                    em_advance * max_char_count
14183                });
14184
14185        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14186        left_padding += if show_code_actions || show_runnables {
14187            em_width * 3.0
14188        } else if show_git_gutter && show_line_numbers {
14189            em_width * 2.0
14190        } else if show_git_gutter || show_line_numbers {
14191            em_width
14192        } else {
14193            px(0.)
14194        };
14195
14196        let right_padding = if gutter_settings.folds && show_line_numbers {
14197            em_width * 4.0
14198        } else if gutter_settings.folds {
14199            em_width * 3.0
14200        } else if show_line_numbers {
14201            em_width
14202        } else {
14203            px(0.)
14204        };
14205
14206        GutterDimensions {
14207            left_padding,
14208            right_padding,
14209            width: line_gutter_width + left_padding + right_padding,
14210            margin: -descent,
14211            git_blame_entries_width,
14212        }
14213    }
14214
14215    pub fn render_crease_toggle(
14216        &self,
14217        buffer_row: MultiBufferRow,
14218        row_contains_cursor: bool,
14219        editor: View<Editor>,
14220        cx: &mut WindowContext,
14221    ) -> Option<AnyElement> {
14222        let folded = self.is_line_folded(buffer_row);
14223        let mut is_foldable = false;
14224
14225        if let Some(crease) = self
14226            .crease_snapshot
14227            .query_row(buffer_row, &self.buffer_snapshot)
14228        {
14229            is_foldable = true;
14230            match crease {
14231                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14232                    if let Some(render_toggle) = render_toggle {
14233                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14234                            if folded {
14235                                editor.update(cx, |editor, cx| {
14236                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14237                                });
14238                            } else {
14239                                editor.update(cx, |editor, cx| {
14240                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14241                                });
14242                            }
14243                        });
14244                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14245                    }
14246                }
14247            }
14248        }
14249
14250        is_foldable |= self.starts_indent(buffer_row);
14251
14252        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14253            Some(
14254                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14255                    .toggle_state(folded)
14256                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14257                        if folded {
14258                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14259                        } else {
14260                            this.fold_at(&FoldAt { buffer_row }, cx);
14261                        }
14262                    }))
14263                    .into_any_element(),
14264            )
14265        } else {
14266            None
14267        }
14268    }
14269
14270    pub fn render_crease_trailer(
14271        &self,
14272        buffer_row: MultiBufferRow,
14273        cx: &mut WindowContext,
14274    ) -> Option<AnyElement> {
14275        let folded = self.is_line_folded(buffer_row);
14276        if let Crease::Inline { render_trailer, .. } = self
14277            .crease_snapshot
14278            .query_row(buffer_row, &self.buffer_snapshot)?
14279        {
14280            let render_trailer = render_trailer.as_ref()?;
14281            Some(render_trailer(buffer_row, folded, cx))
14282        } else {
14283            None
14284        }
14285    }
14286}
14287
14288impl Deref for EditorSnapshot {
14289    type Target = DisplaySnapshot;
14290
14291    fn deref(&self) -> &Self::Target {
14292        &self.display_snapshot
14293    }
14294}
14295
14296#[derive(Clone, Debug, PartialEq, Eq)]
14297pub enum EditorEvent {
14298    InputIgnored {
14299        text: Arc<str>,
14300    },
14301    InputHandled {
14302        utf16_range_to_replace: Option<Range<isize>>,
14303        text: Arc<str>,
14304    },
14305    ExcerptsAdded {
14306        buffer: Model<Buffer>,
14307        predecessor: ExcerptId,
14308        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14309    },
14310    ExcerptsRemoved {
14311        ids: Vec<ExcerptId>,
14312    },
14313    BufferFoldToggled {
14314        ids: Vec<ExcerptId>,
14315        folded: bool,
14316    },
14317    ExcerptsEdited {
14318        ids: Vec<ExcerptId>,
14319    },
14320    ExcerptsExpanded {
14321        ids: Vec<ExcerptId>,
14322    },
14323    BufferEdited,
14324    Edited {
14325        transaction_id: clock::Lamport,
14326    },
14327    Reparsed(BufferId),
14328    Focused,
14329    FocusedIn,
14330    Blurred,
14331    DirtyChanged,
14332    Saved,
14333    TitleChanged,
14334    DiffBaseChanged,
14335    SelectionsChanged {
14336        local: bool,
14337    },
14338    ScrollPositionChanged {
14339        local: bool,
14340        autoscroll: bool,
14341    },
14342    Closed,
14343    TransactionUndone {
14344        transaction_id: clock::Lamport,
14345    },
14346    TransactionBegun {
14347        transaction_id: clock::Lamport,
14348    },
14349    Reloaded,
14350    CursorShapeChanged,
14351}
14352
14353impl EventEmitter<EditorEvent> for Editor {}
14354
14355impl FocusableView for Editor {
14356    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14357        self.focus_handle.clone()
14358    }
14359}
14360
14361impl Render for Editor {
14362    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14363        let settings = ThemeSettings::get_global(cx);
14364
14365        let mut text_style = match self.mode {
14366            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14367                color: cx.theme().colors().editor_foreground,
14368                font_family: settings.ui_font.family.clone(),
14369                font_features: settings.ui_font.features.clone(),
14370                font_fallbacks: settings.ui_font.fallbacks.clone(),
14371                font_size: rems(0.875).into(),
14372                font_weight: settings.ui_font.weight,
14373                line_height: relative(settings.buffer_line_height.value()),
14374                ..Default::default()
14375            },
14376            EditorMode::Full => TextStyle {
14377                color: cx.theme().colors().editor_foreground,
14378                font_family: settings.buffer_font.family.clone(),
14379                font_features: settings.buffer_font.features.clone(),
14380                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14381                font_size: settings.buffer_font_size(cx).into(),
14382                font_weight: settings.buffer_font.weight,
14383                line_height: relative(settings.buffer_line_height.value()),
14384                ..Default::default()
14385            },
14386        };
14387        if let Some(text_style_refinement) = &self.text_style_refinement {
14388            text_style.refine(text_style_refinement)
14389        }
14390
14391        let background = match self.mode {
14392            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14393            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14394            EditorMode::Full => cx.theme().colors().editor_background,
14395        };
14396
14397        EditorElement::new(
14398            cx.view(),
14399            EditorStyle {
14400                background,
14401                local_player: cx.theme().players().local(),
14402                text: text_style,
14403                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14404                syntax: cx.theme().syntax().clone(),
14405                status: cx.theme().status().clone(),
14406                inlay_hints_style: make_inlay_hints_style(cx),
14407                inline_completion_styles: make_suggestion_styles(cx),
14408                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14409            },
14410        )
14411    }
14412}
14413
14414impl ViewInputHandler for Editor {
14415    fn text_for_range(
14416        &mut self,
14417        range_utf16: Range<usize>,
14418        adjusted_range: &mut Option<Range<usize>>,
14419        cx: &mut ViewContext<Self>,
14420    ) -> Option<String> {
14421        let snapshot = self.buffer.read(cx).read(cx);
14422        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14423        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14424        if (start.0..end.0) != range_utf16 {
14425            adjusted_range.replace(start.0..end.0);
14426        }
14427        Some(snapshot.text_for_range(start..end).collect())
14428    }
14429
14430    fn selected_text_range(
14431        &mut self,
14432        ignore_disabled_input: bool,
14433        cx: &mut ViewContext<Self>,
14434    ) -> Option<UTF16Selection> {
14435        // Prevent the IME menu from appearing when holding down an alphabetic key
14436        // while input is disabled.
14437        if !ignore_disabled_input && !self.input_enabled {
14438            return None;
14439        }
14440
14441        let selection = self.selections.newest::<OffsetUtf16>(cx);
14442        let range = selection.range();
14443
14444        Some(UTF16Selection {
14445            range: range.start.0..range.end.0,
14446            reversed: selection.reversed,
14447        })
14448    }
14449
14450    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14451        let snapshot = self.buffer.read(cx).read(cx);
14452        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14453        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14454    }
14455
14456    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14457        self.clear_highlights::<InputComposition>(cx);
14458        self.ime_transaction.take();
14459    }
14460
14461    fn replace_text_in_range(
14462        &mut self,
14463        range_utf16: Option<Range<usize>>,
14464        text: &str,
14465        cx: &mut ViewContext<Self>,
14466    ) {
14467        if !self.input_enabled {
14468            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14469            return;
14470        }
14471
14472        self.transact(cx, |this, cx| {
14473            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14474                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14475                Some(this.selection_replacement_ranges(range_utf16, cx))
14476            } else {
14477                this.marked_text_ranges(cx)
14478            };
14479
14480            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14481                let newest_selection_id = this.selections.newest_anchor().id;
14482                this.selections
14483                    .all::<OffsetUtf16>(cx)
14484                    .iter()
14485                    .zip(ranges_to_replace.iter())
14486                    .find_map(|(selection, range)| {
14487                        if selection.id == newest_selection_id {
14488                            Some(
14489                                (range.start.0 as isize - selection.head().0 as isize)
14490                                    ..(range.end.0 as isize - selection.head().0 as isize),
14491                            )
14492                        } else {
14493                            None
14494                        }
14495                    })
14496            });
14497
14498            cx.emit(EditorEvent::InputHandled {
14499                utf16_range_to_replace: range_to_replace,
14500                text: text.into(),
14501            });
14502
14503            if let Some(new_selected_ranges) = new_selected_ranges {
14504                this.change_selections(None, cx, |selections| {
14505                    selections.select_ranges(new_selected_ranges)
14506                });
14507                this.backspace(&Default::default(), cx);
14508            }
14509
14510            this.handle_input(text, cx);
14511        });
14512
14513        if let Some(transaction) = self.ime_transaction {
14514            self.buffer.update(cx, |buffer, cx| {
14515                buffer.group_until_transaction(transaction, cx);
14516            });
14517        }
14518
14519        self.unmark_text(cx);
14520    }
14521
14522    fn replace_and_mark_text_in_range(
14523        &mut self,
14524        range_utf16: Option<Range<usize>>,
14525        text: &str,
14526        new_selected_range_utf16: Option<Range<usize>>,
14527        cx: &mut ViewContext<Self>,
14528    ) {
14529        if !self.input_enabled {
14530            return;
14531        }
14532
14533        let transaction = self.transact(cx, |this, cx| {
14534            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14535                let snapshot = this.buffer.read(cx).read(cx);
14536                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14537                    for marked_range in &mut marked_ranges {
14538                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14539                        marked_range.start.0 += relative_range_utf16.start;
14540                        marked_range.start =
14541                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14542                        marked_range.end =
14543                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14544                    }
14545                }
14546                Some(marked_ranges)
14547            } else if let Some(range_utf16) = range_utf16 {
14548                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14549                Some(this.selection_replacement_ranges(range_utf16, cx))
14550            } else {
14551                None
14552            };
14553
14554            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14555                let newest_selection_id = this.selections.newest_anchor().id;
14556                this.selections
14557                    .all::<OffsetUtf16>(cx)
14558                    .iter()
14559                    .zip(ranges_to_replace.iter())
14560                    .find_map(|(selection, range)| {
14561                        if selection.id == newest_selection_id {
14562                            Some(
14563                                (range.start.0 as isize - selection.head().0 as isize)
14564                                    ..(range.end.0 as isize - selection.head().0 as isize),
14565                            )
14566                        } else {
14567                            None
14568                        }
14569                    })
14570            });
14571
14572            cx.emit(EditorEvent::InputHandled {
14573                utf16_range_to_replace: range_to_replace,
14574                text: text.into(),
14575            });
14576
14577            if let Some(ranges) = ranges_to_replace {
14578                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14579            }
14580
14581            let marked_ranges = {
14582                let snapshot = this.buffer.read(cx).read(cx);
14583                this.selections
14584                    .disjoint_anchors()
14585                    .iter()
14586                    .map(|selection| {
14587                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14588                    })
14589                    .collect::<Vec<_>>()
14590            };
14591
14592            if text.is_empty() {
14593                this.unmark_text(cx);
14594            } else {
14595                this.highlight_text::<InputComposition>(
14596                    marked_ranges.clone(),
14597                    HighlightStyle {
14598                        underline: Some(UnderlineStyle {
14599                            thickness: px(1.),
14600                            color: None,
14601                            wavy: false,
14602                        }),
14603                        ..Default::default()
14604                    },
14605                    cx,
14606                );
14607            }
14608
14609            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14610            let use_autoclose = this.use_autoclose;
14611            let use_auto_surround = this.use_auto_surround;
14612            this.set_use_autoclose(false);
14613            this.set_use_auto_surround(false);
14614            this.handle_input(text, cx);
14615            this.set_use_autoclose(use_autoclose);
14616            this.set_use_auto_surround(use_auto_surround);
14617
14618            if let Some(new_selected_range) = new_selected_range_utf16 {
14619                let snapshot = this.buffer.read(cx).read(cx);
14620                let new_selected_ranges = marked_ranges
14621                    .into_iter()
14622                    .map(|marked_range| {
14623                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14624                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14625                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14626                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14627                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14628                    })
14629                    .collect::<Vec<_>>();
14630
14631                drop(snapshot);
14632                this.change_selections(None, cx, |selections| {
14633                    selections.select_ranges(new_selected_ranges)
14634                });
14635            }
14636        });
14637
14638        self.ime_transaction = self.ime_transaction.or(transaction);
14639        if let Some(transaction) = self.ime_transaction {
14640            self.buffer.update(cx, |buffer, cx| {
14641                buffer.group_until_transaction(transaction, cx);
14642            });
14643        }
14644
14645        if self.text_highlights::<InputComposition>(cx).is_none() {
14646            self.ime_transaction.take();
14647        }
14648    }
14649
14650    fn bounds_for_range(
14651        &mut self,
14652        range_utf16: Range<usize>,
14653        element_bounds: gpui::Bounds<Pixels>,
14654        cx: &mut ViewContext<Self>,
14655    ) -> Option<gpui::Bounds<Pixels>> {
14656        let text_layout_details = self.text_layout_details(cx);
14657        let gpui::Point {
14658            x: em_width,
14659            y: line_height,
14660        } = self.character_size(cx);
14661
14662        let snapshot = self.snapshot(cx);
14663        let scroll_position = snapshot.scroll_position();
14664        let scroll_left = scroll_position.x * em_width;
14665
14666        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14667        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14668            + self.gutter_dimensions.width
14669            + self.gutter_dimensions.margin;
14670        let y = line_height * (start.row().as_f32() - scroll_position.y);
14671
14672        Some(Bounds {
14673            origin: element_bounds.origin + point(x, y),
14674            size: size(em_width, line_height),
14675        })
14676    }
14677}
14678
14679trait SelectionExt {
14680    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14681    fn spanned_rows(
14682        &self,
14683        include_end_if_at_line_start: bool,
14684        map: &DisplaySnapshot,
14685    ) -> Range<MultiBufferRow>;
14686}
14687
14688impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14689    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14690        let start = self
14691            .start
14692            .to_point(&map.buffer_snapshot)
14693            .to_display_point(map);
14694        let end = self
14695            .end
14696            .to_point(&map.buffer_snapshot)
14697            .to_display_point(map);
14698        if self.reversed {
14699            end..start
14700        } else {
14701            start..end
14702        }
14703    }
14704
14705    fn spanned_rows(
14706        &self,
14707        include_end_if_at_line_start: bool,
14708        map: &DisplaySnapshot,
14709    ) -> Range<MultiBufferRow> {
14710        let start = self.start.to_point(&map.buffer_snapshot);
14711        let mut end = self.end.to_point(&map.buffer_snapshot);
14712        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14713            end.row -= 1;
14714        }
14715
14716        let buffer_start = map.prev_line_boundary(start).0;
14717        let buffer_end = map.next_line_boundary(end).0;
14718        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14719    }
14720}
14721
14722impl<T: InvalidationRegion> InvalidationStack<T> {
14723    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14724    where
14725        S: Clone + ToOffset,
14726    {
14727        while let Some(region) = self.last() {
14728            let all_selections_inside_invalidation_ranges =
14729                if selections.len() == region.ranges().len() {
14730                    selections
14731                        .iter()
14732                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14733                        .all(|(selection, invalidation_range)| {
14734                            let head = selection.head().to_offset(buffer);
14735                            invalidation_range.start <= head && invalidation_range.end >= head
14736                        })
14737                } else {
14738                    false
14739                };
14740
14741            if all_selections_inside_invalidation_ranges {
14742                break;
14743            } else {
14744                self.pop();
14745            }
14746        }
14747    }
14748}
14749
14750impl<T> Default for InvalidationStack<T> {
14751    fn default() -> Self {
14752        Self(Default::default())
14753    }
14754}
14755
14756impl<T> Deref for InvalidationStack<T> {
14757    type Target = Vec<T>;
14758
14759    fn deref(&self) -> &Self::Target {
14760        &self.0
14761    }
14762}
14763
14764impl<T> DerefMut for InvalidationStack<T> {
14765    fn deref_mut(&mut self) -> &mut Self::Target {
14766        &mut self.0
14767    }
14768}
14769
14770impl InvalidationRegion for SnippetState {
14771    fn ranges(&self) -> &[Range<Anchor>] {
14772        &self.ranges[self.active_index]
14773    }
14774}
14775
14776pub fn diagnostic_block_renderer(
14777    diagnostic: Diagnostic,
14778    max_message_rows: Option<u8>,
14779    allow_closing: bool,
14780    _is_valid: bool,
14781) -> RenderBlock {
14782    let (text_without_backticks, code_ranges) =
14783        highlight_diagnostic_message(&diagnostic, max_message_rows);
14784
14785    Arc::new(move |cx: &mut BlockContext| {
14786        let group_id: SharedString = cx.block_id.to_string().into();
14787
14788        let mut text_style = cx.text_style().clone();
14789        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14790        let theme_settings = ThemeSettings::get_global(cx);
14791        text_style.font_family = theme_settings.buffer_font.family.clone();
14792        text_style.font_style = theme_settings.buffer_font.style;
14793        text_style.font_features = theme_settings.buffer_font.features.clone();
14794        text_style.font_weight = theme_settings.buffer_font.weight;
14795
14796        let multi_line_diagnostic = diagnostic.message.contains('\n');
14797
14798        let buttons = |diagnostic: &Diagnostic| {
14799            if multi_line_diagnostic {
14800                v_flex()
14801            } else {
14802                h_flex()
14803            }
14804            .when(allow_closing, |div| {
14805                div.children(diagnostic.is_primary.then(|| {
14806                    IconButton::new("close-block", IconName::XCircle)
14807                        .icon_color(Color::Muted)
14808                        .size(ButtonSize::Compact)
14809                        .style(ButtonStyle::Transparent)
14810                        .visible_on_hover(group_id.clone())
14811                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14812                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14813                }))
14814            })
14815            .child(
14816                IconButton::new("copy-block", IconName::Copy)
14817                    .icon_color(Color::Muted)
14818                    .size(ButtonSize::Compact)
14819                    .style(ButtonStyle::Transparent)
14820                    .visible_on_hover(group_id.clone())
14821                    .on_click({
14822                        let message = diagnostic.message.clone();
14823                        move |_click, cx| {
14824                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14825                        }
14826                    })
14827                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14828            )
14829        };
14830
14831        let icon_size = buttons(&diagnostic)
14832            .into_any_element()
14833            .layout_as_root(AvailableSpace::min_size(), cx);
14834
14835        h_flex()
14836            .id(cx.block_id)
14837            .group(group_id.clone())
14838            .relative()
14839            .size_full()
14840            .block_mouse_down()
14841            .pl(cx.gutter_dimensions.width)
14842            .w(cx.max_width - cx.gutter_dimensions.full_width())
14843            .child(
14844                div()
14845                    .flex()
14846                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14847                    .flex_shrink(),
14848            )
14849            .child(buttons(&diagnostic))
14850            .child(div().flex().flex_shrink_0().child(
14851                StyledText::new(text_without_backticks.clone()).with_highlights(
14852                    &text_style,
14853                    code_ranges.iter().map(|range| {
14854                        (
14855                            range.clone(),
14856                            HighlightStyle {
14857                                font_weight: Some(FontWeight::BOLD),
14858                                ..Default::default()
14859                            },
14860                        )
14861                    }),
14862                ),
14863            ))
14864            .into_any_element()
14865    })
14866}
14867
14868fn inline_completion_edit_text(
14869    editor_snapshot: &EditorSnapshot,
14870    edits: &Vec<(Range<Anchor>, String)>,
14871    include_deletions: bool,
14872    cx: &WindowContext,
14873) -> InlineCompletionText {
14874    let edit_start = edits
14875        .first()
14876        .unwrap()
14877        .0
14878        .start
14879        .to_display_point(editor_snapshot);
14880
14881    let mut text = String::new();
14882    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14883    let mut highlights = Vec::new();
14884    for (old_range, new_text) in edits {
14885        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14886        text.extend(
14887            editor_snapshot
14888                .buffer_snapshot
14889                .chunks(offset..old_offset_range.start, false)
14890                .map(|chunk| chunk.text),
14891        );
14892        offset = old_offset_range.end;
14893
14894        let start = text.len();
14895        let color = if include_deletions && new_text.is_empty() {
14896            text.extend(
14897                editor_snapshot
14898                    .buffer_snapshot
14899                    .chunks(old_offset_range.start..offset, false)
14900                    .map(|chunk| chunk.text),
14901            );
14902            cx.theme().status().deleted_background
14903        } else {
14904            text.push_str(new_text);
14905            cx.theme().status().created_background
14906        };
14907        let end = text.len();
14908
14909        highlights.push((
14910            start..end,
14911            HighlightStyle {
14912                background_color: Some(color),
14913                ..Default::default()
14914            },
14915        ));
14916    }
14917
14918    let edit_end = edits
14919        .last()
14920        .unwrap()
14921        .0
14922        .end
14923        .to_display_point(editor_snapshot);
14924    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14925        .to_offset(editor_snapshot, Bias::Right);
14926    text.extend(
14927        editor_snapshot
14928            .buffer_snapshot
14929            .chunks(offset..end_of_line, false)
14930            .map(|chunk| chunk.text),
14931    );
14932
14933    InlineCompletionText::Edit {
14934        text: text.into(),
14935        highlights,
14936    }
14937}
14938
14939pub fn highlight_diagnostic_message(
14940    diagnostic: &Diagnostic,
14941    mut max_message_rows: Option<u8>,
14942) -> (SharedString, Vec<Range<usize>>) {
14943    let mut text_without_backticks = String::new();
14944    let mut code_ranges = Vec::new();
14945
14946    if let Some(source) = &diagnostic.source {
14947        text_without_backticks.push_str(source);
14948        code_ranges.push(0..source.len());
14949        text_without_backticks.push_str(": ");
14950    }
14951
14952    let mut prev_offset = 0;
14953    let mut in_code_block = false;
14954    let has_row_limit = max_message_rows.is_some();
14955    let mut newline_indices = diagnostic
14956        .message
14957        .match_indices('\n')
14958        .filter(|_| has_row_limit)
14959        .map(|(ix, _)| ix)
14960        .fuse()
14961        .peekable();
14962
14963    for (quote_ix, _) in diagnostic
14964        .message
14965        .match_indices('`')
14966        .chain([(diagnostic.message.len(), "")])
14967    {
14968        let mut first_newline_ix = None;
14969        let mut last_newline_ix = None;
14970        while let Some(newline_ix) = newline_indices.peek() {
14971            if *newline_ix < quote_ix {
14972                if first_newline_ix.is_none() {
14973                    first_newline_ix = Some(*newline_ix);
14974                }
14975                last_newline_ix = Some(*newline_ix);
14976
14977                if let Some(rows_left) = &mut max_message_rows {
14978                    if *rows_left == 0 {
14979                        break;
14980                    } else {
14981                        *rows_left -= 1;
14982                    }
14983                }
14984                let _ = newline_indices.next();
14985            } else {
14986                break;
14987            }
14988        }
14989        let prev_len = text_without_backticks.len();
14990        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14991        text_without_backticks.push_str(new_text);
14992        if in_code_block {
14993            code_ranges.push(prev_len..text_without_backticks.len());
14994        }
14995        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14996        in_code_block = !in_code_block;
14997        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14998            text_without_backticks.push_str("...");
14999            break;
15000        }
15001    }
15002
15003    (text_without_backticks.into(), code_ranges)
15004}
15005
15006fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15007    match severity {
15008        DiagnosticSeverity::ERROR => colors.error,
15009        DiagnosticSeverity::WARNING => colors.warning,
15010        DiagnosticSeverity::INFORMATION => colors.info,
15011        DiagnosticSeverity::HINT => colors.info,
15012        _ => colors.ignored,
15013    }
15014}
15015
15016pub fn styled_runs_for_code_label<'a>(
15017    label: &'a CodeLabel,
15018    syntax_theme: &'a theme::SyntaxTheme,
15019) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15020    let fade_out = HighlightStyle {
15021        fade_out: Some(0.35),
15022        ..Default::default()
15023    };
15024
15025    let mut prev_end = label.filter_range.end;
15026    label
15027        .runs
15028        .iter()
15029        .enumerate()
15030        .flat_map(move |(ix, (range, highlight_id))| {
15031            let style = if let Some(style) = highlight_id.style(syntax_theme) {
15032                style
15033            } else {
15034                return Default::default();
15035            };
15036            let mut muted_style = style;
15037            muted_style.highlight(fade_out);
15038
15039            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15040            if range.start >= label.filter_range.end {
15041                if range.start > prev_end {
15042                    runs.push((prev_end..range.start, fade_out));
15043                }
15044                runs.push((range.clone(), muted_style));
15045            } else if range.end <= label.filter_range.end {
15046                runs.push((range.clone(), style));
15047            } else {
15048                runs.push((range.start..label.filter_range.end, style));
15049                runs.push((label.filter_range.end..range.end, muted_style));
15050            }
15051            prev_end = cmp::max(prev_end, range.end);
15052
15053            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15054                runs.push((prev_end..label.text.len(), fade_out));
15055            }
15056
15057            runs
15058        })
15059}
15060
15061pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15062    let mut prev_index = 0;
15063    let mut prev_codepoint: Option<char> = None;
15064    text.char_indices()
15065        .chain([(text.len(), '\0')])
15066        .filter_map(move |(index, codepoint)| {
15067            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15068            let is_boundary = index == text.len()
15069                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15070                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15071            if is_boundary {
15072                let chunk = &text[prev_index..index];
15073                prev_index = index;
15074                Some(chunk)
15075            } else {
15076                None
15077            }
15078        })
15079}
15080
15081pub trait RangeToAnchorExt: Sized {
15082    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15083
15084    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15085        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15086        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15087    }
15088}
15089
15090impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15091    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15092        let start_offset = self.start.to_offset(snapshot);
15093        let end_offset = self.end.to_offset(snapshot);
15094        if start_offset == end_offset {
15095            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15096        } else {
15097            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15098        }
15099    }
15100}
15101
15102pub trait RowExt {
15103    fn as_f32(&self) -> f32;
15104
15105    fn next_row(&self) -> Self;
15106
15107    fn previous_row(&self) -> Self;
15108
15109    fn minus(&self, other: Self) -> u32;
15110}
15111
15112impl RowExt for DisplayRow {
15113    fn as_f32(&self) -> f32 {
15114        self.0 as f32
15115    }
15116
15117    fn next_row(&self) -> Self {
15118        Self(self.0 + 1)
15119    }
15120
15121    fn previous_row(&self) -> Self {
15122        Self(self.0.saturating_sub(1))
15123    }
15124
15125    fn minus(&self, other: Self) -> u32 {
15126        self.0 - other.0
15127    }
15128}
15129
15130impl RowExt for MultiBufferRow {
15131    fn as_f32(&self) -> f32 {
15132        self.0 as f32
15133    }
15134
15135    fn next_row(&self) -> Self {
15136        Self(self.0 + 1)
15137    }
15138
15139    fn previous_row(&self) -> Self {
15140        Self(self.0.saturating_sub(1))
15141    }
15142
15143    fn minus(&self, other: Self) -> u32 {
15144        self.0 - other.0
15145    }
15146}
15147
15148trait RowRangeExt {
15149    type Row;
15150
15151    fn len(&self) -> usize;
15152
15153    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15154}
15155
15156impl RowRangeExt for Range<MultiBufferRow> {
15157    type Row = MultiBufferRow;
15158
15159    fn len(&self) -> usize {
15160        (self.end.0 - self.start.0) as usize
15161    }
15162
15163    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15164        (self.start.0..self.end.0).map(MultiBufferRow)
15165    }
15166}
15167
15168impl RowRangeExt for Range<DisplayRow> {
15169    type Row = DisplayRow;
15170
15171    fn len(&self) -> usize {
15172        (self.end.0 - self.start.0) as usize
15173    }
15174
15175    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15176        (self.start.0..self.end.0).map(DisplayRow)
15177    }
15178}
15179
15180fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15181    if hunk.diff_base_byte_range.is_empty() {
15182        DiffHunkStatus::Added
15183    } else if hunk.row_range.is_empty() {
15184        DiffHunkStatus::Removed
15185    } else {
15186        DiffHunkStatus::Modified
15187    }
15188}
15189
15190/// If select range has more than one line, we
15191/// just point the cursor to range.start.
15192fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15193    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15194        range
15195    } else {
15196        range.start..range.start
15197    }
15198}
15199
15200pub struct KillRing(ClipboardItem);
15201impl Global for KillRing {}
15202
15203const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);